<?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\User;
use common\models\UserInfo;
use yii\base\Exception;
use yii\validators\UrlValidator;

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

    private $_userId;
    private $_fromId;
    private $_lvPv;

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

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

    public function attributeLabels()
    {
        return [
            'userName' => '会员编号',
            'levelId' => '级别',
            'periodNum' => '期数',
            '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, '会员不存在');
        }
    }

    /**
     * 查看级别是否有变化
     * @param $attribute
     */
    public function isLevel($attribute){
        $this->_fromId = Info::getDecLv($this->_userId);
        if($this->levelId == $this->_fromId){
            $this->addError($attribute, '级别没有变化无需调整');
        }
        $decLv = DeclarationLevel::findOneAsArray('ID=:ID',[':ID'=>$this->levelId],'PERF');
        $this->_lvPv = $decLv['PERF'];
    }

    /**
     * 期数是否满足要求
     * @param $attribute
     * @throws \yii\db\Exception
     */
    public function isPeriodNum($attribute) {
        $period = Period::instance();
        if ($period->isSent($this->periodNum)) {
            $this->addError($attribute, '期数' . $this->periodNum . '已挂网');
        }
    }

    /**
     * 调价调整操作
     * @return Ad|null
     * @throws \yii\db\Exception
     */
    public function adminChange(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->beforeUpdate($this->_userId,'ID',['select'=>'ID,LAST_DEC_LV,DEC_LV,DEC_LV_UPDATED_AT,DEC_LV_UPDATED_PERIOD,LAST_DEC_LV_UPDATED_PERIOD,LAST_DEC_LV_UPDATED_AT']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            // 恢复所传期数的和这个会员相关的其他调整
            $period = Period::instance();
            DecLevelLog::updateAll(['STATUS' => 0], 'USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => $this->_userId, ':PERIOD_NUM' => $this->periodNum]);
            // 新增数据
            $model = new DecLevelLog();
            $model->USER_ID = $this->_userId;
            $model->FROM_ID = $this->_fromId;
            $model->TO_ID = $this->levelId;
//            $model->PERIOD_NUM = $this->periodNum;
//            $model->CALC_MONTH = $period->getYearMonth($this->periodNum);
            $model->PERIOD_NUM = 0;
            $model->CALC_MONTH = 0;
            $model->REMARK = $this->remark;
            $model->STATUS = 1;
            $model->ADMIN_ID = \Yii::$app->user->id;
            $model->CREATED_AT = Date::nowTime();
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            //修改会员级别，如果是上期，则一起变化，如果不是，则只改变实时级别
            $nowPeriodNum = $period->getNowPeriodNum();
            //$changePeriodNum = $this->periodNum;
            $nowTime = Date::nowTime();
            //if ($changePeriodNum == $nowPeriodNum - 1) {
                User::updateAll(['LAST_DEC_LV' => $this->levelId, 'DEC_LV' => $this->levelId, 'DEC_LV_UPDATED_AT'=>$nowTime, 'DEC_LV_UPDATED_PERIOD'=>$nowPeriodNum, 'LAST_DEC_LV_UPDATED_AT'=>$nowTime, 'LAST_DEC_LV_UPDATED_PERIOD'=>$nowPeriodNum, 'ZG_UPGRADE_PV'=>$this->_lvPv], 'ID=:ID', [':ID' => $this->_userId]);
//            } else {
//                User::updateAll(['DEC_LV' => $this->levelId, 'DEC_LV_UPDATED_AT'=>$nowTime, 'DEC_LV_UPDATED_PERIOD'=>$nowPeriodNum, 'ZG_UPGRADE_PV'=>$this->_lvPv], 'ID=:ID', [':ID' => $this->_userId]);
//            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('adminChange', $e->getMessage());
            return null;
        }
        $this->adminOperateLogger->afterUpdate($this->_userId,'ID',['select'=>'ID,LAST_DEC_LV,DEC_LV,DEC_LV_UPDATED_AT,DEC_LV_UPDATED_PERIOD,LAST_DEC_LV_UPDATED_PERIOD,LAST_DEC_LV_UPDATED_AT'])->clean()->save([
            'optType' => '修改会员级别',
            'userId' => $this->_userId,
            'userName' => Info::getUserNameByUserId($this->_userId),
            'remark' => $this->remark
        ]);
        return $model;
    }


}
