<?php  
namespace backend\controllers;

use backend\helpers\DateTimeHelper;
use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\CommissionLog;
use backend\models\CommissionTicket;
use backend\models\Member;
use backend\models\Mt4Trades;
use backend\models\UserMember;
use Yii;
use backend\models\Commission; 

class CommissionController extends BaseController
{
    
    /**
     * 返佣规则
     */
    public function actionRule()
    {
        $member_id = Yii::$app->request->post('member_id');
        $login = (int) Yii::$app->request->post('login');
        $model = new Commission();
        $list = $model->getCommissionByMemberIdAndLogins($member_id, [$login]);
        if (!empty($list[$login])) {
            return $this->outJson(1, $list[$login]);
        } else {
            return $this->outJson(0);
        }
    }

    /**
     * 已返佣设置
     * @return \yii\web\Response
     */
    public function actionSetHadComm()
    {
        $login = intval(Yii::$app->getRequest()->post('login'));
        if ($login <= 0) {
            return $this->outJson(0, [], '未指定数据对象');
        }
        $trades = Mt4Trades::findAllCloseTrade($login);
        if ($trades) {
            while ($pieces = array_splice($trades, 0, 1000)) {
                $rows = [];
                foreach ($pieces as $piece) {
                    $rows[] = [
                        'ticket' => $piece['TICKET'],
                        'type' => 1,
                    ];
                }
                if ($rows) {
                    $command = Mt4Trades::getDb()->createCommand();
                    $columns = array_combine(array_keys($rows[0]), array_keys($rows[0]));
                    $sql = $command->batchInsert(CommissionTicket::tableName(), $columns, $rows)->getSql();
                    $command->setSql(str_ireplace("INSERT INTO", "INSERT IGNORE INTO", $sql))->execute();
                }
            }
        }
        return $this->outJson(1, [], '操作成功');
    }

    /**
     * 开启自动返佣
     * @return \yii\web\Response
     */
    public function actionSetIsCommissionRun()
    {
        $login = intval(Yii::$app->getRequest()->post('login'));
        $run = trim(Yii::$app->getRequest()->post('run'));
        if ($login <= 0) {
            return $this->outJson(0, [], '未指定数据对象');
        }
        if (!is_numeric($run) || !in_array($run, [0, 1])) {
            return $this->outJson(0, [], '参数非法');
        }
        $userMember = UserMember::findByLogin($login);
        if ($userMember == null) {
            return $this->outJson(0, [], '数据不存在');
        }
        $userMember->is_commission_run = $run;
        if ($userMember->save()) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], '操作失败');
        }
    }

    /**
     * 取消上级代理
     * @return \yii\web\Response
     */
    public function actionDelIb()
    {
        $login = intval(Yii::$app->getRequest()->post('login'));
        if ($login <= 0) {
            return $this->outJson(0, [], '未指定数据对象');
        }
        $userMember = UserMember::findByLogin($login);
        if ($userMember == null) {
            return $this->outJson(0, [], '数据不存在');
        }
        if ($userMember->delete()) {
            Commission::deleteCommissionsByLogin($userMember->login);
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], '操作失败');
        }
    }

    /**
     * 批量设置返佣规则
     */
    public function actionBatchSet()
    {
        $model = new Commission();
        $result = $model->batchSet(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 设置所属代理
     * @return \yii\web\Response
     */
    public function actionSetIb()
    {
        $login = intval(Yii::$app->getRequest()->post('login'));
        $memberId = intval(Yii::$app->getRequest()->post('memberId'));
        if ($login <= 0 || $memberId <= 0) {
            return $this->outJson(0, [], '参数非法');
        }
        $member = Member::findById($memberId);
        if ($member == null) {
            return $this->outJson(0, [], '所属代理不存在');
        }
        $userMember = UserMember::findByLogin($login);
        if ($userMember == null) {
            // 未设置所属代理
            $userMember = new UserMember();
            $userMember->login = $login;
        }
        $userMember->member_id = $memberId;
        $userMember->name = $member['name'];
        $userMember->in_time = intval(microtime(true) * 1000);
        if ($userMember->save()) {
            Commission::deleteCommissionsByLogin($login);
            return $this->outJson(1, $userMember->getAttributes());
        } else {
            return $this->outJson(0, [], $userMember->getErrors());
        }
    }

    /**
     * 返佣规则
     * @return \yii\web\Response
     */
    public function actionDetail()
    {
        $login = intval(Yii::$app->getRequest()->get('login'));
        if ($login <= 0) {
            return $this->outJson(0, [], '参数非法');
        }
        $userMember = UserMember::findByLogin($login);
        if ($userMember == null) {
            return $this->outJson(0, [], '数据为空');
        }
        $member = Member::findById($userMember['member_id']);
        $parents = [];
        if ($member != null) {
            $parents = Member::findParents($member['id']);
            foreach ($parents as &$parent) {
                $parent['comm'] = Commission::findByCommission($login, $parent['id']);
            }
        }
        return $this->outJson(1, $parents);
    }

    /**
     * 设置返佣规则
     * @return \yii\web\Response
     */
    public function actionSetCommission()
    {
        $login = intval(Yii::$app->getRequest()->post('login'));
        $userId = intval(Yii::$app->getRequest()->post('userId'));
        if ($login <= 0) {
            return $this->outJson(0, [], '参数非法');
        }
        Commission::deleteCommissionsByLogin($login);
        $userMember = UserMember::findByLogin($login);
        if ($userMember != null) {
            $parents = Member::findParents($userMember['member_id']);
            foreach ((array)$parents as $parent) {
                $f = floatval(Yii::$app->getRequest()->post("f{$parent['id']}", 0)); // 外汇
                $m = floatval(Yii::$app->getRequest()->post("m{$parent['id']}", 0)); // 贵金属
                $c = floatval(Yii::$app->getRequest()->post("c{$parent['id']}", 0)); // 原油
                $h = floatval(Yii::$app->getRequest()->post("h{$parent['id']}", 0)); // 黄金
                $b = floatval(Yii::$app->getRequest()->post("b{$parent['id']}", 0)); // 白银
                $wy = floatval(Yii::$app->getRequest()->post("wy{$parent['id']}", 0)); // 外佣
                $g = floatval(Yii::$app->getRequest()->post("g{$parent['id']}", 0)); // 股指
                $bt = floatval(Yii::$app->getRequest()->post("bt{$parent['id']}", 0)); // 比特币

                $commission = new Commission();
                $commission->login = $login;
                $commission->member_id = $parent['id'];
                $commission->forex = $f;
                $commission->metal = $m;
                $commission->cfd = $c;
                $commission->gold = $h;
                $commission->silver = $b;
                $commission->wy = $wy;
                $commission->stock = $g;
                $commission->btc = $bt;
                $commission->in_time = intval(microtime(true) * 1000);
                if ($commission->save()) {
                    $commissionLog = new CommissionLog();
                    $commissionLog->login = $login;
                    $commissionLog->member_id = $parent['id'];
                    $commissionLog->type = 'no';
                    $commissionLog->forex = $f;
                    $commissionLog->metal = $m;
                    $commissionLog->cfd = $c;
                    $commissionLog->gold = $h;
                    $commissionLog->silver = $b;
                    $commissionLog->wy = $wy;
                    $commissionLog->stock = $g;
                    $commissionLog->btc = $bt;
                    $commissionLog->modify_user = $userId;
                    $commissionLog->in_time = DateTimeHelper::microtime_float();
                    $commissionLog->save();
                }
            }
        }
        return $this->outJson(1, [], '操作成功');
    }

    /**
     * 获取返佣规则记录log
     */
    public function actionGetCommissionLog()
    {
        $data = Yii::$app->getRequest()->get();
        $data['memberId'] = isset($data['memberId']) ? intval($data['memberId']) : '';
        $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']) : 'in_time desc';

        $data = ValidatorHelper::validateData($data, [
            ['search', 'string'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }

        $query = CommissionLog::find()->alias('a')
            ->select('a.id,a.login,a.member_id,a.type,a.forex,a.metal,a.cfd,a.gold,a.silver,a.wy,a.stock,a.btc,a.in_time,b.name')
            ->leftJoin('crm_member as b', 'a.modify_user = b.id')
            ->where(['member_id' => $data['memberId']])
            ->orderBy($data['orderBy']);
        if (!empty($data['search'])) {
            $query->andFilterWhere(['like', 'a.member_id', $data['search']]);
        }
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        return $this->outJson(1, $result);
    }
}