import axios, { AxiosResponse } from 'axios';
import { message } from 'antd';
import config, { getHeaders } from './config';
import LocalStorage from '@/LocalStorage';
import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/utils/crypto';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import {
    mockFetchKnowledgeLibList,
    mockFetchKnowledgeLibDetail,
    mockCreateKnowledgeLib,
    mockModifyKnowledgeLib,
    mockDeleteKnowledgeLib,
    mockFetchEmbeddingList,
    mockFetchDocumentLibList,
    mockFetchDocumentLibDetail,
    mockModifyDocumentLib,
    mockDeleteDocumentLib,
    mockUploadDocument,
    mockFetchDocumentSetting,
    mockModifyDocumentSetting,
    mockFetchSliceList,
    mockFetchSliceDetail,
    mockAddSlice,
    mockModifySlice,
    mockDeleteSlice,
    mockFetchReviseToolList,
    mockFetchReviseToolAllList,
    mockFetchReviseToolSliceList,
    mockSubmitReviseSlice,
    mockFetchReviseHistoryList,
    mockFetchTakaiAppTypeList,
    mockFetchChatHistoryList,
    mockExportChatHistory,
} from '@/mock/knowledgeApi';
import { applicationMockHandlers } from '@/mock/applicationApi';
import { authMockHandlers } from '@/mock/authApi';
import { auditMockHandlers } from '@/mock/auditApi';
import { overviewMockHandlers } from '@/mock/overviewApi';

const encryptHeader = 'encrypt-key';

// 是否启用 Mock 模式
const USE_MOCK = true;

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: config.baseURL,
    timeout: 600000 * 2,// 请求超时 20 分钟
});

// Mock 请求处理映射
const mockHandlerMap: Record<string, Function> = {
    // 知识库相关
    'POST /bigmodel/api/knowledgeList': mockFetchKnowledgeLibList,
    'GET /bigmodel/api/detailKnowledge': mockFetchKnowledgeLibDetail,
    'POST /bigmodel/api/createKnowledge': mockCreateKnowledgeLib,
    'PUT /bigmodel/api/updateKnowledge': mockModifyKnowledgeLib,
    'DELETE /bigmodel/api/delKnowledge': mockDeleteKnowledgeLib,
    'GET /bigmodel/api/embedding': mockFetchEmbeddingList,

    // 文档管理相关
    'POST /bigmodel/api/documentList': mockFetchDocumentLibList,
    'GET /bigmodel/api/documentDetail': mockFetchDocumentLibDetail,
    'PUT /bigmodel/api/updateDocument': mockModifyDocumentLib,
    'DELETE /bigmodel/api/delDocument': mockDeleteDocumentLib,
    'POST /bigmodel/api/uploadDocument': mockUploadDocument,
    'GET /bigmodel/api/documentSetting': mockFetchDocumentSetting,
    'PUT /bigmodel/api/updateDocumentSetting': mockModifyDocumentSetting,

    // 切片管理相关
    'POST /bigmodel/api/getSliceList': mockFetchSliceList,
    'GET /bigmodel/api/getSliceDetail': mockFetchSliceDetail,
    'POST /bigmodel/api/add/slice': mockAddSlice,
    'PUT /bigmodel/api/updateSliceInfo': mockModifySlice,
    'DELETE /bigmodel/api/deleteSlice': mockDeleteSlice,

    // 修订工具相关
    'GET /deepseek/revise/pageList': mockFetchReviseToolList,
    'GET /deepseek/revise/list': mockFetchReviseToolAllList,
    'GET /deepseek/revise/sliceList': mockFetchReviseToolSliceList,
    'PUT /deepseek/revise/reviseSlice': mockSubmitReviseSlice,
    'GET /deepseek/revise/reviseHistoryList': mockFetchReviseHistoryList,

    // 字典数据相关
    'GET /deepseek/api/standard_classification': () => mockFetchTakaiAppTypeList('standard_classification'),
    'GET /deepseek/api/parsing_type': () => mockFetchTakaiAppTypeList('parsing_type'),
    'GET /deepseek/api/splitting_type': () => mockFetchTakaiAppTypeList('splitting_type'),
    'GET /deepseek/api/revision_status': () => mockFetchTakaiAppTypeList('revision_status'),

    // 聊天记录相关
    'POST /bigmodel/api/chatHistory/list': mockFetchChatHistoryList,
    'POST /bigmodel/api/dialog/export': mockExportChatHistory,

    // 应用管理相关
    ...applicationMockHandlers,

    // 认证与用户相关
    ...authMockHandlers,

    // 审核管理相关
    ...auditMockHandlers,

    // 首页统计相关
    ...overviewMockHandlers,
};

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config: any) => {
        const isEncrypt = config.headers?.isEncrypt === 'true';
        config.headers = {
            'Content-Language': 'zh_CN',
            clientid:'e5cd7e4891bf95d1d19206ce24a7b32e',
            ...config.headers,
            ...getHeaders(),
        };
        if (!navigator.onLine) {
            message.error('网络故障');
        }
             // 当开启参数加密
        if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
            // 生成一个 AES 密钥
            const aesKey = generateAesKey();
            config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
            config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) : encryptWithAes(config.data, aesKey);
        }
        return config;
    }
);

// 响应拦截器 - 添加 Mock 支持
axiosInstance.interceptors.request.use(
    (config: any) => {
        if (USE_MOCK) {
            const method = (config.method || 'GET').toUpperCase();
            const url = config.url || '';
            
            // 构建匹配键
            const matchKey = `${method} ${url.split('?')[0]}`;
            
            // 查找匹配的 Mock 处理器
            for (const [key, handler] of Object.entries(mockHandlerMap)) {
                if (matchKey.includes(key.replace(`${method} `, ''))) {
                    // 找到匹配的 Mock 处理器，返回 Mock 数据
                    return Promise.resolve({
                        config,
                        data: null,
                        headers: config.headers,
                        status: 200,
                        statusText: 'OK',
                        mockHandler: handler,
                        mockParams: config.data || config.params,
                        mockUrl: url,
                    });
                }
            }
        }
        return config;
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {
        // 处理 Mock 响应
        if (response.mockHandler) {
            const handler = response.mockHandler;
            const params = response.mockParams;
            const url = response.mockUrl;
            
            // 从 URL 提取 ID 参数（用于详情接口）
            const urlParts = url.split('/');
            const idParam = urlParts[urlParts.length - 1];
            
            return handler(params || {}, idParam);
        }
        
        // 正常响应处理
        const { config, data } = response;
        if (config.responseType === 'blob') {
            return Promise.resolve(data);
        } else {
            if (data.code === 200) {// 成功
                return Promise.resolve(data);
            } else {// 失败
                if (data.code === 401) {
                    LocalStorage.clear();
                    message.error('登录过期');
                    // 使用 window.location 确保跳转生效
                    window.location.replace('/login');
                    return Promise.reject();
                } else {
                    message.error(data.msg||'请求失败');
                    return Promise.reject(data);
                }
            }
        }
    },
    (error) => {// 错误信息
        // HTTP 状态码
        const statusCode = error.response?.status;
        if (String(error).includes('timeout')) {
            message.error('请求超时');
        } else {
            if (statusCode === 401) {
                LocalStorage.clear();
                message.error('登录过期');
                // 使用 window.location 确保跳转生效
                window.location.replace('/login');
            } else if (statusCode && statusCode < 500) {
                message.error('请求失败');
            } else {
                message.error('服务异常');
            }
        }
        return Promise.reject();
    }
);

export default axiosInstance;
