<?php 
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/1/001
 * Time: 19:31
 */

namespace backend\controllers;


use backend\helpers\DateTimeHelper;
use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Member;
use backend\models\Mt4Users;
use backend\models\Transfer;
use common\helpers\MtKit;
use common\helpers\Utils;

class TransferController extends BaseController
{
    /**
     * xtrader首页数据-同名转账
     */
    public function actionTransfer()
    {
        $request = \Yii::$app->request;
        $member_id = $request->get('member_id');
        $member = Member::findOne(['id' => $member_id]);
        $login = $this->getMainLogin($member);
        $user = (new Mt4Users())->findByLogin($login);
        $logins = (new Member())->getLogins($member_id);
        $result = [
            'member' => $member,
            'user' => $user,
            'logins' => $logins,
        ];
        return $this->outJson(1, $result);
    }

    /**
     * 同名转账列表
     */
    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['member_id'] = isset($data['member_id']) ? trim($data['member_id']) : '';
        $data['inStartTime'] = isset($data['inStartTime']) ? trim($data['inStartTime']) : '';
        $data['inEndTime'] = isset($data['inEndTime']) ? trim($data['inEndTime']) : '';
        $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['search'] = isset($data['search']) ? trim($data['search']) : '';

        $data = ValidatorHelper::validateData($data, [
            ['type', 'integer'],
            ['from', 'string'],
            ['member_id', 'integer'],
            ['inStartTime', 'integer'],
            ['inEndTime', 'integer'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        
        $query = Transfer::find()->alias('t')
            ->select(['t.*','u.name', 'u.type as member_type'])
            ->innerJoin('crm_member u', 't.member_id = u.id')
            ->orderBy($data['orderBy']);
        // 按type获取列表
        $query->andFilterWhere(['t.type' => $data['type']]);
        
        if ($data['from'] == 'admin') {
            $query->andFilterWhere(['t.member_id' => $data['member_id']]);
        } else {
            $query->andWhere(['t.member_id' => $data['member_id']]);
        }
        $query->andFilterWhere(['>=', 't.in_time', $data['inStartTime']]);
        $query->andFilterWhere(['<', 't.in_time', $data['inEndTime']]);
        $query->andFilterWhere([
            'or',
            ['like', 't.memo', $data['search']]
        ]);

        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        if ($result['dataList']) {
            foreach ($result['dataList'] as $k => $v) {
                $result['dataList'][$k]['amount'] = Utils::formatFloatOrInt($v['amount']);
            }
        }
        return $this->outJson(1, $result);
    }

    /**
     * 审核同名转账
     */
    public function actionUpdateType()
    {
        $data = \Yii::$app->getRequest()->post();
        $data['id'] = isset($data['id']) ? (int)$data['id'] : 0;
        $data['type'] = isset($data['type']) ? (int)$data['type'] : '';
        $data['admin_name'] = isset($data['admin_name']) ? trim($data['admin_name']) : '';

        $info = Transfer::findOne(['id' => $data['id']]);

        if (!$info) {
            return $this->outJson(0, [], '该记录不存在');
        }

        if (isset($data['type']) && $info->type == 0) {
            $info->type = $data['type'];
            $data['admin_name'] != '' && $info->admin_name = $data['admin_name'];
        } else {
            return $this->outJson(0, [], '只有‘未审核’状态才可操作');
        }

        $rs = $info->update();

        if (!$rs) {
            return $this->outJson(0, [], '数据操作失败');
        }
        if ($data['type'] == 2) {
            $toLogin = $info->to_login;
            $fromLogin = $info->from_login;
            $amount = $info->amount;
            $wres = MtKit::withdrawal($fromLogin, $amount, "Withdrwal(Z$toLogin)");
            if ($wres) {
                MtKit::deposit($toLogin, $amount, "Deposit(Z$fromLogin)");
            }
        }
        return $this->outJson(1, ['id' => $info['id']], '操作成功');
    }

    /**
     * 获取某条记录的备注
     */
    public function actionMemo()
    {
        $data = \Yii::$app->getRequest()->get();
        $data['id'] = isset($data['id']) ? $data['id'] : 0;
        $transfer = Transfer::findOne(['id' => $data['id']]);
        return $this->outJson(1, $transfer);
    }

    /**
     * 修改某条记录的备注
     */
    public function actionMemoUpdate()
    {
        $data = \Yii::$app->getRequest()->post();
        $data['id'] = isset($data['id']) ? $data['id'] : 0;
        $data['memo'] = isset($data['memo']) ? $data['memo'] : '';

        $info = Transfer::findOne(['id' => $data['id']]);

        if (!$info) {
            return $this->outJson(0, [], '该记录不存在');
        }

        $info->memo = $data['memo'];

        $rs = $info->save();

        if (!$rs) {
            return $this->outJson(0, [], '数据操作失败');
        }
        return $this->outJson(1, ['id' => $info['id']], '操作成功');
    }

    /**
     * 申请同名转账
     */
    public function actionAddTransfer()
    {
        $request = \Yii::$app->request;
        if ($request->isPost) {
            $params = $request->post();
            $params['member_id'] = isset($params['member_id']) ? trim($params['member_id']) : '';
            $params['from_login'] = isset($params['flogin']) ? trim($params['flogin']) : '';
            $params['to_login'] = isset($params['tlogin']) ? trim($params['tlogin']) : '';
            $params['amount'] = isset($params['amount']) ? doubleval($params['amount']) : '';
            $params['type'] = isset($params['type']) ? intval($params['type']) : 0;

            if ($params['from_login'] == null) {
                return $this->outJson(0, [], '请选择账户');
            }

            if ($params['to_login'] == null) {
                return $this->outJson(0, [], '请选择账户');
            }

            if ($params['from_login'] == $params['to_login']) {
                return $this->outJson(0, [], '转出与转入账户相同');
            }

            if (empty($params['amount'])) {
                return $this->outJson(0, [], '请填写金额');
            }

            $isHave = false;
            $member = Member::find()->select('logins')->where(['id' => $params['member_id']])->asArray()->limit(1)->one();
            if ($member['logins']) {
                $mt4Login = explode(',', $member['logins']);
                if (in_array($params['from_login'], $mt4Login)) {
                    $isHave = true;
                }
            }

            if (!$isHave) {
                return $this->outJson(0, [], '参数错误');
            }
            
            // 判断是否为同名账户，只有传入type参数的时候才判断
            if ($params['type']) {
                $isSameAccount = Member::isSameAccount($params['from_login'], $params['to_login'], $params['type']);
                if ($isSameAccount['code'] != 1) {
                    return $this->outJson(0, [], $isSameAccount['message']);
                }    
            }

            $transfer = Transfer::findOne(['member_id' => $params['member_id'], 'type' => 0]);
            if ($transfer) {
                return $this->outJson(0, [], '您还有未处理的申请记录，请等待审核');
            }

            $mt4User = (new Mt4Users())->findByLogin($params['from_login']);
            if (doubleval($mt4User['BALANCE']) < $params['amount']) {
                return $this->outJson(0, [], '余额不足');
            }

            $transfer = new Transfer();
            $transfer->setAttributes($params);
            $transfer->type = 0;
            $transfer->in_time = DateTimeHelper::microtime_float();

            if ($transfer->save()) {
                return $this->outJson(1, $transfer->getAttributes(), '提交成功');
            } else {
                $errors = $transfer->getErrors();
                if (!empty($errors)) {
                    foreach ($errors as $key => $error) {
                        if ($key == 'amount') {
                            return $this->outJson(0, [], '金额必须是整数');
                        }
                    }
                }
            }
        } else {
            return $this->outJson(0, [], '参数传输格式错误');
        }
    }

    /**
     * 同名转账:转入账户是否属于转出账户的客户判断
     */
    public function actionIsIbUser()
    {
        $fromLogin = \Yii::$app->getRequest()->get('fromLogin');
        $toLogin = \Yii::$app->getRequest()->get('toLogin');
        $type = \Yii::$app->getRequest()->get('type');

        $isSameAccount = Member::isSameAccount($fromLogin, $toLogin, $type);
       
        $result['isSuccess'] = $isSameAccount['code'] == 1 ? true : false;
        $result['msg'] = $isSameAccount['message'];
        return $this->outJson(1, $result);
    }
}

