<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\snowflake\SnowFake;
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\DecRole;
use common\models\DecRoleLog;
use common\models\Period;
use common\models\DeclarationLevel;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;
use yii\validators\UrlValidator;

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

    private $_userId;
    private $_fromId;

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

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

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

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'adminChange' => ['userName', 'levelId', '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, 'Member does not exist'); // 会员不存在
        }
    }

    /**
     * 查看级别是否有变化
     * @param $attribute
     */
    public function isLevel($attribute){
        $baseUserInfo = User::findOneAsArray('ID=:ID', [':ID' => $this->_userId], 'ID,USER_NAME,IS_DEC,DEC_ROLE_ID');
        if( $baseUserInfo['IS_DEC'] == 0 ) {
            $this->addError($attribute, '只有报单中心才能修改报单中心级别');
            return false;
        }
        $this->_fromId = $baseUserInfo['DEC_ROLE_ID'] ?? '';
        unset($baseUserInfo);
        if($this->levelId == $this->_fromId){
            $this->addError($attribute, '级别没有变化无需调整');
        }
    }

    /**
     * 报单中心级别调整操作
     * @return boolean
     * @throws \yii\db\Exception
     */
    public function adminChange(){
        if(!$this->validate()){
            return false;
        }
        $this->adminOperateLogger->beforeUpdate($this->_userId,'ID',['select'=>'ID,DEC_ROLE_ID']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            // 新增数据
            DecRoleLog::insertOne([
                'ID' => SnowFake::instance()->generateId(),
                'USER_ID' => $this->_userId,
                'FROM_ID' => $this->_fromId,
                'TO_ID' => $this->levelId,
                'PERIOD_NUM' => 0,
                'CALC_MONTH' => 0,
                'REMARK' => $this->remark,
                'STATUS' => 1,
                'ADMIN_ID' => \Yii::$app->user->id,
                'CREATED_AT' => Date::nowTime(),
            ]);
            User::updateAll(['DEC_ROLE_ID' => $this->levelId], 'ID=:ID', [':ID' => $this->_userId]);

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('adminChange', $e->getMessage());
            return false;
        }
        $this->adminOperateLogger->afterUpdate($this->_userId,'ID',['select'=>'ID,DEC_ROLE_ID'])->clean()->save([
            'optType' => '修改报单中心级别',
            'userId' => $this->_userId,
            'userName' => Info::getUserNameByUserId($this->_userId),
            'remark' => $this->remark
        ]);
        return true;
    }


}
