<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\Log;
use common\helpers\user\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\BonusAsync;
use common\models\Period;
use common\models\UserInfo;
use common\models\UserRelation;
use common\models\UserSystem;
use yii\base\Exception;

/**
 * Login form
 */
class UserSystemForm extends Model {
    public $id;
    public $systemName;
    public $leaderUserName;
    public $remark;

    private $_leaderUid;
    private $_tempSystemLeaders = [];  // 用于循环给下级设置体系的时候，临时设置子集领导的数组
    private $_limit = 2;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'systemName', 'leaderUserName', 'remark'], 'trim'],
            [['id', 'systemName', 'leaderUserName'], 'required'],
            [['systemName'], 'unique', 'on' => 'update', 'targetClass' => UserSystem::class, 'targetAttribute' => 'SYSTEM_NAME', 'when' => function ($model) {
                return $model->isAttributeChanged('SYSTEM_NAME');
            }],
            [['leaderUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['id'], 'exist', 'targetClass' => UserSystem::class, 'targetAttribute' => 'ID', 'on'=>'renewSystem'],
            [['leaderUserName'], 'isLeaderUser'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'add' => ['systemName', 'leaderUserName','remark'],
            'edit' => ['systemName','leaderUserName', 'remark'],
            'renewSystem' => ['id'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'systemName' => '体系名称',
            'leaderUserName' => '领导人会员编号',
        ];
    }

    public function isLeaderUser($attributes) {
        $leaderUserInfo = UserInfo::findOneAsArray(['USER_NAME' => $this->leaderUserName]);
        if ($leaderUserInfo) {
            $this->_leaderUid = $leaderUserInfo['USER_ID'];
        }
    }

    /**
     * 页面端编辑
     * @return UserSystem|null|static
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        return $this->_editHandle();
    }

    /**
     * 恢复
     * @return UserSystem|null
     * @throws \yii\db\Exception
     */
    public function renewSystem(){
        if (!$this->validate()) {
            return null;
        }
        return $this->_editHandle();
    }

    /**
     * 撤销体系前
     * @param $selected
     * @throws Exception
     */
    public function beforeDelete($selected) {
        $this->adminOperateLogger->setIsBatch(true)->setOptObjField('LEADER_UID')->beforeDelete($selected, 'ID');
        foreach ($selected as $id) {
            $period = Period::instance();
            $model = UserSystem::findOne(['ID' => $id]);
            $model->UPDATED_AT = Date::nowTime();
            $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
            $model->UPDATE_ADMIN = \Yii::$app->user->id;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $leaderUid = $model->LEADER_UID;
            // 把该体系对应的领导人及下级所有是该体系的会员，全部改为上级的体系
            // 获取该体系的上级会员所在的体系
            $parentUserInfo = UserRelation::getFirstParentUserInfo($leaderUid);
            if ($parentUserInfo) {
                $newSystemId = $parentUserInfo['SYSTEM_ID'];
            } else {
                $newSystemId = null;
            }
            UserInfo::updateAll(['IS_SYSTEM_LEADER' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $leaderUid]);
            // 把该体系的所有体系都改成新体系
            UserInfo::updateAll(['SYSTEM_ID' => $newSystemId], 'SYSTEM_ID=:SYSTEM_ID AND IS_SYSTEM_LEADER=0', [':SYSTEM_ID' => $id]);
        }
    }

    /**
     * 撤销体系
     * @param $selected
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => '撤销体系',
        ]);
    }

    /**
     * 处理编辑
     * @return UserSystem|null
     * @throws \yii\db\Exception
     */
    private function _editHandle() {
        if($this->scenario!='add'){
            $this->adminOperateLogger->beforeUpdate(UserSystem::findOne(['ID' => $this->id]));
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            if ($this->scenario == 'add') {
                $model = new UserSystem();
                $model->SYSTEM_NAME = $this->systemName;
                $model->LEADER_UID = $this->_leaderUid;
                $model->PERIOD_NUM = $period->getNowPeriodNum();
                $model->CREATE_REMARK = $this->remark;
                $model->CREATE_ADMIN = \Yii::$app->user->id;
                $model->CREATED_AT = Date::nowTime();
            } elseif ($this->scenario == 'edit') {
                $model = UserSystem::findOne(['ID' => $this->id]);
                if($model->IS_DEL){
                    $this->addError('id', '该体系已被撤销，不能编辑');
                    return null;
                }
                $model->SYSTEM_NAME = $this->systemName;
                $model->LEADER_UID = $this->_leaderUid;
                $model->UPDATED_AT = Date::nowTime();
                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
                $model->UPDATE_ADMIN = \Yii::$app->user->id;
                $model->CREATE_REMARK = $this->remark;
            } elseif ($this->scenario == 'renewSystem') {
                $model = UserSystem::findOne(['ID' => $this->id]);
                $model->IS_DEL = 0;
                $model->UPDATED_AT = Date::nowTime();
                $model->UPDATE_PERIOD_NUM = $period->getNowPeriodNum();
                $model->UPDATE_ADMIN = \Yii::$app->user->id;
                $this->_leaderUid = $model->LEADER_UID;
            }else {
                $this->addError('id', '提交场景不存在');
                return null;
            }
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            // 下级会员全部变成该体系的会员
            //if ($this->scenario == 'add') {
                // 自己也变成该体系
                UserInfo::updateAll(['SYSTEM_ID' => $model->ID, 'IS_SYSTEM_LEADER'=>1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_leaderUid]);
                $this->_childrenChangeSystem($this->_leaderUid, $model->ID);
           //}
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        if($this->scenario!='add'){
            $this->adminOperateLogger->afterUpdate($model);

        }else{
            $this->adminOperateLogger->afterInsert($model);
        }
        $optType = '添加体系';
        if($this->scenario=='edit'){
            $optType = '编辑体系';
        }elseif ($this->scenario=='renewSystem'){
            $optType = '恢复体系';
        }
        $this->adminOperateLogger->clean()->save([
            'optType' => $optType,
            'userId' => $model->LEADER_UID,
            'userName' => Info::getUserNameByUserId($model->LEADER_UID),
            'remark' => $this->remark??''
        ]);
        return $model;
    }

    /**
     * 改变子会员的体系
     * @param $userId
     * @param $systemId
     * @throws \yii\db\Exception
     */
    private function _childrenChangeSystem($userId, $systemId){
        // 查询子会员里面是体系领导人的所有子会员
        $allChildSystemLeader = UserRelation::find()->select('UR.*,UI.SYSTEM_ID')->from(UserRelation::tableName().' AS UR')->join('LEFT JOIN', UserInfo::tableName().' AS UI', 'UI.USER_ID=UR.USER_ID')->where('UR.PARENT_UID=:PARENT_UID AND UI.IS_SYSTEM_LEADER=1', [':PARENT_UID'=>$userId])->asArray()->all();
        // 先把所有子会员的体系，全部改成新体系
        $sql = "UPDATE {{%USER_INFO}} UI SET UI.SYSTEM_ID=:SYSTEM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_RELATION}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
        \Yii::$app->db->createCommand($sql)->bindValues([':SYSTEM_ID'=>$systemId, ':PARENT_UID'=>$userId])->query();
        // 循环把所有子会员的体系都设置了
        foreach($allChildSystemLeader as $ChildSystemLeader){
            UserInfo::updateAll(['SYSTEM_ID' => $ChildSystemLeader['SYSTEM_ID']], 'USER_ID=:USER_ID', [':USER_ID' => $ChildSystemLeader['USER_ID']]);
            $sql = "UPDATE {{%USER_INFO}} UI SET UI.SYSTEM_ID=:SYSTEM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_RELATION}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
            \Yii::$app->db->createCommand($sql)->bindValues([':SYSTEM_ID'=>$ChildSystemLeader['SYSTEM_ID'], ':PARENT_UID'=>$ChildSystemLeader['USER_ID']])->query();
        }
    }

}
