<?php

namespace frontend\controllers;

use Yii;
use frontend\models\LottoRecord;
use backend\helpers\DateTimeHelper;

class LottoRecordController extends BaseController
{
    /**
     * 中奖记录
     */
    public function actionList()
    {
        $post = Yii::$app->request->post();
        $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;
        $activityType = isset($post['activityType']) ? $post['activityType'] : 0;

        // 搜索
        $where = ['and'];
        if ($search) {
            $where[] = ['like', 'mobile', $search];
        }
        if ($activityType) {
            $where[] = ['=', 'activity_type', $activityType];
        }

        // 排序
        $allowOrderColumn = ['id', 'mobile', 'lottery', 'activity_type', 'in_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 = LottoRecord::find();
        $query->where($where);
        $count = $query->count();
        
        $list = [];
        if ($count) {
            $list = $query->orderBy($orderCondition)->offset($start)->limit($length)->asArray()->all();
        }

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

        return $this->outJson(1, $data);
    }
    
    /**
     * 删除中奖记录
     */
    public function actionDelete()
    {
        $id = (int) Yii::$app->request->post('id');
        $model = LottoRecord::find()->where(['id' => $id])->limit(1)->one();
        if (!$model) {
            return $this->outJson(0, [], '参数错误');
        }
        $result = $model->delete();
        if ($result) {
            return $this->outJson(1);
        } else {
            return $this->outJson(0, [], '删除失败');
        }
    }
    
    /**
     * 新增
     */
    public function actionAdd()
    {
        $request = Yii::$app->getRequest()->post();
        $model = new LottoRecord();
        $model->in_time = DateTimeHelper::microtime_float();
        $model->setAttributes($request);
        if ($model->save()) {
            return $this->outJson(1, $model->id);
        } else {
            return $this->outJson(0, [], '保存失败!');
        }
    }
    
}