<?php

namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\libs\logging\operate\AdminOperate;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * Login form
 */
class UserGroupForm extends Model {
    public $userIds;
    public $isGroup;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['userIds', 'isGroup'], 'trim'],
            [['userIds'], 'required'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'group' => ['userIds', 'isGroup'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userIds' => '会员ID',
            'isGroup' => '是否团队领导人',
        ];
    }

    public function beforeValidate() {
        return parent::beforeValidate();
    }

    /**
     * 是否团队领导人
     * @return null
     * @throws \yii\db\Exception
     */
    public function group() {
        if (!$this->validate()) {
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,IS_GROUP_LEADER,GROUP_LEADER_AT']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $allUidIn = implode("','", $this->userIds);
            if (!UserInfo::updateAll(['IS_GROUP_LEADER' => $this->isGroup ? $this->isGroup : 0, 'GROUP_LEADER_AT' => Date::nowTime()], "USER_ID IN ('" . $allUidIn . "')")) {
                throw new Exception('团队领导人更新失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,IS_GROUP_LEADER,GROUP_LEADER_AT']);
        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
            'optType' => $this->isGroup ? '设置团队领导人' : '取消团队领导人',
        ]);



        return $this->userIds;
    }

}
