<?php

namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\Log;
use common\models\BonusAsync;
use common\models\Period;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\UserTeam;
use yii\base\Exception;

/**
 * Login form
 */
class UserTeamForm extends Model {
    public $id;
    public $teamName;
    public $leaderUserName;
    public $remark;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'teamName', 'leaderUserName', 'remark'], 'trim'],
            [['id', 'teamName', 'leaderUserName'], 'required'],
            [['leaderUserName'], 'unique', 'targetClass' => UserTeam::class, 'targetAttribute' => 'TEAM_NAME'],
            [['leaderUserName'], 'exist', 'targetClass' => UserInfo::class, 'targetAttribute' => 'USER_NAME'],
            [['id'], 'exist', 'targetClass' => UserTeam::class, 'targetAttribute' => 'ID', 'on'=>'renewTeam'],
            [['leaderUserName'], 'isLeaderUser'],
        ];
    }

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

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

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

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

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

    /**
     * 删除团队的
     * @param $id
     * @throws Exception
     */
    public function delete($id) {
        $period = Period::instance();
        $model = UserTeam::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 = UserNetwork::getFirstParentUserInfo($leaderUid);
        if ($parentUserInfo) {
            $newTeamId = $parentUserInfo['TEAM_ID'];
        } else {
            $newTeamId = null;
        }
        // 把该团队的所有团队都改成新团队
        UserInfo::updateAll(['TEAM_ID' => $newTeamId], 'TEAM_ID=:TEAM_ID AND IS_TEAM_LEADER=0', [':TEAM_ID' => $id]);
    }

    /**
     * 处理编辑
     * @return UserTeam|null
     * @throws \yii\db\Exception
     */
    private function _editHandle() {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $period = Period::instance();
            if ($this->scenario == 'add') {
                $model = new UserTeam();
                $model->TEAM_NAME = $this->teamName;
                $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 = UserTeam::findOne(['ID' => $this->id]);
                if($model->IS_DEL){
                    $this->addError('id', '该团队已被撤销，不能编辑');
                    return null;
                }
                $model->TEAM_NAME = $this->teamName;
                $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 == 'renewTeam') {
                $model = UserTeam::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(['TEAM_ID' => $model->ID, 'IS_TEAM_LEADER'=>1], 'USER_ID=:USER_ID', [':USER_ID' => $this->_leaderUid]);
                $this->_childrenChangeTeam($this->_leaderUid, $model->ID);
           //}
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 改变子会员的团队
     * @param $userId
     * @param $teamId
     * @throws \yii\db\Exception
     */
    private function _childrenChangeTeam($userId, $teamId){
        // 查询子会员里面是团队领导人的所有子会员
        $allChildTeamLeader = UserNetwork::find()->select('UR.*,UI.TEAM_ID')->from(UserNetwork::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_TEAM_LEADER=1', [':PARENT_UID'=>$userId])->asArray()->all();
        // 先把所有子会员的团队，全部改成新团队
        $sql = "UPDATE {{%USER_INFO}} UI SET UI.TEAM_ID=:TEAM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_NETWORK}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
        \Yii::$app->db->createCommand($sql)->bindValues([':TEAM_ID'=>$teamId, ':PARENT_UID'=>$userId])->query();
        // 循环把所有子会员的团队都设置了
        foreach($allChildTeamLeader as $ChildTeamLeader){
            UserInfo::updateAll(['TEAM_ID' => $ChildTeamLeader['TEAM_ID']], 'USER_ID=:USER_ID', [':USER_ID' => $ChildTeamLeader['USER_ID']]);
            $sql = "UPDATE {{%USER_INFO}} UI SET UI.TEAM_ID=:TEAM_ID WHERE EXISTS (SELECT UR.USER_ID FROM {{%USER_NETWORK}} UR WHERE UI.USER_ID=UR.USER_ID AND UR.PARENT_UID=:PARENT_UID)";
            \Yii::$app->db->createCommand($sql)->bindValues([':TEAM_ID'=>$ChildTeamLeader['TEAM_ID'], ':PARENT_UID'=>$ChildTeamLeader['USER_ID']])->query();
        }
    }

}
