<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2025-09-15
 *
 * 
 */

namespace app\common\model\system;

use app\common\model\BaseModel;

class ApiRequestLog extends BaseModel
{

    /**
     * @return string
     * @author xaboy
     * @day 2025-09-15
     */
    public static function tablePk(): string
    {
        return 'log_id';
    }

    /**
     * @return string
     * @author xaboy
     * @day 2025-09-15
     */
    public static function tableName(): string
    {
        return 'api_request_log';
    }

    /**
     * 记录接口请求日志
     * @param array $data
     * @return bool
     */
    public static function record(array $data): bool
    {
        try {
            $logData = [
                'request_id' => $data['request_id'] ?? self::generateRequestId(),
                'app_type' => $data['app_type'] ?? '',
                'request_method' => $data['request_method'] ?? '',
                'request_url' => $data['request_url'] ?? '',
                'request_params' => isset($data['request_params']) ? json_encode($data['request_params'], JSON_UNESCAPED_UNICODE) : null,
                'request_headers' => isset($data['request_headers']) ? json_encode($data['request_headers'], JSON_UNESCAPED_UNICODE) : null,
                'request_ip' => $data['request_ip'] ?? '',
                'user_agent' => $data['user_agent'] ?? '',
                'user_id' => $data['user_id'] ?? 0,
                'merchant_id' => $data['merchant_id'] ?? 0,
                'admin_id' => $data['admin_id'] ?? 0,
                'response_code' => $data['response_code'] ?? 0,
                'response_data' => isset($data['response_data']) ? json_encode($data['response_data'], JSON_UNESCAPED_UNICODE) : null,
                'response_time' => $data['response_time'] ?? 0,
                'error_message' => $data['error_message'] ?? '',
            ];

            return self::create($logData) !== false;
        } catch (\Exception $e) {
            // 记录日志失败时不中断主流程
            return false;
        }
    }

    /**
     * 生成请求唯一标识
     * @return string
     */
    private static function generateRequestId(): string
    {
        return md5(uniqid('api_request_', true) . mt_rand(1000, 9999));
    }

    /**
     * 根据请求ID查找日志
     * @param string $requestId
     * @return array|null
     */
    public static function findByRequestId(string $requestId): ?array
    {
        $log = self::getDB()->where('request_id', $requestId)->find();
        return $log ? $log->toArray() : null;
    }

    /**
     * 获取指定时间范围内的日志列表
     * @param string $startTime
     * @param string $endTime
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getListByTimeRange(string $startTime, string $endTime, int $page = 1, int $limit = 20): array
    {
        $query = self::getDB()
            ->where('create_time', '>=', $startTime)
            ->where('create_time', '<=', $endTime)
            ->order('log_id', 'desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select()->toArray();

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_page' => ceil($total / $limit)
        ];
    }

    /**
     * 清理过期日志
     * @param int $days 保留天数
     * @return int
     */
    public static function clearExpiredLogs(int $days = 30): int
    {
        $expireTime = date('Y-m-d H:i:s', strtotime("-$days days"));
        return self::getDB()->where('create_time', '<', $expireTime)->delete();
    }
}