<?php
namespace backend\models\searches;

use backend\models\Mt4tradeApi;
use common\helpers\ExcelHelper;
use Yii;
use yii\data\ArrayDataProvider;
use yii\data\Pagination;
use yii\helpers\Url;
use common\helpers\UserAgentHelper;

class STradeSearch extends DataTable
{
    public $type;
    public $sTime;
    public $eTime;
    public $login;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['type', 'login'], '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'] = $this->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));

        if ($this->pageSize > 5000) {
            if (Yii::$app->getRequest()->getIsAjax()) {
                Yii::$app->getResponse()->redirect(Url::current(), UserAgentHelper::isIE() ? 200 : 302);
            } else {
                $this->exportXls($data);
            }
            Yii::$app->end();
        }

        $api = new Mt4tradeApi();
        $result = $api->getTradeList($data);
//        $result = $this->multiQuery($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;
    }

    /**
     * @param array $data
     */
    protected function exportXls($data)
    {
        ExcelHelper::init();
        $nameMap = [
            'deposit' => '入金',
            'withdraw' => '出金',
            'position' => '持仓',
            'history' => '历史',
            'pending' => '挂单',
            'credit' => '信用',
        ];
        $filename = isset($nameMap[$data['type']]) ? $nameMap[$data['type']] . '报表' : '交易报表';
        $attachmentName = Yii::$app->user->identity->name . "_{$filename}_" . date('Y-m-d') . '.xlsx';
        $header = [];
        if (in_array($data['type'], ['position', 'pending'])) {
            $header = ['订单号', '类型', '品种', 'SL', 'TP', '手数', '开仓价格', '开仓时间', '利息', '佣金', '获利'];
        } elseif (in_array($data['type'], ['history'])) {
            $header = ['订单号', '类型', '品种', 'SL', 'TP', '手数', '开仓价格', '开仓时间', '平仓价格', '平仓时间',
                '利息', '佣金', '获利'];
        } elseif (in_array($data['type'], ['deposit', 'withdraw'])) {
            $header = ['代理商', '金额', '时间'];
        }
        $source = [];
        $summaryRow = [];
        $api = new Mt4tradeApi();
        $cmdMap = [
            0 => 'BUY',
            1 => 'SELL',
            2 => 'BUY LIMIT',
            3 => 'SELL LIMIT',
            4 => 'BUY STOP',
            5 => 'SELL STOP',
            6 => 'BALANCE',
            7 => 'CREDIT',
        ];
        $data['pageSize'] = 5000;
        $data['page'] = 1;
        while (true) {
            $result = $api->getTradeList($data);
            if ($result['code'] == 1 && !empty($result['data']['dataList'])) {
                foreach ((array)$result['data']['dataList'] as $key => $row) {
                    $cmd = isset($cmdMap[$row['CMD']]) ? $cmdMap[$row['CMD']] : '';
                    $volume = $row['VOLUME'] / 100;
                    $arr = [];
                    if (in_array($data['type'], ['position', 'pending'])) {
                        $arr[] = $row['TICKET'];
                        $arr[] = $cmd;
                        $arr[] = $row['SYMBOL'];
                        $arr[] = $row['SL'];
                        $arr[] = $row['TP'];
                        $arr[] = $volume;
                        $arr[] = $row['OPEN_PRICE'];
                        $arr[] = $row['OPEN_TIME'];
                        $arr[] = $row['SWAPS'];
                        $arr[] = $row['COMMISSION'];
                        $arr[] = $row['PROFIT'];
                    } elseif (in_array($data['type'], ['history'])) {
                        $arr[] = $row['TICKET'];
                        $arr[] = $cmd;
                        $arr[] = $row['SYMBOL'];
                        $arr[] = $row['SL'];
                        $arr[] = $row['TP'];
                        $arr[] = $volume;
                        $arr[] = $row['OPEN_PRICE'];
                        $arr[] = $row['OPEN_TIME'];
                        $arr[] = $row['CLOSE_PRICE'];
                        $arr[] = $row['CLOSE_TIME'];
                        $arr[] = $row['SWAPS'];
                        $arr[] = $row['COMMISSION'];
                        $arr[] = $row['PROFIT'];
                    } elseif (in_array($data['type'], ['deposit', 'withdraw'])) {
                        $arr[] = $row['TICKET'];
                        $arr[] = $row['PROFIT'];
                        $arr[] = $row['OPEN_TIME'];
                    }
                    $source[] = $arr;
                }
                $summaryRow = array_pop($source);
            } else {
                break;
            }
            if ($data['page'] * $data['pageSize'] >= $result['data']['totalCount']) {
                break;
            }
            $data['page']++;
        }
        $source[] = $summaryRow;
        ExcelHelper::output($source, $header, $attachmentName);
    }

}