<?php
namespace backend\modules\ib\controllers;

use common\helpers\ExcelHelper;
use Yii;
use backend\models\MemberApi;
use backend\models\RebateApi;
use yii\helpers\Url;
use common\helpers\UserAgentHelper;

/**
 * 返佣报表
 */
class RebateController extends BaseController
{
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $ibId = (int) $request->get('ibId');
        $sTime = $request->get('sTime', ''); // 开始时间
        $eTime = $request->get('eTime', ''); // 结束时间
        
        $api = new MemberApi();
        $ibs = $api->getIbs()['data'];

        return $this->render('index', [
            'ibId' => $ibId,
            'sTime' => $sTime,
            'eTime' => $eTime,
            'ibs' => $ibs,
            'isHaveAdmin' => Yii::$app->user->identity->isHaveAdmin(),
        ]);
    }

    /**
     * 列表数据
     */
    public function actionList()
    {
        $get = Yii::$app->request->get();
        $orderInt = isset($get['order'][0]['column']) ? (int) $get['order'][0]['column'] : 1;
        $order = isset($get['columns'][$orderInt]['data']) ? $get['columns'][$orderInt]['data'] : '';
        $orderBy = isset($get['order'][0]['dir']) ? $get['order'][0]['dir'] : 'desc';
        $search = isset($get['search']['value']) ? $get['search']['value'] : '';
        
        $start = isset($get['start']) ? (int) $get['start'] : 0;
        $length = isset($get['length']) ? (int) $get['length'] : 20;
        $sTime = isset($get['sTime']) ? $get['sTime'] : '';
        $eTime = isset($get['eTime']) ? $get['eTime'] : '';
        $ibId = isset($get['ibId']) ? $get['ibId'] : 0;
        $draw = isset($get['draw']) ? $get['draw'] : 1;
        
        $params = [
            'order' => $order,
            'orderBy' => $orderBy,
            'search' => $search,
            'start' => $start,
            'length' => $length,
            'sTime' => $sTime,
            'eTime' => $eTime,
            'ibId' => $ibId,
            'draw' => $draw,
        ];

        if ($params['length'] > 5000) {
            if (Yii::$app->getRequest()->getIsAjax()) {
                Yii::$app->getResponse()->redirect(Url::current(), UserAgentHelper::isIE() ? 200 : 302);
            } else {
                $this->exportXls($params);
            }
            Yii::$app->end();
        }
        
        $api = new RebateApi();
        $result = $api->getList($params);
        echo json_encode($result['data']);
    }

    /**
     * @param array $params
     */
    protected function exportXls($params)
    {
        ExcelHelper::init();
        $attachmentName = Yii::$app->user->identity->name . "_返佣报表_" . date('Y-m-d') . '.xlsx';
        $header = ['订单号', '姓名', '账户', '类型', '手数', '规则', '佣金', '时间'];
        $source = [];
        $summaryRow = [];
        $api = new RebateApi();
        $tradeTypeMap = [
            0 => 'FOREX',
            1 => 'CFD',
            2 => 'XAU',
            3 => 'XAG',
        ];
        $params['length'] = 5000;
        while (true) {
            $result = $api->getList($params);
            if ($result['code'] == 1 && !empty($result['data']['data'])) {
                foreach ((array)$result['data']['data'] as $key => $row) {
                    $tradeType = isset($tradeTypeMap[$row['trade_type']]) ? $tradeTypeMap[$row['trade_type']] : '';
                    $inTime = $row['in_time'] ? date('m/d H:i', $row['in_time'] / 1000) : '';
                    $arr = [];
                    $arr[] = $row['trade_ticket'];
                    $arr[] = $row['name'];
                    $arr[] = $row['user_login'];
                    $arr[] = $tradeType;
                    $arr[] = $row['trade_volume'];
                    $arr[] = $row['commission_rule'];
                    $arr[] = $row['commission'];
                    $arr[] = $inTime;
                    $source[] = $arr;
                }
                $summaryRow = array_pop($source);
            } else {
                break;
            }
            $params['start'] += $params['length'];
            if ($params['start'] >= $result['data']['recordsTotal']) {
                break;
            }
        }
        $source[] = $summaryRow;
        ExcelHelper::output($source, $header, $attachmentName);
    }
    
}