<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\libs\logging\operate\AdminOperate;
use common\models\OcrApi;
use yii\helpers\Json;

/**
 * Login form
 */
class OcrApiForm extends Model
{
    public $id;
    public $config;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'config'], 'trim'],
            [['id', 'config'], 'required'],
            [['id'], 'exist', 'targetClass'=>OcrApi::class, 'targetAttribute'=>'ID'],
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'edit' => ['id', 'config']
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 编辑
     * @return null|static
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }
        $this->adminOperateLogger->saveBeforeContent = OcrApi::getConfigById($this->id);
        if($this->scenario == 'edit') {
            $model = OcrApi::findOne(['ID'=>$this->id]);
            $model->UPDATE_ADMIN = \Yii::$app->user->id;
            $model->UPDATED_AT = Date::nowTime();
            $model->CONFIG = Json::encode($this->config);
        } else {
            $this->addError('edit', '提交场景不存在');
            return null;
        }
        if(!$model->save()){$this->addErrors($model->getErrors());
            return null;
        }
        $this->adminOperateLogger->saveAfterContent = OcrApi::getConfigById($this->id);
        $this->adminOperateLogger->clean()->save([
            'optType' => 'OcrApi配置成功',
        ]);
        return $model;
    }
}
