import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { useUserStore } from '@/store/modules/user';
import { getToken } from '@/utils/auth';
import { tansParams, blobValidate } from '@/utils/ruoyi';
import cache from '@/plugins/cache';
import { HttpStatus } from '@/enums/RespEnum';
import { errorCode } from '@/utils/errorCode';
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
import FileSaver from 'file-saver';
import { getLanguage } from '@/lang';
import { decryptBase64, decryptWithAes, encryptBase64, encryptWithAes, generateAesKey } from '@/utils/crypto';
import { decrypt, encrypt } from '@/utils/jsencrypt';
import router from '@/router';
import { processSecurityRequest, processSecurityResponse } from './securityHandler';
import { isGmCryptoEnabled } from './cryptoConfig';
import qs from 'qs';

const encryptHeader = 'encrypt1-key';
let downloadLoadingInstance: LoadingInstance;

// 是否显示重新登录
export const isRelogin = { show: false };

export const globalHeaders = () => {
  return {
    Authorization: 'Bearer ' + getToken(),
    clientid: import.meta.env.VITE_APP_CLIENT_ID
  };
};

/**
 * 上传文件时的头部信息
 */
export const globalUploadHeaders = () => {
  return {
    ...globalHeaders(),
    'isuploadfile': 'true'
  };
};

/**
 * 下载文件时的头部信息
 */
export const globalDownloadHeaders = () => {
  return {
    ...globalHeaders(),
    'X-Download-Request': 'true',
    'isdownloadfile': 'true'
  };
};

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['clientid'] = import.meta.env.VITE_APP_CLIENT_ID;
axios.defaults.headers['auth-mode'] = 'JWT';

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 120000
});

// 请求拦截器
service.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    try {
      // 对应国际化资源文件后缀
      config.headers['Content-Language'] = getLanguage();
      // 从请求头获取控制标识
      const isToken = config.headers?.isToken === false;
      // 是否需要防止数据重复提交
      const isRepeatSubmit = config.headers?.repeatSubmit === false;
      // 是否需要加密
      const isEncrypt = config.headers?.isEncrypt === 'true';
      // Token处理
      if (getToken() && !isToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken();
      }
      // GET请求参数处理
      if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
      }

      // 防重复提交检查
      if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
        const requestObj = {
          url: config.url,
          data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
          time: new Date().getTime()
        };
        const sessionObj = cache.session.getJSON('sessionObj');
        if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
          cache.session.setJSON('sessionObj', requestObj);
        } else {
          const s_url = sessionObj.url; // 请求地址
          const s_data = sessionObj.data; // 请求数据
          const s_time = sessionObj.time; // 请求时间
          const interval = 500; // 间隔时间(ms)，小于此时间视为重复提交
          if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
            const message = '数据正在处理，请勿重复提交';
            return Promise.reject(new Error(message));
          } else {
            cache.session.setJSON('sessionObj', requestObj);
          }
        }
      }
      //如果是国密所有都加密
      if (isGmCryptoEnabled()) {
        // 使用国密处理（专门的SecurityHandler处理）
        await processSecurityRequest(config);
      } else {
        if (import.meta.env.VITE_APP_ENCRYPT === 'true') {
          // 当开启参数加密
          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);
          }
        }
      }
      // FormData处理
      if (config.data instanceof FormData) {
        delete config.headers['Content-Type'];
      }
      return config;
    } catch (error) {
      return Promise.reject(error);
    }
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res;
    }
    // 解密处理
    if (isGmCryptoEnabled()) {
      // 使用国密解密（专门的SecurityHandler处理）
      res = processSecurityResponse(res, res.config as InternalAxiosRequestConfig);
    } else {
      // 使用原有的传统解密逻辑
      if (import.meta.env.VITE_APP_ENCRYPT === 'true') {
        // 加密后的 AES 秘钥
        const keyStr = res.headers[encryptHeader];
        // 加密
        if (keyStr != null && keyStr != '') {
          const data = res.data;
          // 请求体 AES 解密
          const base64Str = decrypt(keyStr);
          // base64 解码 得到请求头的 AES 秘钥
          const aesKey = decryptBase64(base64Str.toString());
          // aesKey 解码 data
          const decryptData = decryptWithAes(data, aesKey);
          // 将结果 (得到的是 JSON 字符串) 转为 JSON
          res.data = JSON.parse(decryptData);
        }
      }
    }
    // 未设置状态码则默认成功状态
    const code = res.data.code || HttpStatus.SUCCESS;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || res.data.message || errorCode['default'];
    if (code === 401) {
      // prettier-ignore
      if (!isRelogin.show) {
        isRelogin.show = true;
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          isRelogin.show = false;
          useUserStore().logout().then(() => {
            router.replace({
              path: '/login',
              query: {
                redirect: encodeURIComponent(router.currentRoute.value.fullPath || '/')
              }
            })
          });
        }).catch(() => {
          isRelogin.show = false;
        });
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
    } else if (code === HttpStatus.SERVER_ERROR) {
      ElMessage({ message: msg, type: 'error' });
      return Promise.reject(new Error(msg));
    } else if (code === HttpStatus.WARN) {
      ElMessage({ message: msg, type: 'warning' });
      return Promise.reject(new Error(msg));
    } else if (code === HttpStatus.BATCH_SERVER_ERROR) {
      //批量错误处理
      return Promise.reject(res.data);
    } else if (code !== HttpStatus.SUCCESS) {
      ElNotification.error({ title: msg });
      return Promise.reject('error');
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error: any) => {
    let { message } = error;
    if (message == 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(url: string, params: any, fileName: string, config?: { isEncrypt?: boolean; [key: string]: any }) {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  const headers: Record<string, any> = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Download-Request': 'true',
    'isdownloadfile': 'true'
  };
  // 安全序列化：对象（含空对象）转 JSON 字符串
  const postData = qs.stringify(params);
  return service
    .post(url, postData, {
      headers,
      responseType: 'blob',
      ...config
    })
    .then(async (resp: any) => {
      const isLogin = blobValidate(resp.data);
      if (isLogin) {
        const blob = new Blob([resp.data]);
        FileSaver.saveAs(blob, fileName);
      } else {
        const resText = await resp.data.text();
        let rspObj;
        try {
          rspObj = JSON.parse(resText);
        } catch (e) {
          ElMessage.error('下载失败：响应格式错误');
          return;
        }
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        ElMessage.error(errMsg);
      }
    })
    .catch((r: any) => {
      ElMessage.error('下载文件出现错误，请联系管理员！');
    })
    .finally(() => {
      downloadLoadingInstance.close();
    });
}


// 通用下载方法(JSON格式)
export function downloadByJson(url: string, params: any, fileName: string) {
  downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });

  const headers: Record<string, any> = {
    'Content-Type': 'application/json;charset=utf-8',
    'X-Download-Request': 'true' // 添加下载标识
  };

  return service
    .post(url, params, {
      transformRequest: [
        (params: any) => {
          return JSON.stringify(params);
        }
      ],
      headers,
      responseType: 'blob'
    })
    .then(async (resp: any) => {
      const isLogin = blobValidate(resp.data);
      if (isLogin) {
        const blob = new Blob([resp.data]);
        FileSaver.saveAs(blob, fileName);
      } else {
        const resText = await resp.data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r: any) => {
      ElMessage.error('下载文件出现错误，请联系管理员！');
      downloadLoadingInstance.close();
    });
}

// 通用GET下载方法
export function downloadByGet(url: string, fileName?: string, contentType: string = 'application/octet-stream', headers?: Record<string, any>) {
  downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });

  const downloadHeaders = {
    ...globalDownloadHeaders(),
    ...headers
  };

  return service
    .get(url, {
      headers: downloadHeaders,
      responseType: 'blob'
    })
    .then(async (resp: any) => {
      const isLogin = blobValidate(resp.data);
      if (isLogin) {
        const blob = new Blob([resp.data], { type: contentType });
        // 如果没有提供文件名，尝试从响应头获取
        const finalFileName = fileName || decodeURIComponent(resp.headers['download-filename'] || 'download');
        FileSaver.saveAs(blob, finalFileName);
      } else {
        const resText = await resp.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r: any) => {
      ElMessage.error('下载文件出现错误，请联系管理员！');
      downloadLoadingInstance.close();
    });
}

// 导出 axios 实例
export default service;
