<?php
/**
 * Created by PhpStorm.
 * User: chenkuan
 * Date: 2017/12/15
 * Time: 下午3:13
 */

namespace frontend\models\searches;

use yii\base\Model;
use yii\data\BaseDataProvider;

class DataTable extends Model
{
    public $draw = 1;
    /**
     * [
     *   0 => ['data' => 'id', 'name' => '', 'searchable' => 'true', 'orderable' => 'true', 'search' => ['value' => '', 'regex' => 'false']],
     *   1 => ['data' => 'name', 'name' => '', 'searchable' => 'true', 'orderable' => 'true', 'search' => ['value' => '', 'regex' => 'false']],
     *   ...
     * ],
     * @var array
     */
    public $columns = [];
    /**
     * [
     *   0 => ['column' => '0', 'dir' => 'desc'],
     * ]
     * @var array
     */
    public $order = [];
    public $start = 0;
    public $length = 10;
    /**
     * ['value' => '', 'regex' => 'false']
     * @var array
     */
    public $search = [];

    protected $page;
    protected $pageSize;
    protected $orderBy;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['draw', 'start', 'length'], 'integer'],
            [['columns', 'order', 'search'], 'safe'],
        ];
    }

    /**
     * 初始化DataTable查询参数
     */
    protected function initSearchParams()
    {
        $length = intval($this->length);
        if ($length <= 0) {
            $length = 10;
        }
        $start = intval($this->start);
        if ($start <= 0) {
            $start = 0;
        }
        $this->pageSize = $length;
        // start=0 => page=1 start=20 page=2...
        $this->page = (int)ceil($start / $length) + 1;
        // 排序
        $columnIndex = isset($this->order[0]['column']) ? trim($this->order[0]['column']) : '';
        $column = isset($this->columns[$columnIndex]['data']) ? trim($this->columns[$columnIndex]['data']) : '';
        $dir = isset($this->order[0]['dir']) ? trim($this->order[0]['dir']) : '';
        if ($column != '' && $dir != '' && in_array(strtolower($dir), ['asc', 'desc'])) {
            $this->orderBy = $column . ' ' . $dir;
        }
    }

    /**
     * @param BaseDataProvider $dataProvider
     * @return array
     */
    public function outResult(BaseDataProvider $dataProvider)
    {
        return [
            'recordsFiltered' => $dataProvider->getTotalCount(),
            'data' => $dataProvider->getModels(),
            'draw' => $this->draw,
            'recordsTotal' => $dataProvider->getTotalCount(),
        ];
    }
}
