<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Status;
use common\models\Period;
use common\models\User;
use common\models\UserClose;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * Login form
 */
class UserCloseForm extends Model {
    public $id;
    public $userName;
    public $type;
    public $isClose;
    public $remark;
    public $auditStatus;

    private $_userId;
    private $_userCloseModel;
    private $_periodNum;
    private $_closeInfo = [
        UserClose::TYPE_GT => '关停',
        UserClose::TYPE_TF => '停发',
    ];

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'userName', 'type', 'isClose', 'remark', 'auditStatus'], 'trim'],
            [['id', 'userName', 'type', 'isClose'], 'required'],
            [['userName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['id', 'userName'], 'initModel'],
            [['id'], 'exist', 'targetClass' => UserClose::class, 'targetAttribute' => 'ID'],
            [['type'], 'isType'],
            [['isClose'], 'checkClose'],
            [['auditStatus'], 'isAuditStatus'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            // 手动申请
            'add' => ['userName', 'type', 'isClose', 'remark'],
            // 自动关停
            'auto' => ['userName', 'type', 'isClose', 'remark'],
            // 审核关停
            'audit' => ['id', 'auditStatus']
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'userName' => '会员编号',
            'type' => '类型',
            'isClose' => '是否关停',
            'remark' => '备注',
        ];
    }

    /**
     * 初始化model和userId
     * @param $attribute
     */
    public function initModel($attribute) {
        $period = Period::instance();
        $this->_periodNum = $period->getNowPeriodNum();
        if ($this->scenario == 'audit') {
            $this->_userCloseModel = UserClose::findOne(['ID' => $this->id]);
            $this->_userId = $this->_userCloseModel->USER_ID;
        } elseif ($this->scenario == 'add' || $this->scenario == 'auto') {
            $this->_userCloseModel = new UserClose();
            $oneUser = UserInfo::findOneAsArray(['USER_NAME' => $this->userName], [], 'USER_ID');
            $this->_userId = $oneUser['USER_ID'];
            // 查看数据库中是否已经存在了该会员的申请未审核
            $oneUserClose = UserClose::findOne(['USER_ID' => $this->_userId, 'AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value'], 'TYPE' => $this->type]);
            if ($oneUserClose && $this->scenario == 'add') {
                // 不允许重复申请
                $this->addError($attribute, '已经存在该会员的待审核数据，请等待审核后再申请');
            } elseif ($oneUserClose && $this->scenario == 'auto') {
                // 如果是自动关停时，如果遇上未审核的，直接审核拒绝，防止影响自动关停的进程
                $oneUserClose->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
                $oneUserClose->AUDITED_AT = Date::nowTime();
                $oneUserClose->save();
            }
        } else {
            $this->addError($attribute, '场景不正确');
        }
    }

    /**
     * 关停还是停发
     * @param $attribute
     */
    public function isType($attribute) {
        if (!in_array($this->type, [UserClose::TYPE_GT, UserClose::TYPE_TF])) {
            $this->addError($attribute, '类型不正确');
        }
    }

    /**
     * 校验该用户是否已经被关闭
     * @param $attribute
     */
    public function checkClose($attribute) {
        if ($this->type == UserClose::TYPE_GT) {
            if ($this->isClose == 1 && Status::isCloseAccount($this->_userId)) {
                $this->addError($attribute, '该会员已经被关停');
            } elseif ($this->isClose == 0 && !Status::isCloseAccount($this->_userId)) {
                $this->addError($attribute, '该会员没有被关停');
            }
        } elseif ($this->type == UserClose::TYPE_TF) {
            if ($this->isClose == 1 && Status::isCloseBonus($this->_userId)) {
                $this->addError($attribute, '该会员已经被停发');
            } elseif ($this->isClose == 0 && !Status::isCloseBonus($this->_userId)) {
                $this->addError($attribute, '该会员没有被停发');
            }
        }
    }

    /**
     * 审核状态是否正确
     * @param $attributes
     */
    public function isAuditStatus($attributes) {
        if (!array_key_exists($this->auditStatus, \Yii::$app->params['auditStatus'])) {
            $this->addError($attributes, '无效的审核状态');
        }
    }

    /**
     * 申请
     * @return null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $model = $this->_userCloseModel;
            $model->USER_ID = $this->_userId;
            $model->TYPE = $this->type;
            $model->PERIOD_NUM = $this->_periodNum;
            $model->IS_CLOSE = $this->isClose;
            $model->REMARK = $this->remark;
            if ($this->scenario == 'add') {
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['un']['value'];
                $model->IS_MANUAL = 1;
                $model->ADMIN_ID = \Yii::$app->user->id;
            } elseif ($this->scenario == 'auto') {
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
                $model->AUDITED_AT = Date::nowTime();
            } else {
                $this->addError('setClose', '场景不正确');
            }
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            // 把商城会员表的状态改为0
            $isCloseShopUser = false;
            $closeShopStatus = 0;
            if ($this->scenario == 'auto' && $this->type == UserClose::TYPE_GT && $this->isClose == 1) {
                $isCloseShopUser = true;
                $closeShopStatus = 0;
            } elseif ($this->scenario == 'auto' && $this->type == UserClose::TYPE_GT && $this->isClose == 0) {
                $isCloseShopUser = true;
                $closeShopStatus = 1;
            }
            if ($isCloseShopUser) {
                $oneUser = User::findOne(['ID' => $this->_userId]);
                $oneUser->STATUS = $closeShopStatus;
                if (!$oneUser->save()) {
                    throw new Exception(Form::formatErrorsForApi($oneUser->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;

    }

    /**
     * 审核
     * @return null
     * @throws \yii\db\Exception
     */
    public function audit() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $model = $this->_userCloseModel;
            if ($this->auditStatus == 'true') {
                $model->AUDIT_ADMIN_ID = \Yii::$app->user->id;
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['true']['value'];
                $model->AUDITED_AT = Date::nowTime();
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
                if ($model->IS_CLOSE) {
                    $closedAt = Date::nowTime();
                } else {
                    $closedAt = 0;
                }
                // 修改结算系统会员表的状态
                $closeField = UserClose::TYPE_GT ? 'CLOSE_ACCOUNT' : 'CLOSE_BONUS';
                UserInfo::updateAll([$closeField => $model->IS_CLOSE, 'CLOSE_ACCOUNT_AT' => $closedAt], 'USER_ID=:USER_ID', [':USER_ID' => $this->_userId]);
                // 把商城会员表的状态改为0
                $isCloseShopUser = false;
                $closeShopStatus = 0;
                if ($model->TYPE == UserClose::TYPE_GT && $model->IS_CLOSE == 1) {
                    $isCloseShopUser = true;
                    $closeShopStatus = 0;
                } elseif ($model->TYPE == UserClose::TYPE_GT && $model->IS_CLOSE == 0) {
                    $isCloseShopUser = true;
                    $closeShopStatus = 1;
                }
                if ($isCloseShopUser) {
                    $oneUser = User::findOne(['ID' => $this->_userId]);
                    $oneUser->STATUS = $closeShopStatus;
                    if (!$oneUser->save()) {
                        throw new Exception(Form::formatErrorsForApi($oneUser->getErrors()));
                    }
                }
            } elseif ($this->auditStatus == 'reject') {
                $model->AUDIT_ADMIN_ID = \Yii::$app->user->id;
                $model->AUDIT_STATUS = \Yii::$app->params['auditStatus']['reject']['value'];
                $model->AUDITED_AT = Date::nowTime();
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError($e->getMessage());
            return null;
        }
        return $model;
    }


}
