<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Info;
use common\helpers\Validator;
use common\libs\logging\operate\AdminOperate;
use common\models\Ad;
use common\models\AdLocation;
use common\models\Article;
use common\models\DecLevelLog;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;
use yii\validators\UrlValidator;

/**
 * Login form
 */
class ChangeShowEmpLvForm extends Model
{
    public $userName;
    public $levelId;
    public $isReset;
    public $remark;

    private $_userId;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userName', 'levelId', 'remark', 'isReset'], 'trim'],
            [['userName'], 'required'],
            [['userName'], 'exist', 'targetClass'=>User::class, 'targetAttribute'=>'USER_NAME'],
            [['levelId'], 'exist', 'targetClass'=>EmployLevel::class, 'targetAttribute'=>'ID'],
            [['userName'], 'isUser'],
            [['levelId'], 'isLevel'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'userName' => '会员编号',
            'levelId' => '级别',
            'isReset' => '是否重置',
            'remark' => '期数',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'adminChange' => ['userName', 'levelId', 'isReset', 'remark'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 赋值UserId并校验会员是否存在
     * @param $attribute
     */
    public function isUser($attribute){
        $this->_userId = Info::getUserIdByUserName($this->userName);
        if(!$this->_userId){
            $this->addError($attribute, '会员不存在');
        }
    }

    /**
     * 查看级别是否有变化
     * @param $attribute
     */
    public function isLevel($attribute){
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID',[':USER_ID'=>$this->_userId],'SHOW_EMP_LV');
        if($this->levelId == $userInfo['SHOW_EMP_LV']){
            $this->addError($attribute, '前台显示级别没有变化无需调整');
        }
    }

    /**
     * 修改会员前台显示级别
     * @return bool|null
     * @throws \yii\db\Exception
     */
    public function adminChange(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->beforeUpdate($this->_userId,'USER_ID',['select'=>'SHOW_EMP_LV']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            if ($this->isReset) {
                UserInfo::updateAll(['SHOW_EMP_LV' => NULL], 'USER_ID=:USER_ID', [':USER_ID' => $this->_userId]);
            } else {
                UserInfo::updateAll(['SHOW_EMP_LV' => $this->levelId], 'USER_ID=:USER_ID', [':USER_ID' => $this->_userId]);
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('adminChange', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->afterUpdate($this->_userId,'USER_ID',['select'=>'SHOW_EMP_LV'])->clean()->save([
            'optType' => '修改会员前台显示聘级',
            'userId' => $this->_userId,
            'userName' => Info::getUserNameByUserId($this->_userId),
            'remark' => $this->remark
        ]);
        return true;
    }


}
