<?php

namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\libs\logging\operate\AdminOperate;
use common\models\User;
use yii\base\Exception;

/**
 * Login form
 */
class UserBasicForm extends Model {
    public $userId;
    public $password;
    public $passwordType;

    //个人资料
    public $nation;
    public $realName;
    public $idCard;
    public $mobile;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $studiocode;
    public $studiodate;

    public $status;

    public function init() {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => User::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['userId', 'password', 'passwordType','nation','realName', 'mobile','openBank','bankAddress','bankNo','status'], 'trim'],
            [['userId'], 'required'],
            [['idCard', 'allData'], 'required', 'on'=>['addWithUserName']],
            [['nation','realName', 'mobile', 'idCard', 'openBank', 'bankAddress', 'bankNo'], 'required', 'on'=>'modifyProfile'],
            [['mobile'], 'mobile'],
            [['studiocode'],'string','max'=>'10']
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'modifyPassword' => ['userId', 'password', 'passwordType'],
            'modifyProfile' => ['userId','nation','realName','idCard','mobile','openBank','bankAddress','bankNo','studiocode','studiodate'],
            'modifyStatus' => ['userId','status'],
            'isModifyPasswordStatus' => ['userId','status'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'ID' => 'ID',
            'password' => '密码',
            'passwordType' => '密码类型',
            'nation' => '民族',
            'realName' => '真实姓名',
            'idCard' => '身份证号',
            'mobile' => '手机号',
            'openBank' => '银行名称',
            'bankAddress' => '开户支行',
            'bankNo' => '银行账号',
            'status' => '状态',
            'studiocode'=>'工作室编号'
        ];
    }

    public function beforeValidate() {
        return parent::beforeValidate();
    }

    /**
     * 编辑用户信息
     * @return null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $userModel = User::findOne(['ID'=>$this->userId]);
            if( $this->passwordType === 'password' ) {
                $userModel->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
            }else {
                $userModel->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->password);
            }

            if( !$userModel->save(false) ) {
                throw new Exception($userModel->getErrors());
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return null;
        }

        return $userModel;

    }

    /**
     * 修改个人资料
     * @return User|null
     * @throws \yii\db\Exception
     */
    public function modifyProfile(){
        if(!$this->validate()){
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $userModel = User::findOne(['ID' => $this->userId]);
            $this->adminOperateLogger->beforeUpdate($userModel);
            $userModel->NATION = $this->nation;
            $userModel->REAL_NAME = $this->realName;
            $userModel->MOBILE = $this->mobile;
            $userModel->ID_CARD = $this->idCard;
            $userModel->OPEN_BANK = $this->openBank;
            $userModel->BANK_NO = $this->bankNo;
            $userModel->BANK_ADDRESS = $this->bankAddress;
            $userModel->IS_STUDIO_CODE = $this->studiocode;
            $userModel->IS_STUDIO_DATE = $this->studiodate;
            if( !$userModel->save(false) ) {
                throw new Exception($userModel->getErrors());
            }
            $transaction->commit();
            $this->adminOperateLogger->afterUpdate($userModel)->clean()->save([
                'optType' => '修改会员资料',
                'userId' => $this->userId,
                'userName' => $userModel->USER_NAME,
                'nation' => $this->nation,
                'realName' => $this->realName,
                'mobile' => $this->mobile,
                'idCard' => $this->idCard,
                'openBank' => $this->openBank,
                'bankNo' => $this->bankNo,
                'studiocode' => $this->studiocode,
                'studiodate' => $this->studiodate,
                'bankAddress' => $this->bankAddress,
            ]);
        }catch (Exception $e) {
            $transaction->rollBack();
            return null;
        }
        return $userModel;
    }


    /**
     * 修改会员状态
     * @return User|null
     * @throws \yii\db\Exception
     */
    public function modifyStatus(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->beforeUpdate($this->userId, 'ID',['select'=>'ID,STATUS']);

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $userModel = User::findOne(['ID' => $this->userId]);
            if($userModel->STATUS==$this->status){
                $statusName = ($userModel->STATUS == 1) ? '激活' : '锁定';
                throw new Exception('当前会员状态已【' . $statusName . '】，无需重复设置！');
            }
            $userModel->STATUS = $this->status;
            $userModel->STATUS_AT = Date::nowTime();
            if( !$userModel->save(false) ) {
                throw new Exception($userModel->getErrors());
            }
            $transaction->commit();
        }catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('modifyStatus', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->afterUpdate($this->userId,'ID',['select'=>'ID,STATUS'])->clean()->save([
            'optType' => ($this->status == 1) ? '会员激活' : '会员锁定',
        ]);
        return $userModel;
    }

    /**
     * @return User|null
     * @throws \yii\db\Exception
     */
    public function isModifyPasswordStatus(){
        if(!$this->validate()){
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $userModel = User::findOne(['ID' => $this->userId]);
            if($userModel->IS_MODIFY_PASSWORD==$this->status){
                throw new Exception('状态没有发生改变，无需重复设置！');
            }
            $userModel->IS_MODIFY_PASSWORD = $this->status;
            if( !$userModel->save(false) ) {
                throw new Exception($userModel->getErrors());
            }
            $transaction->commit();
        }catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('isModifyPasswordStatus', $e->getMessage());
            return null;
        }
        return $userModel;
    }

}
