<?php
namespace common\models\forms;

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

/**
 * Login form
 */
class DecRoleForm extends Model
{
    public $id;
    public $roleName;
    public $fwBonusPercent;

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

    /**
     * 编辑
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }
        if($this->scenario == 'edit') {
            $model = DecRole::findOne(['ID'=>$this->id]);
            $model->UPDATER = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->UPDATED_AT = Date::nowTime();
        } else {
            $this->addError('id', '提交场景不存在');
            return null;
        }
        $model->ROLE_NAME = $this->roleName;
        $model->FW_BONUS_PERCENT = $this->fwBonusPercent;
        if($model->save()){
            return $model;
        } else {
            $this->addErrors($model->getErrors());
            return null;
        }
    }
}
