<?php

namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Tool;
use common\helpers\user\Balance;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\libs\logging\operate\UserOperate;
use common\models\DealType;
use common\models\Period;
use common\models\User;
use common\models\UserInfo;
use yii\db\Exception;

/**
 * Login form
 */
class UserConfigForm extends Model {
    public $isAutoWithdraw;
    public $allowReconsumeSms;

    private $_config;

    public function init() {
        parent::init();
        $this->userOperateLogger = new UserOperate([
            'fetchClass' => UserInfo::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['isAutoWithdraw', 'allowReconsumeSms'], 'required'],
            [['isAutoWithdraw', 'allowReconsumeSms'], 'boolean'],
            [['isAutoWithdraw'], 'isCanAutoWithdraw'],
            [['allowReconsumeSms'], 'isAllowReconsumeSms'],
        ];
    }

    public function attributeLabels() {
        return [
            'isAutoWithdraw' => '是否自动提现',
            'allowReconsumeSms' => '开启复销短信通知',
        ];
    }


    /**
     * 指定场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'autoWithdraw' => ['isAutoWithdraw'],
            'allowReconsumeSms' => ['allowReconsumeSms'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 是否可以修改自动提现
     * @param $attribute
     */
    public function isCanAutoWithdraw($attribute) {
        if (!Info::isVerified(\Yii::$app->user->id)) {
            $this->addError($attribute, '请先实名认证');
        }
        $this->_config = Cache::getSystemConfig();
        if (!$this->_config['isCanAutoWithdraw']['VALUE'] && $this->isAutoWithdraw) {
            $this->addError('scenario', '系统关闭了自动提现');
        }
    }

    /**
     * 是否可以开启复销短信通知
     * @param $attribute
     */
    public function isAllowReconsumeSms($attribute) {
        $this->_config = Cache::getSystemConfig();
        if (!$this->_config['smsOpen']['VALUE'] && $this->isAutoWithdraw) {
            $this->addError('scenario', '系统关闭了开启复销短信通知');
        }
    }

    /**
     * 更新自动提现
     * @return bool|null
     * @throws Exception
     */
    public function autoWithdraw() {
        if (!$this->validate()) {
            return null;
        }
        $this->userOperateLogger->beforeUpdate(\Yii::$app->user->id,'USER_ID',['select'=>'IS_AUTO_WITHDRAW']);
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if (!UserInfo::updateAll(['IS_AUTO_WITHDRAW' => $this->isAutoWithdraw], 'USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->user->id])) {
                throw new Exception('更新个人设置失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('autoWithdraw', $e->getMessage());
            return null;
        }
        $this->userOperateLogger->afterUpdate(\Yii::$app->user->id,'USER_ID',['select'=>'IS_AUTO_WITHDRAW']);
        $this->userOperateLogger->clean()->save([
            'optType' => '开启关闭自动提现',
            'userId' => \Yii::$app->user->id,
            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
        ]);
        return true;
    }

    /**
     * 更新复销短信提醒
     * @return bool|null
     * @throws Exception
     * @throws \yii\base\Exception
     */
    public function allowReconsumeSms() {
        if (!$this->validate()) {
            return null;
        }
        $this->userOperateLogger->beforeUpdate(\Yii::$app->user->id,'USER_ID',['select'=>'ALLOW_RECONSUME_SMS,ALLOW_RECONSUME_SMS_TO']);
        $balanceData = Balance::getLogData(\Yii::$app->user->id);
        $beforeData = $this->userOperateLogger->saveBeforeContent;
        $this->userOperateLogger->saveBeforeContent = array_merge($beforeData,$balanceData);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $userId = \Yii::$app->user->id;
            if (!UserInfo::updateAll(['ALLOW_RECONSUME_SMS' => $this->allowReconsumeSms?$this->allowReconsumeSms:0], 'USER_ID=:USER_ID', [':USER_ID' => $userId])) {
                throw new Exception('更新个人设置失败');
            }
            //开启扣费
            $smsTo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId], 'ALLOW_RECONSUME_SMS_TO');
            //如果开启并且会员短信不在有效期
            if ($this->allowReconsumeSms && $smsTo['ALLOW_RECONSUME_SMS_TO'] < Date::nowTime()) {
                $smsWallet = explode(",", $this->_config['smsWallet']['VALUE']);
                $smsFee = $this->_config['smsFee']['VALUE'];
                //获取剩余月份
                $period = Period::instance();
                $year = $period->getNowYear();
                $monthLeft = Period::getMonthLeft();
                $smsFee = Tool::formatPrice($smsFee * $monthLeft);
                $to = Date::yearEnd();
                foreach ($smsWallet as $item) {
                    //1奖金钱包2现金钱包
                    if ($item == 1) {
                        //看余额是否充足
                        if (Balance::getAvailableBalance($userId) < $smsFee) continue;
                        Balance::changeUserBonus($userId, 'bonus', -abs($smsFee), ['DEAL_TYPE_ID' => DealType::SMS, 'REMARK' => $year . '年复销提醒短信服务费']);
                        if (!UserInfo::updateAll(['ALLOW_RECONSUME_SMS_TO' => $to], 'USER_ID=:USER_ID', [':USER_ID' => $userId])) {
                            throw new Exception('更新个人短信有效期失败');
                        }
                        break;
                    } elseif ($item == 2) {
                        throw new Exception('不存在此方式');
                        break;
                    }
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('allowReconsumeSms', $e->getMessage());
            return null;
        }

        $this->userOperateLogger->afterUpdate(\Yii::$app->user->id,'USER_ID',['select'=>'ALLOW_RECONSUME_SMS,ALLOW_RECONSUME_SMS_TO']);
        $balanceData = Balance::getLogData(\Yii::$app->user->id);
        $afterData = $this->userOperateLogger->saveAfterContent;
        $this->userOperateLogger->saveAfterContent = array_merge($afterData,$balanceData);
        unset($beforeData,$afterData);
        $this->userOperateLogger->clean()->save([
            'optType' => '开启关闭复销短信提醒',
            'userId' => \Yii::$app->user->id,
            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
        ]);
        return true;
    }
}
