<?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 backend\models\Withdraw;
use common\helpers\RateHelper;
use common\helpers\Utils;
use common\lib\Mt4ManagerApi;
use Yii;
use backend\models\MemberBankInfo;
use common\lib\Mt4Deposit;

class WithdrawController extends BaseController
{
    /**
     * 出金记录
     * @return mixed
     */
    public function actionIndex()
    {
        $data = Yii::$app->getRequest()->get();
        $data['type'] = isset($data['type']) ? trim($data['type']) : '';
        $data['from'] = isset($data['from']) ? trim($data['from']) : '';
        $data['memberId'] = isset($data['memberId']) ? trim($data['memberId']) : '';
        $data['inTimeStart'] = isset($data['inTimeStart']) ? trim($data['inTimeStart']) : '';
        $data['inTimeEnd'] = isset($data['inTimeEnd']) ? trim($data['inTimeEnd']) : '';
        $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']) : 'id desc';
        $data = ValidatorHelper::validateData($data, [
            ['type', 'integer'],
            ['from', 'string'],
            ['memberId', 'integer'],
            ['inTimeStart', 'integer'],
            ['inTimeEnd', 'integer'],
            ['search', 'string'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        $query = Withdraw::find()->orderBy($data['orderBy']);
        $query->andFilterWhere(['type' => $data['type']]);
        if ($data['from'] == 'admin') {
            $query->andFilterWhere(['member_id' => $data['memberId']]);
        } else {
            $query->andWhere(['member_id' => $data['memberId']]);
        }
        $query->andFilterWhere(['>=', 'in_time', $data['inTimeStart']]);
        $query->andFilterWhere(['<', 'in_time', $data['inTimeEnd']]);
        $query->andFilterWhere(['or', ['like', 'true_name', $data['search']], ['like', 'login', $data['search']]]);
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        if ($data['from'] == 'admin') {
            $memberTypeCache = []; // 用户类型缓存
            $memberNameCache = []; // 用户名字缓存
            $ibNameCache = []; // 代理商名字缓存
            foreach ($result['dataList'] as &$row) {
                $row['rmb'] = Utils::formatFloatOrInt($row['amount'] * $row['rate']);
                $row['sk'] = Utils::formatFloatOrInt($row['amount'] + $row['fee']);
                if (!array_key_exists($row['member_id'], $memberTypeCache)) {
                    $member = Member::findById($row['member_id']);
                    if ($member == null) {
                        $memberTypeCache[$row['member_id']] = '';
                        $memberNameCache[$row['member_id']] = '';
                    } else {
                        $memberTypeCache[$row['member_id']] = $member['type'];
                        $memberNameCache[$row['member_id']] = $member['name'];
                    }
                }
                $row['memberType'] = $memberTypeCache[$row['member_id']];
                if (!array_key_exists($row['login'], $ibNameCache)) {
                    $userMember = UserMember::findByLogin($row['login']);
                    if ($userMember == null) {
                        $ibNameCache[$row['login']] = '';
                    } else {
                        if (!array_key_exists($userMember['member_id'], $memberNameCache)) {
                            $member = Member::findById($userMember['member_id']);
                            if ($member == null) {
                                $memberTypeCache[$userMember['member_id']] = '';
                                $memberNameCache[$userMember['member_id']] = '';
                            } else {
                                $memberTypeCache[$userMember['member_id']] = $member['type'];
                                $memberNameCache[$userMember['member_id']] = $member['name'];
                            }
                        }
                        $ibNameCache[$row['login']] = $memberNameCache[$userMember['member_id']];
                    }
                }
                $row['IBNAME'] = $ibNameCache[$row['login']];
            }
        }
        return $this->outJson(1, $result);
    }

    /**
     * 出金申请
     * @return \yii\web\Response
     */
    public function actionCreate()
    {
        $data = Yii::$app->getRequest()->post();
        $model = new Withdraw();
        foreach (['fee', 'in_time', 'out_time', 'rate', 'type'] as $field) {
            unset($data[$field]);
        }
        $rate = RateHelper::getRate();
        if (empty($rate['buyRate'])) {
            return $this->outJson(0, [], '汇率获取失败');
        }
        $data['rate'] = $rate['buyRate'];
        if (empty($data['member_id'])) {
            return $this->outJson(0, [], '用户ID不能为空');
        }
        if (empty($data['login'])) {
            return $this->outJson(0, [], 'mt4账户不能为空');
        }
        if (empty($data['amount']) || !is_numeric($data['amount']) || bccomp($data['amount'], '0.00', 2) <= 0) {
            return $this->outJson(0, [], '金额非法');
        }
        $member = Member::find()->where(['id' => $data['member_id']])->asArray()->limit(1)->one();
        if ($member == null) {
            return $this->outJson(0, [], '用户不存在');
        }
        $unDealList = Withdraw::getUnDealList($data['member_id']);
        if ($unDealList) {
            return $this->outJson(0, [], '您还有未处理的申请记录，请等待审核');
        }
        
        // 手续费
        $data['fee'] = Withdraw::getFee($data['amount'], $member);
        
        $mt4User = Mt4Users::find()->where(['LOGIN' => $data['login']])->asArray()->limit(1)->one();
        if ($mt4User == null) {
            return $this->outJson(0, [], 'mt4账户不存在');
        }

        if ($mt4User['BALANCE'] < $data['amount']) {
            return $this->outJson(0, [], '余额不足');
        }

        if ($mt4User['ENABLE_READONLY']  == 1) {
            return $this->outJson(0, [], '只读账号不能申请出金');
        }


        $query = Mt4Trades::find();
        $query->where(['LOGIN' => $data['login'], 'CLOSE_TIME' => '1970-01-01 00:00:00']);
        $query->andWhere(['<', 'CMD', 2]);
        $tcount = $query->count();
        if ($tcount > 0) {
            return $this->outJson(0, [], '有持仓订单不能出金，请平仓后再试');
        }

        if ($data['amount'] < 100) {
            return $this->outJson(0, [], '出金最小金额100美金');
        }
        if ($data['amount'] < $data['fee']) {
            return $this->outJson(0, [], '出金金额不足扣除手续费');
        }

        if ($data['amount'] > 7000) {
            return $this->outJson(0, [], '单笔出金金额最大7000美金');
        }

        $data['amount'] = $data['amount'] - $data['fee'];
        $data['type'] = 6;
        $data['in_time'] = intval(microtime(true) * 1000);
        //如果在后台设置了银行卡信息，则不允许用户修改该信息，取表里的数据
        $bank_info = MemberBankInfo::getBankInfoByMemberId($data['member_id']);
        if ($bank_info) {
            $data['bank_name'] = $bank_info['bank_name'];
            $data['bank_branch'] = $bank_info['bank_branch'];
            $data['bank_swift_code'] = $bank_info['bank_swift_code'];
            $data['bank_card_no'] = $bank_info['bank_card_no'];
            $data['bank_province'] = $bank_info['bank_province'];
            $data['bank_city'] = $bank_info['bank_city'];
            $data['name'] = $bank_info['name'];
            $data['mobile'] = $bank_info['mobile'];
        }
        $model->setAttributes($data);
        if ($model->save()) {
            $api = new Mt4ManagerApi();
            $api->userUpdate($data['login'], ['enable_read_only' => 1]);
            return $this->outJson(1, $model->getAttributes(), '操作成功');
        } else {
            return $this->outJson(0, [], $model->getErrors());
        }
    }

    /**
     * 获取当月出金记录
     * @return \yii\web\Response
     */
    public function actionGetMonthWithdraw()
    {
        $memberId = Yii::$app->getRequest()->get('memberId');
        if ($memberId == null || trim($memberId) === '') {
            return $this->outJson(0, [], '用户ID不能为空');
        }
        $result = Withdraw::getMonthWithdraw($memberId);
        return $this->outJson(1, $result, 'OK');
    }

    /**
     * 统计出金金额 amount+fee
     * @return \yii\web\Response
     */
    public function actionSumWithdraw()
    {
        $type = trim(Yii::$app->getRequest()->get('type'));
        $amount = Withdraw::sumWithdrawByType($type);
        return $this->outJson(1, Utils::formatFloatOrInt($amount));
    }

    /**
     * 统计出金金额 amount
     * @return \yii\web\Response
     */
    public function actionSumNotFee()
    {
        $type = trim(Yii::$app->getRequest()->get('type'));
        $amount = Withdraw::sumNotFeeByType($type);
        return $this->outJson(1, Utils::formatFloatOrInt($amount));
    }

    /**
     * 统计出金金额 人民币 amount*rate
     * @return \yii\web\Response
     */
    public function actionSumRmb()
    {
        $type = trim(Yii::$app->getRequest()->get('type'));
        $amount = Withdraw::sumRmbByType($type);
        return $this->outJson(1, Utils::formatFloatOrInt($amount));
    }

    /**
     * 出金详情
     * @return \yii\web\Response
     */
    public function actionDetail()
    {
        $id = intval(Yii::$app->getRequest()->get('id'));
        if ($id <= 0) {
            return $this->outJson(0, [], '参数非法');
        }
        /** @var Withdraw $withdraw */
        $withdraw = Withdraw::find()->where(['id' => $id])->limit(1)->one();
        if ($withdraw == null) {
            return $this->outJson(0, [], '数据不存在');
        }
        return $this->outJson(1, $withdraw->getAttributes());
    }

    /**
     * 修改出金记录
     * @return \yii\web\Response
     */
    public function actionUpdate()
    {
        $id = Yii::$app->getRequest()->post('id');
        if (!$id) {
            return $this->outJson(0, [], '参数非法');
        }
        /** @var Withdraw $withdraw */
        /*
        $withdraw = Withdraw::find()->where(['id' => $id])->limit(1)->one();
        if ($withdraw == null) {
            return $this->outJson(0, [], '数据不存在');
        }
        */
        $memo = trim(Yii::$app->getRequest()->post('memo'));
        $type = trim(Yii::$app->getRequest()->post('type'));
        $admin_name = trim(Yii::$app->getRequest()->post('admin_name'));
        //$memo != '' && $withdraw->memo = $memo;
        foreach ($id as $val) {
            $withdraw = Withdraw::find()->where(['id' => $val])->limit(1)->one();
            if ($withdraw == null) {
                return $this->outJson(0, [], '数据不存在');
            }
            if ($type != '' && in_array($type, [1, 2, 3, 5, 6])) {
                // 1审核不通过
                // 2已出金
                // 3管理员撤销
                if ($withdraw->type == 0 || $withdraw->type == 5 || $withdraw->type == 6) {
                    $withdraw->type = $type;
                    $admin_name != '' && $withdraw->admin_name = $admin_name;
                    if ($type == 2) {
                        $withdraw->out_time = intval(microtime(true) * 1000);
                    }
                } else {
                    return $this->outJson(0, [], "只有‘等待审核’和‘暂不处理’状态的出金申请才可操作");
                }
            }

            if ($type == 2 ) {
                $mt4Deposit = new Mt4Deposit();
                $result = $mt4Deposit->withdraw($withdraw->login, $withdraw->amount + $withdraw->fee, 'Withdraw');
                if ($result['errCode'] == 0 ) {
                    //更改MT4状态
                    $res = Withdraw::updateAll(['mt4_status' => 1], "id = $withdraw->id");
                    if (!$res) {
                        return $this->outJson(0, [], $result['errMsg']);
                    }
                } else {
                    return $this->outJson(0, [], $result['errMsg']);
                }
            }

            if ($withdraw->save()) {
                $api = new Mt4ManagerApi();
                $api->userUpdate($withdraw->login, ['enable_read_only' => 0]);
            }else {
                return $this->outJson(0, [], $withdraw->getErrors());
            }
        }
        return $this->outJson(1, [], '操作成功');

    }
    
    /**
     * 调用出金接口
     */
    public function actionWithdraw()
    {
        $mt4Id = (int) Yii::$app->request->post('mt4Id');
        $usdMoney = (float) Yii::$app->request->post('usdMoney');
        $comment = trim(Yii::$app->request->post('comment'));
        
        if (empty($mt4Id) || empty($usdMoney) || empty($comment)) {
            return $this->outJson(0, [], '缺少参数');
        }
        
        $mt4Deposit = new Mt4Deposit();
        $result = $mt4Deposit->withdraw($mt4Id, $usdMoney, $comment);
        return $this->outJson($result['errCode'] == 0 ? 1 : 0, $result['data'], $result['errMsg']);
    }
    
}
