<?php

namespace common\models\forms;

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

/**
 * 点位绑定表单
 */
class UserBindForm extends Model {
    public $id;
    public $userId;
    public $mainUid;
    public $userName;
    public $mainUserName;

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

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'userName', 'mainUserName', 'mainUid', 'userId'], 'trim'],
            [['id', 'userName', 'mainUserName'], 'required'],
            [['userName'], 'isUserName'],
            [['mainUserName'], 'isMainUserName'],
            //[['mainUid'], 'isMainUid'],
            //[['userId'], 'isUserId'],
            [['id'], 'initModel'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['userName', 'mainUserName'],
            'edit' => ['id', 'mainUid'],
            'frontEdit' => ['id', 'mainUid'],
            'autoBind' => ['userId', 'mainUid'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userName' => '会员编号',
            'mainUserName' => '主会员编号',
        ];
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = UserBind::findOne(['ID' => $this->id]);
        if (!$this->_model) {
            $this->addError($attributes, 'The data does not exist'); // 数据不存在
        }
        if($this->scenario=='frontEdit'){
            if (Info::getIdCardByUserId(\Yii::$app->user->id) != Info::getIdCardByUserId($this->_model['MAIN_UID'])) {
                $this->addError($attributes, '无权限编辑');
            }
        }
    }

    /**
     * 用户名是否正确
     * @param $attributes
     */
    public function isUserName($attributes) {
        if ($this->userName == $this->mainUserName) {
            $this->addError($attributes, '同一会员不能绑定');
        }
        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->userName]);
        if ($userInfo && Info::isVerified(($userInfo['USER_ID']))) {
            if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
                $this->addError($attributes, '填写的会员已有绑定关系');
            }
            $this->_uid = $userInfo['USER_ID'];
        } else {
            $this->addError($attributes, '会员不存在或未完成实名认证');
        }

    }

    /**
     * 主会员编号
     * @param $attributes
     */
    public function isMainUserName($attributes) {
        $userInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->mainUserName]);
        if ($userInfo && Info::isVerified(($userInfo['USER_ID']))) {
            if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0 AND MAIN_UID!=:USER_ID', [':USER_ID' => $userInfo['USER_ID']])->exists()) {
                $this->addError($attributes, '填写的主会员已被其他主会员绑定');
            }
            $this->_mainUid = $userInfo['USER_ID'];
        } else {
            $this->addError($attributes, '主会员不存在或未完成实名认证');
            return false;
        }
        if (Info::getIdCardByUserId($this->_uid) != Info::getIdCardByUserId($this->_mainUid)) {
            $this->addError($attributes, '两个会员身份证号不一致无法绑定');
        }
        $idCard = Info::getIdCardByUserId($this->_mainUid);
        //是否有其他绑定关系
        $hasUsers = User::find()->select('ID')->where('ID!=:ID AND ID!=:IDU AND VERIFIED=1 AND ID_CARD=:ID_CARD', [':ID' => $this->_mainUid, ':IDU'=>$this->_uid, ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->all();
        if($hasUsers){
            foreach ($hasUsers as $u){
                if (UserBind::find()->where('USER_ID=:USER_ID AND IS_DEL=0 AND MAIN_UID!=:MAIN_UID', [':USER_ID' => $u['ID'], ':MAIN_UID'=>$this->_mainUid])->exists()) {
                    $this->addError($attributes, '身份证'.$idCard.'有其他的绑定关系，请查证');
                    break;
                }
            }
        }
    }

    public function isMainUid($attributes) {
        if(!Info::isVerified($this->mainUid)){
            $this->addError($attributes, '主会员未完成实名认证');
            return false;
        }
    }

    public function isUserId($attributes) {
        if(!Info::isVerified($this->userId)){
            $this->addError($attributes, '会员未完成实名认证');
            return false;
        }
    }



    /**
     * 添加
     * @return UserBind|null
     * @throws \yii\base\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();

            // 查看主点位是否已经存在
            if (!UserBind::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->_mainUid, ':MAIN_UID' => $this->_mainUid])->exists()) {
                UserBind::insertOne([
                    'USER_ID' => $this->_mainUid,
                    'MAIN_UID' => $this->_mainUid,
                    'PERIOD_NUM' => $period->getNowPeriodNum(),
                    'IS_DEL' => 0,
                    'CREATE_ADMIN' => \Yii::$app->user->id,
                    'CREATED_AT' => Date::nowTime(),
                ]);
            }
            // 会员信息表添加点位合作标识
            UserInfo::updateAll(['IS_BIND' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_uid]);
            UserInfo::updateAll(['IS_BIND' => 1, 'IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_mainUid]);
            // 添加会员合作点位
            $model = new UserBind();
            $model->USER_ID = $this->_uid;
            $model->MAIN_UID = $this->_mainUid;
            $model->PERIOD_NUM = $period->getNowPeriodNum();
            $model->IS_DEL = 0;
            $model->CREATE_ADMIN = \Yii::$app->user->id;
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->afterInsert($model);
        $this->adminOperateLogger->clean()->save([
            'optType' => '添加点位绑定',
            'userId' => $model->USER_ID,
            'userName' => Info::getUserNameByUserId($model->USER_ID),
        ]);
        return $model;
    }

    /**
     * 前台编辑主点位
     * @return null
     * @throws \yii\db\Exception
     */
    public function frontEdit() {
        if (!$this->validate()) {
            return null;
        }

        $this->userOperateLogger->beforeUpdate($this->_model->ID,'ID',['select'=>'USER_ID,MAIN_UID']);
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            if ($model->MAIN_UID == $this->mainUid) {
                throw new Exception('未做任何修改');
            }
            //撤销主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $model->MAIN_UID]);
            //设置主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
            //更新绑定表的主会员
            UserBind::updateAll(['MAIN_UID' => $this->mainUid, 'UPDATED_AT' => Date::nowTime(), 'UPDATE_ADMIN' => \Yii::$app->user->id], 'MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $model->MAIN_UID]);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('frontEdit', $e->getMessage());
            return null;
        }
        $this->userOperateLogger->afterUpdate($this->_model->ID,'ID',['select'=>'USER_ID,MAIN_UID']);

        $this->userOperateLogger->clean()->save([
            'optType' => '修改主点位',
            'userId' => $model->USER_ID,
            'userName' => Info::getUserNameByUserId($model->USER_ID),
        ]);
        return $model;
    }

    /**
     * 编辑主点位
     * @return null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }

        $this->adminOperateLogger->beforeUpdate($this->_model);

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            if ($model->MAIN_UID == $this->mainUid) {
                throw new Exception('未做任何修改');
            }
            //撤销主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $model->MAIN_UID]);
            //设置主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
            //更新绑定表的主会员
            UserBind::updateAll(['MAIN_UID' => $this->mainUid, 'UPDATED_AT' => Date::nowTime(), 'UPDATE_ADMIN' => \Yii::$app->user->id], 'MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $model->MAIN_UID]);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->afterUpdate(UserBind::findOne(['ID' => $this->id]));
        $this->adminOperateLogger->clean()->save([
            'optType' => '编辑点位绑定',
            'userId' => $model->USER_ID,
            'userName' => Info::getUserNameByUserId($model->USER_ID),
        ]);
        return $model;
    }

    public function beforeDelete($selected){
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }

    /**
     * 删除
     * @param $selected
     * @throws Exception
     */
    public function delete($selected) {
        foreach ($selected as $select) {
            $userBind = UserBind::findOneAsArray('ID=:ID', [':ID' => $select], 'USER_ID,MAIN_UID');
            //无法删除有子会员的
            if (UserBind::find()->where('MAIN_UID=:USER_ID AND IS_DEL=0 AND USER_ID!=:USER_ID', [':USER_ID' => $userBind['USER_ID']])->exists()) {
                throw new Exception('该主会员有子会员，无法撤销');
            }
            UserInfo::updateAll(['IS_BIND' => 0, 'IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['USER_ID']]);
            User::updateAll(['VERIFIED' => 0], 'ID=:USER_ID', [':USER_ID' => $userBind['USER_ID']]);
            $bindNum = UserBind::findOneAsArray('IS_DEL=0 AND MAIN_UID=:MAIN_UID', [':MAIN_UID' => $userBind['MAIN_UID']],'COUNT(*) AS NUM');
            if (isset($bindNum['NUM']) && $bindNum['NUM'] < 2) {
                UserBind::updateAll(['IS_DEL' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['MAIN_UID']]);
                UserInfo::updateAll(['IS_BIND' => 0, 'IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userBind['MAIN_UID']]);
            }
        }
        $this->adminOperateLogger->clean()->save([
            'optType' => '撤销点位绑定',
        ]);
    }

    /**
     * 自动绑定点位
     * @return UserBind|null
     * @throws \yii\db\Exception
     */
    public function autoBind() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //判断hz
            if (Info::isUnion($this->mainUid) && !Info::isUnion($this->userId)) {
                $userId = $this->mainUid;
                $this->mainUid = $this->userId;
                $this->userId = $userId;
            }

            $period = Period::instance();
            // 查看主点位是否已经存在
            if (!UserBind::find()->where('USER_ID=:USER_ID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':USER_ID' => $this->mainUid, ':MAIN_UID' => $this->mainUid])->exists()) {
                UserBind::insertOne([
                    'USER_ID' => $this->mainUid,
                    'MAIN_UID' => $this->mainUid,
                    'PERIOD_NUM' => $period->getNowPeriodNum(),
                    'IS_DEL' => 0,
                    'CREATE_ADMIN' => \Yii::$app->id == 'app-backendApi' ? \Yii::$app->user->id : null,
                    'CREATED_AT' => Date::nowTime(),
                ]);
            }
            // 会员信息表添加点位合作标识
            UserInfo::updateAll(['IS_BIND' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->userId]);
            UserInfo::updateAll(['IS_BIND' => 1, 'IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $this->mainUid]);
            // 添加会员合作点位
            $model = new UserBind();
            $model->USER_ID = $this->userId;
            $model->MAIN_UID = $this->mainUid;
            $model->PERIOD_NUM = $period->getNowPeriodNum();
            $model->IS_DEL = 0;
            $model->CREATE_USER = $this->userId;
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('autoAdd', $e->getMessage());
            return null;
        }
        return $model;
    }

}
