-- 业务外部接口调用日志及菜单
-- 可重复执行，不自动授予普通角色权限

CREATE TABLE IF NOT EXISTS sys_api_log (
    log_id BIGINT NOT NULL AUTO_INCREMENT COMMENT '日志主键',
    caller_user_id BIGINT NULL COMMENT '调用发起用户ID',
    caller_username VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '调用发起账号',
    api_url TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '接口完整地址',
    http_method VARCHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'HTTP方法',
    content_type VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '请求内容类型',
    request_headers LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '完整请求头',
    request_params LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '完整请求参数',
    response_status INT NULL COMMENT 'HTTP响应状态码',
    response_headers LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '完整响应头',
    response_body LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '完整响应正文',
    call_status CHAR(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'HTTP调用状态（0成功 1失败）',
    error_msg LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '异常信息',
    cost_time BIGINT NOT NULL DEFAULT 0 COMMENT 'HTTP调用耗时（毫秒）',
    call_time DATETIME NOT NULL COMMENT '调用开始时间',
    PRIMARY KEY (log_id),
    KEY idx_sys_api_log_time (call_time, log_id),
    KEY idx_sys_api_log_status_time (call_status, call_time, log_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='业务外部接口调用日志';

SET @log_parent_id = (
    SELECT menu_id
    FROM sys_menu
    WHERE menu_name = '日志管理'
      AND menu_type = 'M'
    LIMIT 1
);

INSERT INTO sys_menu (
    menu_name, parent_id, order_num, path, component, query, route_name,
    is_frame, is_cache, menu_type, visible, status, perms, icon,
    create_by, create_time, update_by, update_time, remark
)
SELECT
    '接口日志', @log_parent_id, 3, 'apilog', 'monitor/apilog/index', '', '',
    1, 0, 'C', '0', '0', 'monitor:apilog:list', 'log',
    'admin', NOW(), '', NULL, '业务外部接口日志菜单'
FROM dual
WHERE @log_parent_id IS NOT NULL
  AND NOT EXISTS (
      SELECT 1
      FROM sys_menu
      WHERE parent_id = @log_parent_id
        AND path = 'apilog'
  );

SET @api_log_menu_id = (
    SELECT menu_id
    FROM sys_menu
    WHERE parent_id = @log_parent_id
      AND path = 'apilog'
    LIMIT 1
);

INSERT INTO sys_menu (
    menu_name, parent_id, order_num, path, component, query, route_name,
    is_frame, is_cache, menu_type, visible, status, perms, icon,
    create_by, create_time, update_by, update_time, remark
)
SELECT
    '接口日志查询', @api_log_menu_id, 1, '#', '', '', '',
    1, 0, 'F', '0', '0', 'monitor:apilog:query', '#',
    'admin', NOW(), '', NULL, ''
FROM dual
WHERE @api_log_menu_id IS NOT NULL
  AND NOT EXISTS (
      SELECT 1
      FROM sys_menu
      WHERE parent_id = @api_log_menu_id
        AND perms = 'monitor:apilog:query'
  );
