<?php

namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\Tool;
use common\helpers\user\Balance;
use common\helpers\user\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\FlowBonus;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\DecOrder;
use common\models\EmployLevel;
use common\models\User;
use common\models\UserBind;
use common\models\UserBonus;
use common\models\UserInfo;
use common\models\UserMove;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\UserSystem;
use common\models\UserTeamwork;
use yii\base\Exception;

/**
 * Login form
 */
class AdminAddUserForm extends Model {
    public $userName;
    public $nation;
    public $realName;
    public $idCard;
    public $mobile;
    public $address;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $bankAreaSelected;
    public $decLv;
    public $areaSelected;
    public $tel;
    public $isDec;
    public $decUserName;
    public $birthday;
    public $decRoleId;
    public $conUserName;
    public $recUserName;
    public $location;
    public $delUserName;
    public $countryId;
    public $languageId;

    private $_decId;
    private $_delUserId;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['userName', 'nation', 'realName', /*'idCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'decLv', 'areaSelected', 'tel', 'isDec', 'decUserName', 'birthday', 'decRoleId', 'conUserName', 'recUserName', 'location', 'delUserName'], 'trim'],
            [['userName', 'realName', /*'idCard',*/ 'decLv', 'decUserName', 'conUserName', 'recUserName', 'location', 'countryId', 'languageId'], 'required'],
            [['userName'], 'unique', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['conUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['recUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['decLv'], 'exist', 'targetClass' => DeclarationLevel::class, 'targetAttribute' => 'ID'],
            [['mobile'], 'mobile'],
//            [['idCard'], 'simpleIdCard'],
            [['bankNo'], 'string', 'max' => 19],
            [['decUserName'], 'issetDec'],
            [['isDec'], 'issetDecRoleId'],
            [['location'], 'isLocation'],
            [['delUserName'], 'isDelUserName'],
            //[['userName'], 'userName'],
            [['realName', 'address', 'bankAddress'], 'realName'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['userName', 'nation', 'realName', /*'idCard',*/ 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'decLv', 'areaSelected', 'tel', 'isDec', 'decUserName', 'birthday', 'decRoleId', 'conUserName', 'recUserName', 'location', 'countryId', 'languageId'],
            'userDel' => ['delUserName'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userName' => 'Member Code',//会员编号
            'nation' => 'Nation',//民族
            'realName' => 'Member Name',//会员姓名
//            'idCard' => 'ID',//身份证号
            'mobile' => 'Phone Number',//手机号
            'address' => 'Address',//地址
            'openBank' => 'Bank Name',//开户行
            'bankAddress' => 'Account opening sub branch',//开户支行
            'bankNo' => 'Payment Reference',//银行账号
            'bankAreaSelected' => 'Banking region',//银行地区
            'decLv' => 'Real time declaration level',//实时报单级别
            'areaSelected' => 'Location',//所在地区
            'tel' => 'Telephone',//电话
            'isDec' => 'Stockist or not',//是否报单中心
            'decUserName' => 'Stockist No', // 报单中心编号
            'birthday' => 'birthday',//生日
            'decRoleId' => 'Stockist Level',//报单中心级别
            'conUserName' => 'Contact person Member No',//接点人会员编号
            'recUserName' => 'Sponsor Member No',
            'location' => 'Resettlement area',//安置区域
            'countryId' => 'Country',//国家
            'languageId' => 'Language',//语言
        ];
    }

    /**
     * 是否存在报单中心
     * @param $attribute
     */
    public function issetDec($attribute) {
        if (!$decUser = User::find()->select('ID')->where('IS_DEC=1 AND USER_NAME=:USER_NAME', [':USER_NAME' => $this->decUserName])->asArray()->one()) {
            $this->addError($attribute, 'Stockist does not exist');//报单中心不存在
        } else {
            $this->_decId = $decUser['ID'];
        }
    }

    /**
     * 校验是否填写报单中心级别
     * @param $attribute
     */
    public function issetDecRoleId($attribute) {
        if ($this->isDec && !$this->decRoleId) {
            $this->addError($attribute, 'Stockist level cannot be empty');//报单中心级别不能为空
        }
    }

    public function isLocation($attribute) {
        if (!in_array($this->location, ['1', '2', '3'])) {
            $this->addError($attribute, 'Location error');//区位错误
        }
    }

    /**
     * 校验删除的用户是否符合条件
     * @param $attribute
     */
    public function isDelUserName($attribute) {
        if (!$this->_delUserId = Info::getUserIdByUserName($this->delUserName)) {
            $this->addError($attribute, 'user does not exist');//用户不存在
        }
        if (UserInfo::findOneAsArray('REC_UID=:REC_UID AND DELETED=0', [':REC_UID' => $this->_delUserId], 'USER_ID')) {
            $this->addError($attribute, 'This member has developed other members and cannot be deleted');//此会员已开拓其它会员不可以删除
        }
        if (UserInfo::findOneAsArray('CON_UID=:CON_UID AND DELETED=0', [':CON_UID' => $this->_delUserId], 'USER_ID')) {
            $this->addError($attribute, 'This member has been placed with other members and cannot be deleted');//此会员已安置其它会员不可以删除
        }
        if (User::findOneAsArray('DEC_ID=:DEC_ID AND DELETED=0', [':DEC_ID' => $this->_delUserId], 'ID')) {
            $this->addError($attribute, 'This member has submitted a bill and other members cannot delete it');//此会员已报单其它会员不可以删除
        }
        if (DecOrder::findOneAsArray('USER_ID=:TO_USER_ID OR TO_USER_ID=:TO_USER_ID', [':TO_USER_ID' => $this->_delUserId], 'ID')) {
            $this->addError($attribute, 'This member has submitted a bill and cannot be deleted');//此会员已报单不可以删除
        }
        $info = Info::baseInfoWithNet($this->_delUserId);
        if ($info['REG_FROM'] == 1) {
            $this->addError($attribute, 'This member is not empty and cannot be deleted');//此会员不是空单无法删除
        }
        $sentMaxPeriodNum = Period::sentMaxPeriodNum();
        if ($info['PERIOD_AT'] <= $sentMaxPeriodNum) {
            $this->addError($attribute, 'The number of enrollment periods of this member is less than or equal to the number of online periods');//此会员加入期数小于等于已挂网期数
        }
        if (User::find()->where('ID=:ID AND VERIFIED=1', [':ID' => $this->_delUserId])->exists()) {
            $this->addError($attribute, 'This member has been authenticated by real name and cannot be deleted');//此会员已实名认证无法删除
        }
        if (User::find()->where('ID=:ID AND SUB_COM_LEADER=1', [':ID' => $this->_delUserId])->exists()) {
            $this->addError($attribute, 'This member is a branch leader and cannot be deleted');//此会员是分公司领导人无法删除
        }
        if (UserInfo::find()->where('USER_ID=:USER_ID AND (IS_GROUP_LEADER=1 OR IS_SYSTEM_LEADER=1 OR IS_BIND=1 OR IS_TEAM=1)', [':USER_ID' => $this->_delUserId])->exists()) {
            $this->addError($attribute, 'This member cannot be deleted due to the following conditions: Team Leader / system leader / point binding / point cooperation');//此会员存在以下情况无法删除，团队领导人/体系领导人/点位绑定/点位合作
        }
        if (Balance::hasBonus($this->_delUserId)) {
            $this->addError($attribute, 'This member has balance and cannot be deleted');//此会员有余额无法删除
        }
        if (FlowBonus::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId], 'ID')) {
            $this->addError($attribute, 'This member has generated a balance flow, which cannot be deleted');//该会员产生过余额流水无法删除
        }
        if (UserMove::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId], 'ID')) {
            $this->addError($attribute, 'The member cannot be deleted due to network migration');//该会员发生过移网无法删除
        }
    }

    /**
     * 添加
     * @return User|null
     * @throws \yii\db\Exception
     */
    public function edit() {
        $this->userName = strtoupper($this->userName);
        if (!$this->validate()) {
            return null;
        }
        $transactionShop = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            // 商城表增加会员
            $user = new User();
            $user->USER_NAME = $this->userName;
            $pwd = Info::passwordGenerator($this->idCard,$user->USER_NAME);
            $user->PASSWORD_HASH = \Yii::$app->security->generatePasswordHash($pwd);
            $pwd = Info::passwordGenerator($this->idCard,$user->USER_NAME,true);
            $user->PAY_PASSWORD = \Yii::$app->security->generatePasswordHash($pwd);
            $user->NATION = 0;
            $user->REAL_NAME = $this->realName;
//            $user->ID_CARD = $this->idCard;
            $user->MOBILE = $this->mobile;
            $user->ADDRESS = $this->address ? $this->address : 'nothing';//无
            $user->OPEN_BANK = $this->openBank;
            $user->BANK_ADDRESS = $this->bankAddress;
            $user->BANK_NO = $this->bankNo;
            $user->BANK_PROVINCE = $this->bankAreaSelected[0] ?? '0';
            $user->BANK_CITY = $this->bankAreaSelected[1] ?? '0';
            $user->BANK_COUNTY = $this->bankAreaSelected[2] ?? '0';
            $user->CREATED_AT = Date::nowTime();
            $user->STATUS = 1;
            $user->DEC_LV = $this->decLv;
            $user->LAST_DEC_LV = $this->decLv;
            $user->EMP_LV = EmployLevel::getDefaultLevelId();
            $user->PROVINCE = $this->areaSelected[0] ?? '0';
            $user->CITY = $this->areaSelected[1] ?? '0';
            $user->COUNTY = $this->areaSelected[2] ?? '0';
            //$user->TEL = $this->tel;
            //$user->REG_IS_COMPLETED = 1;
            $user->AVATAR = 'avatar/1.png';
            $user->IS_DEC = $this->isDec ? $this->isDec : 0;
            $user->DEC_ID = $this->_decId ?? null;
            //$user->BIRTHDAY = Date::ociToDate($this->birthday, Date::OCI_TIME_FORMAT_DATE);
            $user->DEC_ROLE_ID = $this->decRoleId ?? null;
            $user->PERIOD_AT = $period->getNowPeriodNum();
            $user->REG_FROM = 0;//空单标识
            $user->IS_DIRECT_SELLER = 0;
            $user->VERIFIED = 1;
            $user->VERIFIED_AT = Date::nowTime();
            $user->USER_CREATOR = Admin::getAdminNameById(\Yii::$app->user->id);
            $user->IS_RECHARGE = 1;
            $user->COUNTRY_ID = $this->countryId;
            $user->LANGUAGE_ID = $this->languageId;
            if (!$user->save()) {
                throw new Exception(Form::formatErrorsForApi($user->getErrors()));
            }
            // 获取报单级别的设置
            $decLevelConfig = Cache::getDecLevelConfig();
            $decLevelPv = $decLevelConfig[$this->decLv]['PERF'];
            $userForm = new UserForm();
            $userForm->scenario = 'addByAdmin';
            $userForm->userId = $user->ID;
            $userForm->userName = $this->userName;
            $userForm->zcAmount = $decLevelPv;
            $userForm->zcPv = $decLevelPv;
            $userForm->conUserName = $this->conUserName;
            $userForm->recUserName = $this->recUserName;
            $userForm->location = $this->location;
            if (!$userForm->add()) {
                throw new Exception(Form::formatErrorsForApi($userForm->getErrors()));
            }
            $transactionShop->commit();
        } catch (Exception $e) {
            $transactionShop->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }

        $select = new \yii\db\Expression('ID,REAL_NAME,ID_CARD,MOBILE,ADDRESS,OPEN_BANK,BANK_ADDRESS,BANK_NO,BANK_PROVINCE,BANK_CITY,BANK_COUNTY,CREATED_AT,DEC_LV,EMP_LV,PROVINCE,CITY,COUNTY,TEL,SUB_COM_ID,IS_DEC,DEC_ID,DEC_ROLE_ID,PERIOD_AT,REG_FROM');
        $this->adminOperateLogger->afterInsert($user->ID, 'ID', ['select'=>$select]);
        $userData = $this->adminOperateLogger->saveAfterContent;
        $this->adminOperateLogger->fetchClass = UserInfo::class;
        $this->adminOperateLogger->afterInsert($user->ID, 'USER_ID', ['select'=>'USER_ID,CON_UID,REC_UID']);
        $infoData = $this->adminOperateLogger->saveAfterContent;
        $this->adminOperateLogger->saveAfterContent=array_merge($userData,$infoData);

        $this->adminOperateLogger->clean()->save([
            'optType' => 'Blank document entry',//空单录入
            'userId' => $user->ID,
            'userName' => $user->USER_NAME,
        ]);

        return $user;
    }

    /**
     * 删除会员
     * @return null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function userDel() {
        if (!$this->validate()) {
            return null;
        }

        $select = new \yii\db\Expression('ID,REAL_NAME,ID_CARD,MOBILE,ADDRESS,OPEN_BANK,BANK_ADDRESS,BANK_NO,BANK_PROVINCE,BANK_CITY,BANK_COUNTY,CREATED_AT,DEC_LV,EMP_LV,PROVINCE,CITY,COUNTY,TEL,SUB_COM_ID,IS_DEC,DEC_ID,DEC_ROLE_ID,PERIOD_AT,REG_FROM');
        $this->adminOperateLogger->beforeDelete($this->_delUserId, 'ID', ['select'=>$select]);
        $userData = $this->adminOperateLogger->saveBeforeContent;
        $this->adminOperateLogger->fetchClass = UserInfo::class;
        $this->adminOperateLogger->beforeDelete($this->_delUserId, 'USER_ID', ['select'=>'USER_ID,CON_UID,REC_UID']);
        $infoData = $this->adminOperateLogger->saveBeforeContent;
        $this->adminOperateLogger->saveBeforeContent=array_merge($userData,$infoData);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            /*$user=User::findOne(['ID'=>$this->_delUserId]);
            $user->DELETED=1;
            $user->DELETED_AT=Date::nowTime();
            if(!$user->save()){
                throw new Exception(Form::formatErrorsForApi($user->getErrors()));
            }
            $userInfo=UserInfo::findOne(['USER_ID'=>$this->_delUserId]);
            $userInfo->DELETED=1;
            $userInfo->DELETED_AT=Date::nowTime();
            if(!$userInfo->save()){
                throw new Exception(Form::formatErrorsForApi($userInfo->getErrors()));
            }*/
            //为释放用户名资源，彻底删除@190606
            User::deleteAll('ID=:USER_ID', [':USER_ID' => $this->_delUserId]);

            // 获取会员信息
            $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$this->_delUserId]);
            // 调整上级会员的CON_NUM和REC_NUM
            if(!UserInfo::updateAllCounters(['CON_NUM'=> -1], "USER_ID=:USER_ID", [':USER_ID'=>$userInfo['CON_UID']])){
                throw new Exception('Failed to reduce the number of superior member contacts');//减少上级会员接点数量失败
            }
            if(!UserInfo::updateAllCounters(['REC_NUM'=> -1], "USER_ID=:USER_ID", [':USER_ID'=>$userInfo['REC_UID']])){
                throw new Exception('Failed to reduce the number of recommended Sponsor');//减少开拓人推荐数量失败
            }
            // 删除会员信息
            if(!UserInfo::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId])){
                throw new Exception('Failed to delete member information');//删除会员信息失败
            }
            //删除安置
            if(!UserNetwork::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId])){
                throw new Exception('Failed to delete member placement data');//删除会员安置数据失败
            }
            //删除开拓
            if(!UserRelation::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId])){
                throw new Exception('Failed to delete member development data');//删除会员开拓数据失败
            }
            //删除点位绑定
            UserBind::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId]);
            //删除合作
            UserTeamwork::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId]);
            //删除奖金
            UserBonus::deleteAll('USER_ID=:USER_ID', [':USER_ID' => $this->_delUserId]);

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            throw new Exception($e->getMessage());
        }

        $this->adminOperateLogger->clean()->save([
            'optType' => 'Delete empty member',//删除空单会员
        ]);
        return $this->_delUserId;
    }
}
