<?php 

namespace backend\controllers;

use backend\helpers\MailHelper;
use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Config;
use backend\models\Deposit;
use backend\models\DepositConfig;
use backend\models\SyncDesposit;
use backend\models\Member;
use backend\models\UserMember;
use common\helpers\MtKit;
use common\helpers\Utils;
use common\pay\PayForm;
use Yii;

class DepositController extends BaseController
{
    /**
     * 入金记录
     * @return \yii\web\Response
     */
    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['name'] = isset($data['name']) ? trim($data['name']) : '';
        $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'],
            ['name', '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 = Deposit::find()->orderBy($data['orderBy']);
        $query->andFilterWhere(['crm_deposit.mt4_status' => $data['type']]);
        if ($data['from'] == 'admin') {
            $query->andFilterWhere(['member_id' => $data['memberId']]);
        } else {
            $query->andWhere(['member_id' => $data['memberId']]);
        }
        if (trim($data['name']) != '') {
            $query->leftJoin(Member::tableName() . ' m', 'crm_deposit.member_id=m.id')->andWhere(['like', 'm.name', $data['name']]);
        }
        $query->andFilterWhere(['>=', 'in_time', $data['inTimeStart']]);
        $query->andFilterWhere(['<', 'in_time', $data['inTimeEnd']]);
        $query->andFilterWhere(['or', ['like', 'login', $data['search']], ['like', 'id', $data['search']]]);
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        if ($data['from'] == 'admin') {
            foreach ($result['dataList'] as $key => &$row) {
                $member = Member::findById($row['member_id']);
                if ($member == null) {
                    $row['name'] = '';
                    $row['mobile'] = '';
                } else {
                    $row['name'] = $member['name'];
                    $row['mobile'] = $member['mobile'];
                }
                $userMember = UserMember::findByLogin($row['login']);
                if ($userMember == null) {
                    $row['IBNAME'] = '';
                } else {
                    $member = Member::findById($userMember['member_id']);
                    if ($member == null) {
                        $row['IBNAME'] = '';
                    } else {
                        $row['IBNAME'] = $member['name'];
                    }
                }
            }
        }
        return $this->outJson(1, $result);
    }

    /**
     * 入金统计
     * @return \yii\web\Response
     */
    public function actionSumDeposit()
    {
        $type = trim(Yii::$app->getRequest()->get('type'));
        $sum = Deposit::sumDepositByType($type);
        return $this->outJson(1, Utils::formatFloatOrInt($sum));
    }

    /**
     * 入金补单
     */
    public function actionPatchIntoGold()
    {
        $id = intval(Yii::$app->getRequest()->post('id'));
        $admin_name = trim(Yii::$app->getRequest()->post('admin_name'));
        if ($id <= 0) {
            return $this->outJson(0, [], '未指定数据对象');
        }
        $deposit = Deposit::findById($id);
        if ($deposit == null) {
            return $this->outJson(0, [], '数据对象不存在');
        }
        if ($deposit->mt4_status == 0) {
            $deposit->mt4_status = 1;
            $deposit->type = 1;
            $admin_name != '' && $deposit->admin_name = $admin_name;
            if ($deposit->save(false)) {
				SyncDesposit::updateAll(['is_sync' => 1], ['memo' => $deposit['order_sn'], 'is_sync' => 0]);
                MtKit::deposit($deposit['login'], $deposit['amount'], 'Deposit');
                $member = Member::findById($deposit->member_id);
                if ($member != null) {
                    $config = Config::findOne(1);
                    $paramArray = [
                        'name' => $member['name'],
                        'login' => $deposit['login'],
                        'usd' => $deposit['amount'],
                        'rmb' => $deposit['rmb'],
                        'rate' => $deposit['rate'],
                    ];
                    // 发送邮件
                    MailHelper::sendMail("恭喜您，您的入金已成功受理", $member['username'], $paramArray, '', $config->mail_deposit);
                }
            }
        }
        return $this->outJson(1, [], '操作成功');
    }

    /**
     * 获取入金配置
     * @return \yii\web\Response
     */
    public function actionGetDepositConfig()
    {
        $depositConfig = [];
        foreach (PayForm::$payNames as $payId => $payName) {
            $depositConfig[$payId] = [
                'id' => $payId,
                'label' => $payName,
                'enable' => 0,
            ];
        }
        /** @var DepositConfig $model */
        $model = DepositConfig::find()->one();
        if ($model) {
            $configData = @json_decode($model->config_data, true);
            foreach ((array)$configData as $key => $row) {
                if (isset($depositConfig[$row['id']])) {
                    $depositConfig[$row['id']]['enable'] = isset($row['enable']) && $row['enable'] == 1 ? 1 : 0;
                }
            }
        }
        return $this->outJson(1, $depositConfig, '操作成功');
    }

    /**
     * 设置入金配置
     * @return \yii\web\Response
     */
    public function actionSetDepositConfig()
    {
        $depositConfig = [];
        foreach (PayForm::$payNames as $payId => $payName) {
            $depositConfig[$payId] = [
                'id' => $payId,
                'label' => $payName,
                'enable' => 0,
            ];
        }
        /** @var DepositConfig $model */
        $model = DepositConfig::find()->one();
        if ($model == null) {
            $model = new DepositConfig();
        }
        $configData = @json_decode($model->config_data, true);
        foreach ((array)$configData as $key => $row) {
            if (isset($depositConfig[$row['id']])) {
                $depositConfig[$row['id']]['enable'] = isset($row['enable']) && $row['enable'] == 1 ? 1 : 0;
            }
        }
        $config = trim(Yii::$app->getRequest()->post('config'));
        if ($config == '') {
            return $this->outJson(0, [], '参数非法' . __LINE__);
        }
        $configArr = @json_decode($config, true);
        if ($configArr == null) {
            return $this->outJson(0, [], '参数非法' . __LINE__);
        }
        foreach ($configArr as $key => $row) {
            if (!isset($row['id']) || !isset($depositConfig[$row['id']])) {
                continue;
            }
            $depositConfig[$row['id']]['enable'] = isset($row['enable']) && $row['enable'] == 1 ? 1 : 0;
        }
        $model->config_data = json_encode($depositConfig, 320);
        if ($model->save()) {
            return $this->outJson(1, [], '操作成功');
        } else {
            return $this->outJson(0, [], '操作失败');
        }
    }
}

