<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\User;
use common\models\UserBind;
use common\models\UserInfo;
use common\models\UserTeamwork;
use yii\base\Exception;

/**
 * 点位合作表单
 */
class UserTeamworkForm extends Model {
    public $id;
    public $type;
    public $userName;
    public $mainUserName;
    public $dividePercent;
    public $divideArr;
    public $nation;
    public $realName;
    public $idCard;
    public $mobile;
    public $address;
    public $openBank;
    public $bankAddress;
    public $bankNo;
    public $bankAreaSelected;
    public $areaSelected;
    public $tel;
    public $remark;


    const HAS_USER = 1;   // 在网站已有会员
    const NOT_USER = 0;   // 在网站没有会员

    private $_uid;
    private $_mainUid;
    private $_model;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'type', 'userName', 'mainUserName', 'dividePercent', 'nation', 'realName', 'idCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'areaSelected', 'tel', 'remark'], 'trim'],
            [['id', 'type', 'userName', 'mainUserName', 'dividePercent', 'idCard', 'realName'], 'required'],
            [['dividePercent'], 'price', 'message' => '分成比例必须是整数或者两位小数'],
            [['type'], 'boolean', 'message' => '添加类型格式不正确'],
            [['userName'], 'isUserName'],
            [['mobile', 'tel'], 'mobile'],
            [['bankNo'], 'string', 'max' => 19],
            [['mainUserName'], 'isMainUserName'],
            [['dividePercent'], 'isDivide'],
            [['divideArr'], 'isDivideArr'],
            [['id'], 'initModel'],
            [['userName'], 'userName'],
            [['idCard'], 'isIdCard'],
            [['realName','address','bankAddress'], 'realName'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['type', 'userName', 'mainUserName', 'dividePercent', 'nation', 'realName', 'idCard', 'mobile', 'address', 'openBank', 'bankAddress', 'bankNo', 'bankAreaSelected', 'areaSelected', 'tel', 'remark'],
            'changeDivide' => ['id', 'divideArr', 'remark'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'type' => '添加类型',
            'userName' => '会员编号',
            'mainUserName' => '主会员编号',
            'dividePercent' => '分成比例',
            'nation' => '民族',
            'realName' => '会员姓名',
            'idCard' => '身份证',
            'mobile' => '手机号',
            'address' => '地址',
            'openBank' => '开户行',
            'bankAddress' => '银行地址',
            'bankNo' => '银行账号',
            'bankAreaSelected' => '银行地区',
            'areaSelected' => '地区',
            'tel' => '电话',
            'remark' => '备注',
        ];
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = UserTeamwork::findOne(['ID' => $this->id]);
        if (!$this->_model) {
            $this->addError($attributes, 'The data does not exist'); // 数据不存在
        }
    }

    /**
     * 用户名是否正确
     * @param $attributes
     * @throws Exception
     */
    public function isUserName($attributes) {
        if ($this->userName == $this->mainUserName) {
            $this->addError($attributes, '同一会员不能合作');
        }
        if ($this->type == self::HAS_USER) {
            $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
            if ($userInfo) {
                $this->_uid = $userInfo['USER_ID'];
                if ($userInfo['IS_TEAM_MAIN'] == 1) {
                    $this->addError($attributes, '该会员是其他点位合作的主会员，无法添加');
                }
                $info = Info::baseInfo($this->_uid);
                /*if ($info['STATUS'] == UserStatusForm::STATUS_LOGOUT || $info['STATUS'] == UserStatusForm::STATUS_CLOSE) {
                    $this->addError($attributes, '注销或永久关停的会员不允许设置点位合作');
                }*/
                if ($info['STATUS'] != UserStatusForm::STATUS_NORMAL) {
                    $this->addError($attributes, '非正常的会员不允许设置点位合作');
                }
            } else {
                $this->addError($attributes, 'Member does not exist'); // 会员不存在
            }
        } else {
            if (strpos(strtolower($this->userName), 'hz') !== 0) {
                $this->addError($attributes, '无点位的会员编号必须是以hz开头');
            }
            if (!$this->realName || !$this->idCard) {
                $this->addError($attributes, '请详细填写新增无点位会员的相关信息');
            }
        }

    }

    /**
     * 主会员编号
     * @param $attributes
     * @throws Exception
     */
    public function isMainUserName($attributes) {
        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->mainUserName]);
        if ($userInfo) {
            if (UserTeamwork::find()->where('USER_ID=:USER_ID AND MAIN_UID!=:USER_ID AND IS_DEL=0', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
                $this->addError($attributes, '主会员已在其他点位有合作情况');
            }
            $info = Info::baseInfo($userInfo['USER_ID']);
            if ($info['STATUS'] != UserStatusForm::STATUS_NORMAL) {
                $this->addError($attributes, '非正常的主会员不允许设置点位合作');
            }
            $this->_mainUid = $userInfo['USER_ID'];
        } else {
            $this->addError($attributes, '主会员不存在');
        }
    }

    /**
     * 校验分成比例
     * @param $attributes
     * @return bool
     */
    public function isDivide($attributes) {
        /*$divideSum = UserTeamwork::findOneAsArray('USER_ID=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $this->_mainUid], 'DIVIDE_PERCENT');
        if ($divideSum && $divideSum['DIVIDE_PERCENT'] <= $this->dividePercent) {
            $this->addError($attributes, '该合作者的分成比例不能超过主会员分成比例【' . $divideSum . '】');
        }*/
    }

    /**
     * 校验身份证号
     * @param $attributes
     * @return bool
     */
    public function isIdCard($attributes) {
        if($user=User::findOneAsArray('ID_CARD=:ID_CARD',[':ID_CARD'=>$this->idCard],'REAL_NAME')){
            if($user['REAL_NAME']!=$this->realName){
                $this->addError($attributes, '填写的会员姓名与已经实名认证的会员姓名不一致');
            }
        }
    }

    /**
     * 校验分成数组
     * @param $attributes
     * @return bool
     */
    public function isDivideArr($attributes) {
        $sum = 0;
        foreach ($this->divideArr as $value) {
            if (!preg_match("/^[0-9]+([.]{1}[0-9]{1,2})?$/", $value['DIVIDE_PERCENT'])) {
                $this->addError($attributes, '分成比例必须是整数或者两位小数');
                return false;
            }
            $sum += $value['DIVIDE_PERCENT'];
        }
        if ($sum != 100) {
            $this->addError($attributes, '确保总分成比例为100');
        }
    }

    /**
     * 添加
     * @return UserTeamwork|null
     * @throws \yii\base\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            // 如果需要添加虚拟合作会员的，先新增会员
            if ($this->type == self::NOT_USER) {
                // 商城表增加会员
                $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 = $this->nation ? $this->nation : 1;
                $user->REAL_NAME = $this->realName;
                $user->ID_CARD = $this->idCard;
                $user->MOBILE = $this->mobile;
                $user->ADDRESS = $this->address ? $this->address : '无';
                $user->ADDRESS = '无';
                $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 = DeclarationLevel::getDefaultLevelId();
                $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->SUB_COM_ID = null;
                $user->AVATAR = 'avatar/1.png';
                $user->IS_DEC = 0;
                $user->DEC_ID = \Yii::$app->params['mainUserId'];
                $user->BIRTHDAY = null;
                $user->DEC_ROLE_ID = null;
                $user->PERIOD_AT = $period->getNowPeriodNum();
                $user->IS_UNION = 1;//合作会员标识
                $user->IS_DIRECT_SELLER = 0;
                $user->VERIFIED = 1;
                $user->VERIFIED_AT = Date::nowTime();;
                if (!$user->save()) {
                    throw new Exception(Form::formatErrorsForApi($user->getErrors()));
                }
                $this->_uid = $user->ID;
                // 结算表用户表增加会员但不写入点位关系
                $userInfoModel = new UserInfo();
                $userInfoModel->USER_ID = $this->_uid;
                $userInfoModel->USER_NAME = $this->userName;
                $userInfoModel->CON_UID = '0';
                $userInfoModel->REC_UID = '0';
                $userInfoModel->IS_TEAM = 1;
                //$userInfoModel->PERIOD_NUM = $period->getNowPeriodNum();
                $userInfoModel->CREATED_AT = Date::nowTime();
                $userInfoModel->HIGHEST_EMP_LV = EmployLevel::getDefaultLevelId();
                $userInfoModel->ALLOW_TRANSFER = 1;
                $userInfoModel->HIGHEST_EMP_LV_PERIOD = $period->getNowPeriodNum();
                $userInfoModel->TRANSFER_PROP = 100.00;
                $userInfoModel->IS_GROUP_LEADER = 0;
                if (!$userInfoModel->save()) {
                    throw new Exception(Form::formatErrorsForApi($userInfoModel->getErrors()));
                }
            }
            // 查看主点位是否已经存在
            if (!UserTeamwork::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->_mainUid, ':MAIN_UID' => $this->_mainUid])->exists()) {
                UserTeamwork::insertOne([
                    'USER_ID' => $this->_mainUid,
                    'MAIN_UID' => $this->_mainUid,
                    'DIVIDE_PERCENT' => 100 - $this->dividePercent,
                    'PERIOD_NUM' => $period->getNowPeriodNum(),
                    'IS_DEL' => 0,
                    'CREATE_REMARK' => $this->remark,
                    'CREATE_ADMIN' => \Yii::$app->user->id,
                    'CREATED_AT' => Date::nowTime(),
                ]);
            } else {
                $mainModel = UserTeamwork::findOne(['USER_ID' => $this->_mainUid]);
                $mainModel->DIVIDE_PERCENT = $mainModel->DIVIDE_PERCENT - $this->dividePercent;
                if (!$mainModel->save()) {
                    throw new Exception(Form::formatErrorsForApi($mainModel->getErrors()));
                }
            }
            // 会员信息表添加点位合作标识
            UserInfo::updateAll(['IS_TEAM' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_uid]);
            UserInfo::updateAll(['IS_TEAM' => 1, 'IS_TEAM_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_mainUid]);
            // 添加会员合作点位
            $model = new UserTeamwork();
            $model->USER_ID = $this->_uid;
            $model->MAIN_UID = $this->_mainUid;
            $model->DIVIDE_PERCENT = $this->dividePercent;
            $model->PERIOD_NUM = $period->getNowPeriodNum();
            $model->IS_DEL = 0;
            $model->CREATE_REMARK = $this->remark;
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //点位绑定
            UserBind::autoBind($this->_uid,$this->idCard,1);


            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            User::deleteAll(['ID'=>$this->_uid]);
            $this->addError('add', $e->getMessage());
            return null;
        }
        if ($this->type == self::NOT_USER) {
            $this->adminOperateLogger->fetchClass = User::class;
            $this->adminOperateLogger->afterInsert($this->_uid, 'ID', ['select' => 'ID,NATION,REAL_NAME,ID_CARD,ADDRESS,MOBILE,PROVINCE,CITY,COUNTY,OPEN_BANK,BANK_ADDRESS,BANK_NO,BANK_PROVINCE,BANK_CITY,BANK_COUNTY,TEL,CREATED_AT,IS_UNION']);
            $userData = $this->adminOperateLogger->saveAfterContent;
            $this->adminOperateLogger->fetchClass = UserTeamwork::class;
            $this->adminOperateLogger->afterInsert($model);
            $infoData = $this->adminOperateLogger->saveAfterContent;
            $this->adminOperateLogger->saveAfterContent = array_merge($userData, $infoData);
        }else{
            $this->adminOperateLogger->afterInsert($model);
        }
        $this->adminOperateLogger->clean()->save([
            'optType' => '添加合作点位',
            'userId' => $model->USER_ID,
            'userName' => Info::getUserNameByUserId($model->USER_ID),
            'remark' => $this->remark
        ]);
        return $model;
    }

    /**
     * 改变分成比例
     * @return array|null
     * @throws \yii\db\Exception
     */
    public function changeDivide() {
        if (!$this->validate()) {
            return null;
        }
        $logs = [];

        $ids = array_column($this->divideArr, 'ID');
        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($ids,'ID');

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            foreach ($this->divideArr as $value) {
                $model = UserTeamwork::findOne(['ID'=>$value['ID']]);
                $model->DIVIDE_PERCENT = $value['DIVIDE_PERCENT'];
                $model->UPDATE_ADMIN = \Yii::$app->user->id;
                $model->CREATE_REMARK = $this->remark;
                $model->UPDATED_PERIOD = $period->getNowPeriodNum();
                $model->UPDATED_AT = Date::nowTime();
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
                $logs[$value['USER_ID']] = $value['DIVIDE_PERCENT'];
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('changeDivide', $e->getMessage());
            return null;
        }

        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($ids,'ID');
        $this->adminOperateLogger->setOptObjField('USER_ID')->clean()->save([
            'optType' => '编辑合作点位',
            'remark' => $this->remark
        ]);
        return ['logs' => $logs];
    }

    /**
     * 删除
     * @param $selected
     */
    public static function delete($selected) {
        foreach ($selected as $select) {
            $userTeamwork = UserTeamwork::findOneAsArray('ID=:ID', [':ID' => $select], 'USER_ID');
            UserInfo::updateAll(['IS_TEAM' => 0, 'IS_TEAM_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userTeamwork['USER_ID']]);
            // 如果是主合作者位取消了合作，那么子合作者也自动同时取消合作
            if ($userTeamwork['USER_ID'] == $userTeamwork['MAIN_UID']) {
                $allTeamUser = UserTeamwork::findAllAsArray('MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userTeamwork['USER_ID']]);
                foreach ($allTeamUser as $user) {
                    UserInfo::updateAll(['IS_TEAM' => 0, 'IS_TEAM_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $user['USER_ID']]);
                }
                UserTeamwork::updateAll(['IS_DEL' => 1], 'MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userTeamwork['USER_ID']]);
            }
        }
    }
}
