<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\helpers\user\Info;
use common\libs\logging\operate\UserOperate;
use common\models\BaUser;
use common\models\BaUserInfo;
use common\models\User;
use common\models\UserInfo;
use Yii;
use yii\db\Exception;

/**
 * Login form
 */
class BaUserForm extends Model
{
    public $userId;
    public $userName;
    public $zcPv;
    public $zcAmount;
    public $conUserName;
    public $recUserName;
    public $conUid;
    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 $_limit = 1000;

    private $_conTopDeep;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userId', 'userName', 'zcPv', 'zcAmount', 'conUserName', 'recUserName','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', /*'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'=>BaUserInfo::class, 'targetAttribute'=>'USER_ID', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['userName'], 'unique', 'targetClass'=>BaUserInfo::class, 'targetAttribute'=>'USER_NAME' , 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [['recUid'], 'exist', 'targetClass'=>UserInfo::class, 'targetAttribute'=>'USER_ID', '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']],
            [['recUserName'], 'isRec', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
            [[/*'zcPv',*/ 'zcAmount'], 'price', 'on' => ['addWithUserName', 'addWithUid', 'addByAdmin']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'userId' => '会员ID',
            'recUserName' => '开拓人帐号',
            'verifyPassword' => 'Confirm password',//确认密码
            'oldPassword' => 'Original password',//原密码
            'password' => 'Login password',//登录密码
            'payPassword' => 'Payment password',//支付密码
            'email' => 'Email',
        ];
    }

    /**
     * 推荐人是否可用
     * @param $attribute
     * @param $params
     */
    public function isRecUid($attribute, $params) {
        $this->_recUid = $this->recUid;
    }

    /**
     * 推荐人是否可用
     * @param $attribute
     * @param $params
     */
    public function isRec($attribute, $params){
        // 根据账号找到开拓人
        $oneRecUserInfo = User::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME'=>$this->recUserName]);
        if($oneRecUserInfo && $oneRecUserInfo['STATUS']){
            $this->_recUid = $oneRecUserInfo['ID'];
        } else {
            $this->addError($attribute, '注册'.$this->userName.'时，开拓人'.$this->recUserName.'帐号无效或未激活');
        }
    }

    /**
     * 添加会员
     */
    public function add()
    {
        if(!$this->validate()){
            return null;
        }

        $insertUid = $this->userId;
        $insertUserName = $this->userName;
        $recUid = $this->_recUid;

        try {
            // 加入会员信息
            $userInfoModel = new BaUserInfo();
            $userInfoModel->USER_ID = $insertUid;
            $userInfoModel->USER_NAME = $insertUserName;
            $userInfoModel->ZC_AMOUNT = $this->zcAmount;
            $userInfoModel->CON_UID = '';
            $userInfoModel->REC_UID = $recUid;
            $userInfoModel->CREATED_AT = Date::nowTime();
            $userInfoModel->ALLOW_TRANSFER = 1;
            $userInfoModel->TRANSFER_PROP = 100.00;
            $userInfoModel->IS_GROUP_LEADER = 0;
            $userInfoModel->GROUP_LEADER_AT = 0;
            $userInfoModel->save();

            return $userInfoModel;
        } catch (Exception $e) {
            $this->addError('userId', $e->getMessage());
            return 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 = BaUser::findOne(['ID'=>$uid]);
        $model->EMAIL = $this->email;
        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return null;
        }
        BaUser::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 = BaUser::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 = BaUser::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;
    }
}
