<?php 
namespace backend\controllers;

use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Member;
use backend\models\Mt4Trades;
use backend\models\Mt4Users;
use backend\models\UserMember;
use common\helpers\StringHelper;
use common\helpers\Utils;
use Yii;
use common\helpers\DateHelper;

class Mt4tradeController extends BaseController
{
    /*
	 * 获取总平仓单数
	 */
    public function actionGetHistoryTotalCount()
    {
        $login = Yii::$app->getRequest()->get('login');
        $count = Mt4Trades::countHistoryByLogin($login);
        return $this->outJson(1, $count, 'OK');
    }

    /*
     * 获取总平仓单数（赢钱）
     */
    public function actionGetHistoryWinCount()
    {
        $login = Yii::$app->getRequest()->get('login');
        $count = Mt4Trades::countWinHistoryByLogin($login);
        return $this->outJson(1, $count, 'OK');
    }

    /*
     * 获取总平仓单数（输钱）
     */
    public function actionGetHistoryLossCount()
    {
        $login = Yii::$app->getRequest()->get('login');
        $count = Mt4Trades::countLossHistoryByLogin($login);
        return $this->outJson(1, $count, 'OK');
    }

    /**
     * 每日收益图
     * @return \yii\web\Response
     */
    public function actionSumProfitByDay()
    {
        $login = Yii::$app->getRequest()->get('login');
        $mt4Trades = new Mt4Trades();
        $data = $mt4Trades->getProfitSumByDay($login);
        return $this->outJson(1, $data, 'OK');
    }

    /**
     * 交易手数
     * @return \yii\web\Response
     */
    public function actionVolumeSumByDay()
    {
        $login = Yii::$app->getRequest()->get('login');
        $mt4Trades = new Mt4Trades();
        $data = $mt4Trades->getVolumeSumByDay($login);
        return $this->outJson(1, $data, 'OK');
    }

    /**
     * 交易货币分布
     * @return \yii\web\Response
     */
    public function actionSymbolCount()
    {
        $login = Yii::$app->getRequest()->get('login');
        $mt4Trades = new Mt4Trades();
        $data = $mt4Trades->getSymbolCount($login);
        return $this->outJson(1, $data, 'OK');
    }

    /**
     * 交易来源分布
     * @return \yii\web\Response
     */
    public function actionReasonCount()
    {
        $login = Yii::$app->getRequest()->get('login');
        $mt4Trades = new Mt4Trades();
        $data = $mt4Trades->getReasonCount($login);
        return $this->outJson(1, $data, 'OK');
    }

    /**
     * 总入金 总出金
     * @return \yii\web\Response
     */
    public function actionSumProfit()
    {
        $data = Yii::$app->getRequest()->get();
        $data['type'] = isset($data['type']) ? trim($data['type']) : '';
        $data['login'] = isset($data['login']) ? trim($data['login']) : '';
        $data['closeTimeStart'] = isset($data['closeTimeStart']) ? trim($data['closeTimeStart']) : '';
        $data['closeTimeEnd'] = isset($data['closeTimeEnd']) ? trim($data['closeTimeEnd']) : '';
        $data = ValidatorHelper::validateData($data, [
            ['type', 'required'],
            ['login', 'integer'],
            ['closeTimeStart', 'string'],
            ['closeTimeEnd', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        $query = Mt4Trades::find();
        Mt4Trades::addTypeCondition($query, $data['type']);
        $query->andWhere(['LOGIN' => $data['login']]);
        $query->andFilterWhere(['>=', 'CLOSE_TIME', $data['closeTimeStart']]);
        $query->andFilterWhere(['<=', 'CLOSE_TIME', $data['closeTimeEnd']]);
        $profit = $query->sum('PROFIT');
        $profit = $profit ? $profit : 0;
        return $this->outJson(1, ['profit' => $profit]);
    }

    /**
     * 交易列表
     * @return \yii\web\Response
     */
    public function actionList()
    {
        $data = Yii::$app->getRequest()->get();
        $data['type'] = isset($data['type']) ? trim($data['type']) : '';
        $data['login'] = isset($data['login']) ? trim($data['login']) : '';
        $data['closeTimeStart'] = isset($data['closeTimeStart']) ? DateHelper::convertDateToGmt($data['closeTimeStart']) : '';
        $data['closeTimeEnd'] = isset($data['closeTimeEnd']) ? DateHelper::convertDateToGmt($data['closeTimeEnd']) : '';
        $data['search'] = isset($data['search']) ? trim($data['search']) : '';
        $data['page'] = isset($data['page']) ? max(intval($data['page']), 1) : 1;
        $data['pageSize'] = isset($data['pageSize']) ? intval($data['pageSize']) : 20;
        $data['orderBy'] = isset($data['orderBy']) ? trim($data['orderBy']) : 'TICKET desc';
        $data = ValidatorHelper::validateData($data, [
            ['type', 'required'],
            ['login', 'integer'],
            ['closeTimeStart', 'string'],
            ['closeTimeEnd', 'string'],
            ['search', 'string'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        $select = ['TICKET', 'LOGIN', 'CMD', 'SYMBOL', 'SL', 'TP', 'VOLUME', 'OPEN_PRICE', 'OPEN_TIME', 'CLOSE_PRICE', 'CLOSE_TIME', 'SWAPS', 'COMMISSION', 'PROFIT', 'MODIFY_TIME'];
        $query = Mt4Trades::find()->select($select)->orderBy($data['orderBy']);
        Mt4Trades::addTypeCondition($query, $data['type']);
        $query->andWhere(['LOGIN' => $data['login']]);
        $query->andFilterWhere(['>=', 'CLOSE_TIME', $data['closeTimeStart']]);
        $query->andFilterWhere(['<=', 'CLOSE_TIME', $data['closeTimeEnd']]);
        $query->andFilterWhere(['or', ['like', 'LOGIN', $data['search']], ['like', 'TICKET', $data['search']]]);
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        
        // 合计数据
        $sumData = Mt4Trades::findSum($data['login'], $data['type'], $data['closeTimeStart'], $data['closeTimeEnd'], $data['search']);
        $sumData["IBNAME"] = "";
        $sumData["LOGIN"] = "";
        $sumData["NAME"] = "";
        $sumData["TICKET"] = "";
        $sumData["CMD"] = "99";
        $sumData["SYMBOL"] = "";
        $sumData["SL"] = "";
        $sumData["TP"] = "";
        $sumData["VOLUME"] = $sumData['sv'];
        $sumData["OPEN_PRICE"] = "";
        $sumData["OPEN_TIME"] = "";
        $sumData["CLOSE_PRICE"] = "";
        $sumData["CLOSE_TIME"] = "";
        $sumData["SWAPS"] = Utils::formatFloatOrInt($sumData['ss']);
        $sumData["COMMISSION"] = Utils::formatFloatOrInt($sumData['sc']);
        $sumData["MODIFY_TIME"] = "";
        $sumData["SPROFIT"] = Utils::formatFloatOrInt($sumData['sp']);
        $sumData["PROFIT"] = Utils::formatFloatOrInt($sumData['sp']);
        $result['dataList'][] = $sumData;
        
        return $this->outJson(1, $result);
    }

    /**
     * 代理商 交易列表
     * @return \yii\web\Response
     */
    public function actionIbList()
    {
        $data = Yii::$app->getRequest()->get();
        $data['type'] = isset($data['type']) ? trim($data['type']) : '';
        $data['memberId'] = isset($data['memberId']) ? trim($data['memberId']) : '';
        $data['ibId'] = isset($data['ibId']) ? trim($data['ibId']) : '';
        $data['name'] = isset($data['name']) ? trim($data['name']) : '';
        $data['closeTimeStart'] = isset($data['closeTimeStart']) ? DateHelper::convertDateToGmt($data['closeTimeStart']) : '';
        $data['closeTimeEnd'] = isset($data['closeTimeEnd']) ? DateHelper::convertDateToGmt($data['closeTimeEnd']) : '';
        $data['search'] = isset($data['search']) ? trim($data['search']) : '';
        $data['page'] = isset($data['page']) ? max(intval($data['page']), 1) : 1;
        $data['pageSize'] = isset($data['pageSize']) ? intval($data['pageSize']) : 20;
        $data['orderBy'] = isset($data['orderBy']) ? trim($data['orderBy']) : 'TICKET desc';
        $data = ValidatorHelper::validateData($data, [
            ['type', 'required'],
            ['memberId', 'required'],
            ['memberId', 'integer'],
            ['ibId', 'integer'],
            ['name', 'string'],
            ['closeTimeStart', 'string'],
            ['closeTimeEnd', 'string'],
            ['search', 'string'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        /** @var Member $member */
        $member = Member::find()->where(['id' => $data['memberId']])->limit(1)->one();
        if ($member == null) {
            return $this->outJson(0, [], '用户不存在');
        }
        // 查询下级代理
        $children = $member->findChildrenIncludeSelf($member['id']);
        if ($data['ibId']) {
            $childrenTemp = [];
            foreach ($children as $child) {
                if ($child['id'] == $data['ibId']) {
                    $childrenTemp = $member->findChildrenIncludeSelf($child['id']);
                    break;
                }
            }
            $children = $childrenTemp;
            unset($childrenTemp);
        }
        $ids = [];
        foreach ($children as $child) {
            $ids[] = $child['id'];
        }
        $mt4Users = Mt4Users::find()->alias('u')->select('u.LOGIN,u.NAME,um.member_id')
            ->innerJoin(UserMember::tableName() . ' um', 'um.login=u.LOGIN')
            ->where(['um.member_id' => $ids])->andFilterWhere(['like', 'u.NAME', $data['name']])->asArray()->all();
        $userNames = [];
        $ibMemberIds = [];
        foreach ($mt4Users as $mt4User) {
            $userNames[$mt4User['LOGIN']] = $mt4User;
            $ibMemberIds[] = $mt4User['member_id'];
        }
        unset($mt4Users);
        $ibMembers = Member::find()->select('id,name')->where(['id' => $ibMemberIds])->asArray()->all();
        $ibMemberNames = [];
        foreach ($ibMembers as $key => $ibMember) {
            $ibMemberNames[$ibMember['id']] = $ibMember['name'];
        }
        unset($ibMembers);
        foreach ($userNames as $login => $mt4User) {
            $userNames[$login]['IBNAME'] = isset($ibMemberNames[$mt4User['member_id']]) ? $ibMemberNames[$mt4User['member_id']] : '';
        }
        $logins = array_keys($userNames);
        $select = ['TICKET', 'LOGIN', 'CMD', 'SYMBOL', 'SL', 'TP', 'VOLUME', 'OPEN_PRICE', 'OPEN_TIME', 'CLOSE_PRICE', 'CLOSE_TIME', 'SWAPS', 'COMMISSION', 'PROFIT', 'MODIFY_TIME', 'COMMENT'];
        if ($data['type'] == 'deposit' || $data['type'] == 'withdraw') {
            $select[] = 'SUM(PROFIT) as SPROFIT';
            $query = Mt4Trades::find()->select($select)->orderBy($data['orderBy'])->groupBy('LOGIN');
        } else {
            $query = Mt4Trades::find()->select($select)->orderBy($data['orderBy']);
        }
        Mt4Trades::addTypeCondition($query, $data['type']);
        $query->andWhere('LOGIN IN (' . StringHelper::buildInSql($logins) . ')');
        
        $query->andFilterWhere(['>=', 'CLOSE_TIME', $data['closeTimeStart']]);
        $query->andFilterWhere(['<=', 'CLOSE_TIME', $data['closeTimeEnd']]);
        $query->andFilterWhere(['or', ['like', 'LOGIN', $data['search']], ['like', 'TICKET', $data['search']]]);
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        foreach ($result['dataList'] as $key => &$row) {
            $row['SWAPS'] = Utils::formatFloatOrInt($row['SWAPS']);
            $row['PROFIT'] = Utils::formatFloatOrInt($row['PROFIT']);
            $row['COMMISSION'] = Utils::formatFloatOrInt($row['COMMISSION']);
            $row['SL'] = Utils::formatFloatOrInt($row['SL'], 5);
            $row['TP'] = Utils::formatFloatOrInt($row['TP'], 5);
            $row['OPEN_PRICE'] = Utils::formatFloatOrInt($row['OPEN_PRICE'], 5);
            $row['CLOSE_PRICE'] = Utils::formatFloatOrInt($row['CLOSE_PRICE'], 5);
            $row['CLOSE_PRICE'] = Utils::formatFloatOrInt($row['CLOSE_PRICE'], 5);
            if (array_key_exists('SPROFIT', $row)) {
                $row['SPROFIT'] = Utils::formatFloatOrInt($row['SPROFIT']);
            }
            $row['NAME'] = isset($userNames[$row['LOGIN']]['NAME']) ? $userNames[$row['LOGIN']]['NAME'] : '';
            $row['IBNAME'] = isset($userNames[$row['LOGIN']]['IBNAME']) ? $userNames[$row['LOGIN']]['IBNAME'] : '';
            $row['type'] = $row['COMMENT'] === 'deposit(ssac)' ? 'SSAC入金' : '银联入金';
        }
        
        $sumData = Mt4Trades::findSum($logins, $data['type'], $data['closeTimeStart'], $data['closeTimeEnd'], $data['search']);
        $sumData["IBNAME"] = "";
        $sumData["LOGIN"] = "";
        $sumData["NAME"] = "";
        $sumData["TICKET"] = "";
        $sumData["CMD"] = "99";
        $sumData["SYMBOL"] = "";
        $sumData["SL"] = "";
        $sumData["TP"] = "";
        $sumData["VOLUME"] = $sumData['sv'];
        $sumData["OPEN_PRICE"] = "";
        $sumData["OPEN_TIME"] = "";
        $sumData["CLOSE_PRICE"] = "";
        $sumData["CLOSE_TIME"] = "";
        $sumData["SWAPS"] = Utils::formatFloatOrInt($sumData['ss']);
        $sumData["COMMISSION"] = Utils::formatFloatOrInt($sumData['sc']);
        $sumData["MODIFY_TIME"] = "";
        $sumData["SPROFIT"] = Utils::formatFloatOrInt($sumData['sp']);
        $sumData["PROFIT"] = Utils::formatFloatOrInt($sumData['sp']);
        $sumData["type"] = "";
        $result['dataList'][] = $sumData;

        return $this->outJson(1, $result);
    }

    /**
     * 后台交易管理列表数据
     */
    public function actionAdminList()
    {
        $model = new Mt4Trades();
        $result = $model->getAdminList(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }
    
}

