<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\adminapi\model;

use app\common\service\IpService;
use think\Model;

class OperationLog extends Model
{
    /**
     * 新增前事件
     * 根据IP地址自动获取地理位置信息
     * 
     * @param \think\Model $model
     * @return void
     */
    public static function onBeforeInsert($model)
    {
        // 如果存在IP字段，则获取位置信息
        if (!empty($model->ip)) {
            $locationInfo = IpService::getLocation($model->ip);
            // 如果成功获取到位置信息，拼接省市作为 location
            if ($locationInfo && is_array($locationInfo)) {
                $province = $locationInfo['province'] ?? '';
                $city = $locationInfo['city'] ?? '';
                
                // 拼接省市信息，去除空值
                $location = trim($province . $city);
                
                // 设置 location 字段
                $model->location = $location ?: '';
            } else {
                $model->location = '';
            }
        }
    }

    public function searchAdminNameAttr($query, $value, $data)
    {
        if ($value) {
            $query->where("admin_name", "like", "%".$value."%");
        }
    }

    public function searchTypeAttr($query, $value, $data)
    {
        if ($value) {
            $query->where("type", $value);
        }
    }

    public function searchIpAttr($query, $value, $data)
    {
        if ($value) {
            $query->where("ip", "like", "%".$value."%");
        }
    }

    public function searchCreatetimeAttr($query, $value, $data)
    {
        if (!empty($value)) {
            $query->whereBetweenTime('create_time', $value[0], $value[1]);
        }
    }
}