<?php

namespace common\models\forms;

use common\models\LogAdminHandle;
use common\models\LogSystem;
use Yii;

class LogSystemForm extends \yii\base\Model
{
    public $_id;
    public $ip;
    public $created_at;
    public $request_route;
    public $opt_type;
    public $request_content;
    public $response_content;
    public $opt_obj_id;
    public $opt_obj_name;
    public $opt_target_name;
    public $opt_user;
    public $user_agent;
    public $period_num;
    public $is_batch;
    public $device;

    /**
     * @inheritdoc
     */
    public function rules(){
        return [
            [['ip', 'created_at', 'request_route', 'opt_type', 'request_content', 'response_content', 'opt_obj_id', 'opt_obj_name', 'opt_target_name', 'opt_user', 'user_agent', 'period_num', 'is_batch', 'device'], 'trim'],
            [[ 'request_route', 'opt_type'], 'required'],
            [['created_at', 'is_batch', 'period_num'], 'filter', 'filter' => function($value){
                return ($value) ? $value : 0;
            }],
            [['opt_obj_id'], 'string', 'max' => 32],
            [['ip', 'opt_obj_name'], 'string', 'max' => 16],
            [['_id', 'opt_type', 'request_content', 'response_content', 'device'], 'safe'],
            [['user_agent', 'request_route'], 'string', 'max' => 1000],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels(){
        return [
            '_id' => 'ID',
            'ip'=>'操作ip',
            'created_at'=>'创建时间',
            'request_route'=>'请求路由',
            'opt_type'=>'操作类型',
            'request_content'=>'请求内容',
            'response_content'=>'响应内容',
            'opt_obj_id'=>'操作对象id',
            'opt_obj_name'=>'操作对象名称',
            'opt_target_name'=>'操作对象',
            'opt_user'=>'操作人',
            'user_agent'=>'浏览器特征',
            'period_num'=>'期数',
            'is_batch'=>'批量保存',
            'device'=>'客户端',
        ];
    }

    /**
     * 添加
     * @return LogAdminHandle|bool
     */
    public function add(){
        if(!$this->validate()){
            return false;
        }
        $model = new LogSystem();
        $model->ip = $this->ip;
        $model->created_at = intval($this->created_at);
        $model->request_route = $this->request_route;
        $model->opt_type = $this->opt_type;
        $model->request_content = $this->request_content;
        $model->response_content = $this->response_content;
        $model->opt_obj_id = $this->opt_obj_id;
        $model->opt_obj_name = $this->opt_obj_name;
        $model->opt_target_name = $this->opt_target_name;
        $model->opt_user = $this->opt_user;
        $model->user_agent = $this->user_agent;
        $model->period_num = intval($this->period_num);
        $model->is_batch = intval($this->is_batch);
        $model->device = $this->device;

        if(!$model->save()){
            $this->addErrors($model->getErrors());
            return false;
        }
        return $model;
    }
}
