<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\snowflake\SnowFake;
use common\helpers\user\Balance;
use common\helpers\user\Info;
use common\libs\logging\operate\UserOperate;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\User;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use Yii;
use yii\db\Exception;

/**
 * Login form
 */
class UserForm extends Model
{
    public $userId;
    public $userName;
    public $zcPv;
    public $zcAmount;
    public $conUserName;
    public $bottomUserName;
    public $recUserName;
    public $conUid;
    public $bottomUid;
    public $recUid;
    public $location;
    public $idCard;
    public $allData;   // 批量报单的全部报单数据

    //个人资料
    public $nation;
    public $realName;
    public $mobile;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $email;

    //修改密码
    public $password;
    public $oldPassword;
    public $verifyPassword;
    public $payPassword;

    private $_conUid;
    private $_recUid;
    private $_bottomUid;
    private $_limit = 1000;

    private $_conTopUid;
    private $_conTopDeep;
    private $_recTopUid;
    private $_recTopDeep;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userId', 'userName', 'zcPv', 'zcAmount', 'conUserName', 'recUserName', 'bottomUserName', 'conUid', 'recUid', 'location','nation','realName', 'mobile','openBank','bankAddress','bankNo', 'email'], 'trim'],
            [['userId', 'userName', 'zcPv', 'zcAmount', 'conUid', 'recUid', 'location'], 'required', 'on'=>'addWithUid'],
            [['userId', 'userName', 'zcPv', 'zcAmount', 'conUserName', 'recUserName', 'bottomUserName', 'location'], 'required', 'on'=>['addWithUserName', 'addByAdmin']],
            [['idCard', 'allData'], 'required', 'on'=>['addWithUserName']],
            [['userName'], 'required', 'on'=>['validateUser', 'noLoginModifyPassword']],
            [['conUid'], 'required', 'on'=>['validateCon', 'validateAddWithUid']],
            [['conUserName'], 'required', 'on'=>['validateConName', 'validateAddWithName']],
            [['recUid'], 'required', 'on'=>['validateRec', 'validateAddWithUid']],
            [['recUserName'], 'required', 'on'=>['validateRecName', 'validateAddWithName']],
            [['conUid', 'location'], 'required', 'on'=>['validateLocation', 'validateAddWithUid']],
            [['conUserName', 'location'], 'required', 'on'=>['validateLocationConName', 'validateAddWithName']],

            [[/*'nation',*/'realName', 'mobile', /*'idCard',*/ /*'openBank', 'bankAddress', 'bankNo'*//*, 'email'*/], 'required', 'on'=>'modifyProfile'],
            [['oldPassword','verifyPassword'], 'required','on' => ['modifyPassword', 'modifyPasswordPay', 'noLoginModifyPassword']],
            [['password'], 'required','on' => ['modifyPassword', 'noLoginModifyPassword']],
            [['payPassword'], 'required','on' => ['modifyPasswordPay']],
            ['verifyPassword', 'compare', 'compareAttribute' => 'password' ,'message'=>'The two login passwords are inconsistent' ,'on' => ['modifyPassword', 'noLoginModifyPassword']],//两次登录密码输入不一致
            ['verifyPassword', 'compare', 'compareAttribute' => 'payPassword' ,'message'=>'The two payment passwords are inconsistent' ,'on' => ['modifyPasswordPay']],//两次支付密码输入不一致
            [['userId'], 'unique', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['userName'], 'unique', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME' , 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['conUid'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['recUid'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['conUid'], 'isConUid', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['recUid'], 'isRecUid', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['conUserName'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['recUserName'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_NAME', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['conUserName'], 'isCon', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['recUserName'], 'isRec', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['location'], 'isLocation', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            //[['idCard'], 'isSameNetwork'],
            [['zcPv', 'zcAmount'], 'price', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['zcPv'], 'isMinDecLevel', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'userId' => '会员ID',
            'conUserName' => '接点人账号',
            'recUserName' => '开拓人帐号',
            'location' => '区位',
//            'nation' => '民族',
            //'realName' => '真实姓名',
//            'idCard' => '身份证号',
            //'mobile' => '手机号',
//            'openBank' => '银行名称',
//            'bankAddress' => '开户支行',
//            'bankNo' => '银行账号',
            'verifyPassword' => 'Confirm password',//确认密码
            'oldPassword' => 'Original password',//原密码
            'password' => 'Login password',//登录密码
            'payPassword' => 'Payment password',//支付密码
            'email' => 'Email',
        ];
    }

    /**
     * 接点人是否可以放置
     * @param $attribute
     * @param $params
     */
    public function isConUid($attribute, $params){
        $this->_conUid = $this->conUid;
        // 查看该接点人在安置网络中的推荐人数量是否达到上限
        $childNum = UserNetwork::firstFloorChildNum($this->_conUid);
        if($childNum >= 3){
//            $this->addError($attribute, '注册'.$this->userName.'时，接点人'.$this->conUserName.'点位已满无法继续添加');
        }
    }

    /**
     * 推荐人是否可用
     * @param $attribute
     * @param $params
     */
    public function isRecUid($attribute, $params){
        $this->_recUid = $this->recUid;
        // 查看该开拓者推荐的第一层人的数量
//        $childNum = UserRelation::firstFloorChildNum($this->_recUid);
//        if($childNum === 0){
//            // 必须放在自己的左区
//            if($this->location != 1){
//                $this->addError($attribute, '开拓的第一人必须放在自己的一市场');
//            }
//        }
    }

    /**
     * 接点人是否可以放置
     * @param $attribute
     * @param $params
     */
    public function isCon($attribute, $params){
        // 根据账号找到接点人
        $oneConUserInfo = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME'=>$this->conUserName]);
        if($oneConUserInfo){
            $this->_conUid = $oneConUserInfo['USER_ID'];
            // 查看该接点人在安置网络中的推荐人数量是否达到上限
            $childNum = UserNetwork::firstFloorChildNum($this->_conUid);
            if($childNum >= 3){
//                $this->addError($attribute, $this->userName.'的接点人'.$this->conUserName.'点位已满无法继续添加');
            }
        } else {
            $this->addError($attribute, '注册'.$this->userName.'时，接点人'.$this->conUserName.'帐号无效');
        }
    }

    /**
     * 推荐人是否可用
     * @param $attribute
     * @param $params
     */
    public function isRec($attribute, $params){
        // 根据账号找到开拓人
        $oneRecUserInfo = User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME'=>$this->bottomUserName]); //3790 (2026/1/21 14:59 Ryan)
        if($oneRecUserInfo && $oneRecUserInfo['STATUS']){
            $this->_recUid = $oneRecUserInfo['ID'];
            // 取消开拓的第一人必须放在自己的安置网下左区的需求
//            if($this->scenario != 'addByAdmin'){
//                // 查看该开拓者推荐的第一层人的数量
//                $childNum = UserRelation::firstFloorChildNum($this->_recUid);
//                if($childNum === 0){
//                    // 必须放在自己的左区
//                    if($this->location != 1 && $this->scenario != 'validateRecName'){
//                        $this->addError($attribute, '注册'.$this->userName.'时，开拓人'.$this->recUserName.'开拓的第一人必须放在自己的安置网络下的左区');
//                    }
//                }
//            }
        } else {
            $this->addError($attribute, '注册'.$this->userName.'时，开拓人'.$this->recUserName.'帐号无效或未激活');
        }
    }

    /**
     * 区位是否可用
     * @param $attribute
     * @param $params
     */
    public function isLocation($attribute, $params){
        // 查看该接点人下面所有的子会员
        $allChildUser = UserNetwork::getFirstFloorChildren($this->_conUid);
        if($allChildUser){
            $isLocation = [1=>false, 2=>false, 3=>false];
            foreach($allChildUser as $child){
                $isLocation[$child['RELATIVE_LOCATION']] = true;
                if($child['RELATIVE_LOCATION'] == $this->location){
                    $this->addError($attribute, '注册'.$this->userName.'时，'.$this->conUserName.'的区位【'.$this->location.'】已经存在会员');
                }
            }
            // 第二区不能空点，必须要有会员才能注册到第三区
//            if($this->location == 3 && $isLocation[2] === false){
//                $this->addError($attribute, '注册'.$this->userName.'到'.$this->conUserName.'的第三区时，'.$this->conUserName.'的第二区不能空点');
//            }
        } else {
//            if($this->location != 1 && $this->scenario != 'addByAdmin'){
//                $this->addError($attribute, '注册'.$this->userName.'时，接点人'.$this->conUserName.'下的第一个区位必须选择左区');
//            }
        }
    }

    /**
     * 校验注册PV必须要大于最低级别要求
     * @param $attribute
     * @param $params
     */
    public function isMinDecLevel($attribute, $params){
        // 获取排序为2的报单级别
        $decLevel = DeclarationLevel::getLevelFromSort(1);
        if($this->zcPv < $decLevel['PERF']){
            if($this->allData['hasInstalment'] && $this->zcPv + 30 >= $decLevel['PERF']){
            }else{
                $this->addError($attribute, '注册'.$this->userName.'时，注册PV低于最低级别要求，不能报首购单');
            }
        }
    }

    /**
     * 同一身份证号是否在相同网络
     * @param $attribute
     */
    public function isSameNetwork($attribute){
        // 新加入会员的身份证号对应网内的其他会员
        $otherUser = User::find()->where("ID_CARD=:ID_CARD AND ID<>:ID AND IS_UNION=0 AND DELETED=0 AND (ID_CARD_PREFIX IS NULL OR ID_CARD_PREFIX='')", [':ID_CARD'=>$this->idCard, ':ID'=>$this->userId])->select('ID')->asArray()->all();
        // 拿到所有的批量报单数据
        foreach($this->allData as $decData){
            if($decData['insertUserIdCard'] == $this->idCard){
                $otherUser[] = ['ID'=>$decData['toUserId']];
            }
        }
        // 从多轨网络里面找到这些会员的最顶层会员
        if($otherUser){
            $otherUserIds = [];
            foreach($otherUser as $userId){
                $otherUserIds[] = $userId['ID'];
            }
            $otherUserIdsStr = implode("','", $otherUserIds);
            $otherUserIdsStr = "'".$otherUserIdsStr."'";
            $sameIdCardOtherTopUser = UserInfo::find()->where('USER_ID IN ('.$otherUserIdsStr.')')->orderBy('NETWORK_DEEP ASC')->asArray()->one();
            if($sameIdCardOtherTopUser){
                // 通过这个顶层会员查看新报单会员的接点人是不是他的下级
                if(!UserNetwork::find()->where('PARENT_UID=:PARENT_UID AND USER_ID=:USER_ID', [':PARENT_UID'=>$sameIdCardOtherTopUser['USER_ID'], ':USER_ID'=>$this->_conUid])->exists()){
                    // 如果不存在的话，就看这个接点人是不是这个顶层的会员
                    if($this->_conUid != $sameIdCardOtherTopUser['USER_ID']){
                        $this->addError($attribute, '注册'.$this->userName.'时，同一身份证号会员必须在同一网体内');
                    }
                }
            }
        }
    }

    /**
     * 添加会员
     * @return UserInfo|null
     * @throws Exception
     */
    public function add(){
        if(!$this->validate()){
            return null;
        }
        $insertUid = $this->userId;
        $insertUserName = $this->userName;
        $zcPv = $this->zcPv;
        $conUid = $this->_conUid;   // 安置人

//        $recUid = $this->_recUid;   // 推荐人
//        // 实际推荐人
//        $recUidActual = User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->bottomUserName]);

        $recUid = $this->_recUid;   // 推荐人
        // 实际推荐人
        $recUidActual = User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $this->recUserName]);

//        $location = $this->location;

//        $db = \Yii::$app->db;
//        $transaction = $db->beginTransaction();
        try{
            $periodObj = Period::instance();
            $nowPeriodNum = $periodObj->getNowPeriodNum();
            // 查找接点人的体系信息
            $conUserInfo = UserInfo::find()->where('USER_ID=:USER_ID', [':USER_ID'=>$conUid])->asArray()->one();
            // 加入会员信息
            $userInfoModel = new UserInfo();
            $userInfoModel->USER_ID = $insertUid;
            $userInfoModel->USER_NAME = $insertUserName;
            $userInfoModel->ZC_PV = $zcPv;
            $userInfoModel->ZC_AMOUNT = $this->zcAmount;
            $userInfoModel->CON_UID = $conUid;
            $userInfoModel->REC_UID = $recUid;
            $userInfoModel->REC_UID_ACTUAL = $recUidActual['ID'];
            $userInfoModel->SYSTEM_ID = $conUserInfo['SYSTEM_ID'];
            //$userInfoModel->PERIOD_NUM = $nowPeriodNum;
            $userInfoModel->CREATED_AT = Date::nowTime();
            $userInfoModel->HIGHEST_EMP_LV = EmployLevel::getDefaultLevelId();
            $userInfoModel->ALLOW_TRANSFER = 1;
            $userInfoModel->HIGHEST_EMP_LV_PERIOD = $nowPeriodNum;
            $userInfoModel->TRANSFER_PROP = 100.00;
            $userInfoModel->IS_GROUP_LEADER = 0;
            $userInfoModel->GROUP_LEADER_AT = 0;
            if(!$userInfoModel->save()){
                throw new Exception('会员信息更新失败');
            }
            // 安置关系
//            $this->_addToNetwork();
            // 开拓关系
            $this->_addToRelation();
            // 把会员的网络深度也追加上
            $userInfoModel->NETWORK_DEEP = $this->_recTopDeep;
            $userInfoModel->RELATION_DEEP = $this->_recTopDeep;
            if(!$userInfoModel->save()){
                throw new Exception('会员网络深度更新失败');
            }
            // 清空安置网络和开拓网络的顶点和顶点深度的数值
            $this->_conTopUid = null;
            $this->_conTopDeep = null;
            $this->_recTopUid = null;
            $this->_recTopDeep = null;

//            $transaction->commit();
            return $userInfoModel;
        } catch (Exception $e){
//            $transaction->rollBack();
            $this->addError('userId', $e->getMessage());
            //echo $e->getMessage().PHP_EOL;
            return null;
        }
    }

    /**
     * 添加会员
     * @param $nowPeriodNum
     * @return boolean
     */
    public function addForImport($nowPeriodNum){
        $insertUid = $this->userId;
        $insertUserName = $this->userName;
        $zcPv = $this->zcPv;
        $conUid = $this->conUid;
        $recUid = $this->recUid;
        try{
            // 查找接点人的体系信息
            // 加入会员信息
            $insertData = [
                'USER_ID' => $insertUid,
                'USER_NAME' => $insertUserName,
                'ZC_PV' => $zcPv,
                'ZC_AMOUNT' => $this->zcAmount,
                'CON_UID' => $conUid,
                'REC_UID' => $recUid,
                'SYSTEM_ID' => "",
                'CREATED_AT' => time(),
                'HIGHEST_EMP_LV' => "",
                'HIGHEST_EMP_LV_PERIOD' => $nowPeriodNum,
                'TRANSFER_PROP' => 100.00,
                'IS_GROUP_LEADER' => 0,
                'GROUP_LEADER_AT' => 0,
            ];
            UserInfo::insertOne($insertData);
            unset($insertData);
            // 安置关系
//            $this->_addToNetworkForImport();
            // 开拓关系
            //$this->_addToRelationForImport();
            // 把会员的网络深度也追加上
            UserInfo::updateAll([
                "NETWORK_DEEP" => $this->_conTopDeep,
                //"RELATION_DEEP" => $this->_recTopDeep,
            ], "USER_ID='{$insertUid}'");
            // 清空安置网络和开拓网络的顶点和顶点深度的数值
            $this->_conTopUid = null;
            $this->_conTopDeep = null;
            $this->_recTopUid = null;
            $this->_recTopDeep = null;

            unset($insertUid, $insertUserName, $conUid, $recUid);
            return true;
        } catch (Exception $e){
            $this->addError('userId', $e->getMessage());
            return false;
        }
    }

    /**
     * 加入安置网络
     * @throws Exception
     */
    private function _addToNetworkForImport(){
        //获取上级的点位信息
        $conNetInfo = UserNetwork::findOneAsArray(['USER_ID'=>$this->conUid]);
        if( !$conNetInfo ) {
            throw new Exception('接点人信息不存在');
        }
        $this->_conTopUid = $conNetInfo['TOP_UID'];
        $this->_conTopDeep = $conNetInfo['TOP_DEEP'] + 1;
        // 加入安置网络关系
        $insertData = [
            'ID' => SnowFake::instance()->generateId(),
            "USER_ID"  => $this->userId,
            "PARENT_UID"  => $this->conUid,
            "LOCATION_TAG"  => $conNetInfo['LOCATION_TAG'] . $this->location,
            "RELATIVE_LOCATION"  => $this->location,
            "TOP_UID"  => $conNetInfo['TOP_UID'],
            "TOP_DEEP"  => $conNetInfo['TOP_DEEP'] + 1,
            "PARENT_UIDS"  => $conNetInfo['PARENT_UIDS'] . ',' . $this->conUid,
            "CREATED_AT"  => time(),
        ];
        UserNetwork::insertOne($insertData);

        if(!UserInfo::updateAllCounters(['CON_NUM'=>1], "USER_ID=:USER_ID", [':USER_ID'=>$this->conUid])){
            throw new Exception('会员安置关系下级节点数量更新失败');
        }
    }

    /**
     * 加入安置网络
     * @throws Exception
     */
    private function _addToNetwork(){
        //获取上级的点位信息
        $conNetInfo = UserNetwork::findOneAsArray(['USER_ID'=>$this->_conUid]);
        if( !$conNetInfo ) {
            throw new Exception('接点人信息不存在');
        }
        $this->_conTopUid = $conNetInfo['TOP_UID'];
        $this->_conTopDeep = $conNetInfo['TOP_DEEP'] + 1;
        // 加入安置网络关系
        if( $conNetInfo['PARENT_UIDS'] ) {
            $parentUids = $conNetInfo['PARENT_UIDS'] . ',' . $this->_conUid;
        }else {
            $parentUids = $this->_conUid;
        }
        $insertData = [
            'ID' => SnowFake::instance()->generateId(),
            "USER_ID"  => $this->userId,
            "PARENT_UID"  => $this->_conUid,
            "LOCATION_TAG"  => $conNetInfo['LOCATION_TAG'] . $this->location,
            "RELATIVE_LOCATION"  => $this->location,
            "TOP_UID"  => $conNetInfo['TOP_UID'],
            "TOP_DEEP"  => $conNetInfo['TOP_DEEP'] + 1,
            "PARENT_UIDS"  => $parentUids,
            "CREATED_AT"  => time(),
        ];
        UserNetwork::insertOne($insertData);

        if(!UserInfo::updateAllCounters(['CON_NUM'=>1], "USER_ID=:USER_ID", [':USER_ID'=>$this->_conUid])){
            throw new Exception('会员安置关系下级节点数量更新失败');
        }
    }

    /**
     * 加入开拓网络
     * @throws Exception
     */
    private function _addToRelationForImport(){
        //获取上级的推荐信息
        $conRelationInfo = UserRelation::findOneAsArray(['USER_ID'=>$this->recUid]);
        if( !$conRelationInfo ) {
            throw new Exception('推荐人信息不存在');
        }
        $this->_recTopUid = $conRelationInfo['TOP_UID'];
        $this->_recTopDeep = $conRelationInfo['TOP_DEEP'] + 1;
        // 加入推荐网络关系
        $insertData = [
            'ID' => SnowFake::instance()->generateId(),
            "USER_ID"  => $this->userId,
            "PARENT_UID"  => $this->recUid,
            "TOP_UID"  => $conRelationInfo['TOP_UID'],
            "TOP_DEEP"  => $conRelationInfo['TOP_DEEP'] + 1,
            "PARENT_UIDS"  => $conRelationInfo['PARENT_UIDS'] . ',' . $this->recUid,
            "CREATED_AT"  => time(),
        ];
        UserRelation::insertOne($insertData);

        if(!UserInfo::updateAllCounters(['REC_NUM'=>1], "USER_ID=:USER_ID", [':USER_ID'=>$this->recUid])){
            throw new Exception('会员开拓关系下级节点数量更新失败');
        }
    }

    /**
     * 加入开拓网络
     * @throws Exception
     */
    private function _addToRelation(){
        //获取上级的推荐信息
        $conRelationInfo = UserRelation::findOneAsArray(['USER_ID'=>$this->_recUid]);
        if( !$conRelationInfo ) {
            throw new Exception('推荐人信息不存在');
        }
        $this->_recTopUid = $conRelationInfo['TOP_UID'];
        $this->_recTopDeep = $conRelationInfo['TOP_DEEP'] + 1;
        if( $conRelationInfo['PARENT_UIDS'] ) {
            $parentUids = $conRelationInfo['PARENT_UIDS'] . ',' . $this->_recUid;
        }else {
            $parentUids = $this->_recUid;
        }
        // 加入推荐网络关系
        $insertData = [
            'ID' => SnowFake::instance()->generateId(),
            "USER_ID"  => $this->userId,
            "PARENT_UID"  => $this->_recUid,
            "TOP_UID"  => $conRelationInfo['TOP_UID'],
            "TOP_DEEP"  => $conRelationInfo['TOP_DEEP'] + 1,
            "PARENT_UIDS"  => $parentUids,
            "CREATED_AT"  => time(),
        ];
        UserRelation::insertOne($insertData);

        if(!UserInfo::updateAllCounters(['REC_NUM'=>1], "USER_ID=:USER_ID", [':USER_ID'=>$this->_recUid])){
            throw new Exception('会员开拓关系下级节点数量更新失败');
        }
    }

    /**
     * 修改个人资料
     * @return User|null
     */
    public function modifyProfile(){
        if(!$this->validate()){
            return null;
        }
        $this->userOperateLogger->beforeUpdate(\Yii::$app->user->id,'ID',['select'=>'NATION,OPEN_BANK,BANK_NO,BANK_ADDRESS,EMAIL']);

        $uid = \Yii::$app->user->id;
        $model = User::findOne(['ID'=>$uid]);
//        $model->NATION = $this->nation;
        //$model->REAL_NAME = $this->realName;
        //$model->MOBILE = $this->mobile;
        //$model->ID_CARD = $this->idCard;
//        $model->OPEN_BANK = $this->openBank;
//        $model->BANK_NO = $this->bankNo;
//        $model->BANK_ADDRESS = $this->bankAddress;
        $model->EMAIL = $this->email;
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        User::updateBaseInfoToRedis($uid);

        $this->userOperateLogger->afterUpdate(\Yii::$app->user->id,'ID',['select'=>'NATION,OPEN_BANK,BANK_NO,BANK_ADDRESS']);
        $this->userOperateLogger->clean()->save([
            'optType' => '会员修改资料',
            'userId' => \Yii::$app->user->id,
            'userName' => Info::getUserNameByUserId(\Yii::$app->user->id),
        ]);
        return $model;
    }
    /**
     * 修改密码
     */
    public function modifyPassword(){
        if(!$this->validate()){
            return null;
        }
        $uid = \Yii::$app->user->id;
        $model = User::findOne(['ID'=>$uid]);
        if ( !$model->validatePassword($this->oldPassword) ) {
            $this->addError('modifyPassword', Yii::t('app', 'originalLoginPasswordError'));
            return false;
        }
        $model->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return false;
        }
        return true;
    }
    /**
     * 修改支付密码
     */
    public function modifyPasswordPay(){
        if(!$this->validate()){
            return null;
        }
        $uid = \Yii::$app->user->id;
        $model = User::findOne(['ID'=>$uid]);
        if ( !$model->validatePasswordPay($this->oldPassword) ) {
            $this->addError('modifyPasswordPay', Yii::t('app', 'originalPaymentPasswordError'));
            return false;
        }
        $model->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($this->payPassword);
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return false;
        }
        return true;
    }


    /**
     * 不登录修改密码
     */
    public function noLoginModifyPassword(){
        if(!$this->validate()){
            return null;
        }
        $model =  User::findOne(["USER_NAME"=>$this->userName]);
        if( !$model ) {
            $this->addError('noLoginModifyPassword', Yii::t('app', 'userNameNotExists'));
            return false;
        }
        if ( !$model->validatePassword($this->oldPassword) ) {
            $this->addError('noLoginModifyPassword', Yii::t('app', 'originalLoginPasswordError'));
            return false;
        }
        $model->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($this->password);
        $model->IS_MODIFY_PASSWORD = 0;
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return false;
        }
        return true;
    }

}
