<?php
namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\components\Model;
use common\helpers\Date;
use common\helpers\Tool;
use common\models\DeclarationLevel;

/**
 * Login form
 */
class DecLevelForm extends Model
{
    public $id;
    public $levelName;
    public $perf;
    public $isAdjustGift;
    public $isDec;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'levelName', 'perf', 'isAdjustGift', 'isDec'], 'trim', 'on'=>['add', 'edit']],
            [['id'], 'required', 'on'=>'edit'],
            [['id'], 'exist', 'targetClass'=>DeclarationLevel::class, 'targetAttribute'=>'ID'],
            [['levelName', 'perf', 'isAdjustGift', 'isDec'], 'required'],
            [['perf'], 'price'],
        ];
    }

    /**
     * 编辑
     * @return DeclarationLevel|null|static
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }
        if($this->scenario == 'add'){
            $model = new DeclarationLevel();
            $model->CREATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->CREATED_AT = Date::nowTime();
        } elseif($this->scenario == 'edit') {
            $model = DeclarationLevel::findOne(['ID'=>$this->id]);
            $model->UPDATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->UPDATED_AT = Date::nowTime();
        } else {
            $this->addError('id', '提交场景不存在');
            return null;
        }
        $model->LEVEL_NAME = $this->levelName;
        $model->PERF = $this->perf;
        $model->IS_ADJUST_GIFT = $this->isAdjustGift;
        $model->IS_DEC = $this->isDec;
        if($model->save()){
            return $model;
        } else {
            $this->addErrors($model->getErrors());
            return null;
        }
    }
}
