<?php
declare (strict_types = 1);

namespace app\admin\model\v1;

use think\Model;

/**
 * @mixin \think\Model
 */
class SysOperateLog extends Model
{
    // 表名
    protected $name = 'sys_operate_log';

    // 主键
    protected $pk = 'id';

    // 字段信息
    protected $schema = [
        'id'         => 'int',
        'user_id'    => 'int',
        'title'      => 'string',
        'version'    => 'string',
        'method'     => 'string',
        'controller' => 'string',
        'action'     => 'string',
        'url'        => 'string',
        'ip'         => 'string',
        'params'     => 'string',
        'status'     => 'int',
        'message'    => 'string',
        'created_at' => 'datetime'
    ];

    // 关联操作人
    public function user()
    {
        return $this->belongsTo(SysUserModel::class, 'user_id', 'id');
    }

    // 按标题搜索
    public function searchTitleAttr($query, $value, $data)
    {
        if (empty($value)) {
            return;
        }
        $query->where('title', 'like', "%$value%");
    }

    // 按操作时间搜索
    public function searchCreatedAtAttr($query, $value, $data)
    {
        if (empty($value)) return;
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        if (is_array($value)) {
            if (count($value) == 2) {
                $query->whereBetweenTime('created_at', $value[0], $value[1]);
            } else {
                $query->whereTime('created_at', '>=', $value);
            }
        }
    }
}
