<?php

namespace backend\models;

use Yii;

/**
 * @inheritdoc
 */
class AprilActivity extends \common\models\AprilActivity
{
    /**
     * 四月活动后台列表数据
     * @param array $post
     * @return array
     */
    public function getAprilList($post)
    {
        $result = ['code' => 0, 'data' => [], 'message' => ''];

        $order = isset($post['order']) ? strtolower($post['order']) : '';
        $orderBy = isset($post['orderBy']) ? strtolower($post['orderBy']) : 'desc';
        $search = isset($post['search']) ? $post['search'] : '';

        $start = isset($post['start']) ? (int) $post['start'] : 0;
        $length = isset($post['length']) ? (int) $post['length'] : 20;
        $draw = isset($post['draw']) ? $post['draw'] : 1;

        $where = ['and'];
        
        // 搜索
        if ($search) {
            if (filter_var($search, FILTER_VALIDATE_IP) !== false) {
                $where[] = ['=', 'ip', $search];
            } elseif (is_numeric($search)) {
                // 用户名也可能是数字
                $where[] = [
                    'or',
                    ['=', 'phone', $search],
                ];
            } else {
                $where[] = [
                    'or',
                    ['like', 'name', $search],
                ];
            }
        }

        // 排序
        $allowOrderColumn = ['id', 'name', 'phone', 'ip', 'create_time'];
        if (in_array($order, $allowOrderColumn) && in_array($orderBy, ['asc', 'desc'])) {
            if ($orderBy == 'asc') {
                $orderCondition = [$order => SORT_ASC];
            } else {
                $orderCondition = [$order => SORT_DESC];
            }
        } else {
            $orderCondition = ['id' => SORT_DESC];
        }

        $query = static::find();
        $query->where($where)
            ->orderBy($orderCondition);

        $count = $query->count();
        $query->offset($start)->limit($length);
        $list = $query->asArray()->all();
        
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }

        $data['data'] = $list;
        $data['draw'] = $draw;
        $data['recordsFiltered'] = $count;
        $data['recordsTotal'] = $count;

        $result['data'] = $data;
        $result['code'] = 1;

        return $result;
    }
}
