<?php
namespace backend\models\searches;

use backend\models\Mt4tradeApi;
use Yii;
use yii\data\ArrayDataProvider;
use yii\data\Pagination;

class TradeSearch extends DataTable
{
    public $type;
    public $sTime;
    public $eTime;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['type'], 'required'];
        $rules[] = [['sTime', 'eTime'], 'safe'];
        return $rules;
    }

    /**
     * @param array $params
     * @return ArrayDataProvider
     */
    public function search($params)
    {
        $this->setAttributes($params);
        // 初始化DataTable查询参数
        $this->initSearchParams();

        $pagination = new Pagination();
        $pagination->setPageSize($this->pageSize);
        $data['pageSize'] = $pagination->getPageSize();
        $data['page'] = $this->page;
        if ($this->orderBy) {
            $data['orderBy'] = $this->orderBy;
        }
        if (!empty($this->search['value']) && trim($this->search['value']) !== '') {
            $data['search'] = trim($this->search['value']);
        }
        $data['login'] = Yii::$app->getUser()->getIdentity(false)->getMain_login();
        $data['type'] = $this->type;
        $this->sTime && $data['closeTimeStart'] = date('Y-m-d 00:00:00', strtotime($this->sTime));
        $this->eTime && $data['closeTimeEnd'] = date('Y-m-d 23:59:59', strtotime($this->eTime));
        $api = new Mt4tradeApi();
        $result = $api->getTradeList($data);
        $models = [];
        if ($result['code'] == 1) {
            $models = (array)$result['data']['dataList'];
            $pagination->totalCount = $result['data']['totalCount'];
        }
        $dataProvider = new ArrayDataProvider([
            'models' => $models,
            'pagination' => $pagination,
            'totalCount' => $pagination->totalCount,
        ]);
        return $dataProvider;
    }
}