<?php
/**
 * Created by PhpStorm.
 * User: chenkuan
 * Date: 2017/11/8
 * Time: 上午10:14
 */

namespace backend\controllers;


use backend\helpers\DateTimeHelper;
use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Config;
use backend\models\Member;
use backend\models\ModifyLever;
use backend\models\Mt4Users;

class LeverController extends BaseController
{
    const DEF_CONFIG_ID = 1;
    /**
     * xtrader首页数据-修改杠杆
     */
    public function actionLever()
    {
        $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);
        $cache = \Yii::$app->cache;
        $config = $cache->get('config');
        if ($config == null) {
            $config = Config::findOne(['id' => self::DEF_CONFIG_ID]);
            $cache->set('config', $config, 86400);
        }
        $levers = explode(',', $config->lever);

        $result = [
            'member' => $member,
            'user' => $user,
            'logins' => $logins,
            'levers' => $levers,
        ];
        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 = ModifyLever::find()->alias('t')
            ->select(['t.*','u.name'])
            ->leftJoin('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']);
        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'] : '';

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

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

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

        $rs = $info->save();

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

    /**
     * 获取某条记录的备注
     */
    public function actionMemo()
    {
        $data = \Yii::$app->getRequest()->get();
        $data['id'] = isset($data['id']) ? $data['id'] : 0;
        $transfer = ModifyLever::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'] : null;

        $info = ModifyLever::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 actionAddModifyLever()
    {
        $request = \Yii::$app->request;
        if ($request->isPost) {
            $params = $request->post();
            $params['member_id'] = isset($params['member_id']) ? trim($params['member_id']) : '';
            $params['login'] = isset($params['login']) ? trim($params['login']) : '';
            $params['lever'] = isset($params['lever']) ? intval($params['lever']) : '';

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

            if (!$isHave) {
                return $this->outJson(0, [], '参数错误');
            }

            $mt4Users = Mt4Users::find()->where(['login' => $params['login']])->asArray()->limit(1)->one();
            if (intval($mt4Users['LEVERAGE']) == $params['lever']) {
                return $this->outJson(0, [], '提交失败,与当前杠杆一致');
            }

            $result = ModifyLever::findOne([
                'member_id' => $params['member_id'],
                'login' => $params['login'],
                'type' => 0,
            ]);

            if ($result != null) {
                return $this->outJson(0, [], '您还有未处理的申请记录，请等待审核');
            }

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

            if ($lever->save()) {
                return $this->outJson(1, $lever->getAttributes(), '提交成功');
            } else {
                return $this->outJson(0, [], $lever->getErrors());
            }
        } else {
            return $this->outJson(0, [], '参数传输格式错误');
        }
    }
}
