/**
 * axios实例
 */
import axios from 'axios';
import type { AxiosResponse, InternalAxiosRequestConfig, Method } from 'axios';
import { unref } from 'vue';
import { API_BASE_URL, LAYOUT_PATH, DATA_SECRET_KEY, SKIP_REQUEST_ENCRYPTION } from '@/config/setting';
import type { ApiResult } from '@/api';
import router from '@/router';
import { isWhiteList } from '@/router/routes';
import { getToken, setToken } from './token-util';
import { logout, showLogoutConfirm, toURLSearch } from './common';
import {useClientStore} from "@/store/modules/client";
import CryptoJS from 'crypto-js';

interface SecureRequestConfig extends InternalAxiosRequestConfig {
  /** 是否跳过加密处理（适用于文件上传等非文本数据） */
  skipEncryption?: boolean;
}
/**
 * 加密数据
 * @param data
 */
export function encryptData(data: any): string {
  const jsonString = JSON.stringify(data);
  return CryptoJS.AES.encrypt(jsonString, DATA_SECRET_KEY).toString();
}

/**
 * 解密数据
 * @param ciphertext
 */
export function decryptData(ciphertext: string): any {
  const bytes = CryptoJS.AES.decrypt(ciphertext, DATA_SECRET_KEY);
  const jsonString = bytes.toString(CryptoJS.enc.Utf8);

  if (!jsonString) {
    throw new Error('Decryption failed: Invalid key or ciphertext');
  }
  return JSON.parse(jsonString);
}
/**
 * 请求拦截处理
 */
export function requestInterceptor(config: SecureRequestConfig) {
  const method = config.method?.toLowerCase() as Method;


  // 添加客户端信息到header
  const client = useClientStore();
  if(config.headers) {
    config.headers['Client'] = client.clientName
    config.headers['Client-Id'] = client.clientId;
    config.headers['Client-Version'] = client.clientVersion;
  }

  // 添加token到header
  const token = getToken();
  if (token && config.headers) {
    config.headers['Authorization'] = token;
  }
  // get请求处理数组和对象类型参数
  if (method === 'get' && config.params) {
    config.url = toURLSearch(config.params, config.url);
    config.params = {};
  }
  console.log("是否需要加密->", '1' !== SKIP_REQUEST_ENCRYPTION)
  if ('1' !== SKIP_REQUEST_ENCRYPTION) {
    // 是否加密
    const shouldEncrypt = (
      !config.skipEncryption &&
      config.data &&
      ['post', 'put', 'delete', 'patch'].includes(method));
    if (shouldEncrypt && !config.headers?.['X-Encrypted']) {
      config.data = {
        encryptedData: encryptData(config.data)
      };
      config.headers['X-Encrypted'] = true;
    }
  }
}

/**
 * 响应拦截处理
 */
export function responseInterceptor(res: AxiosResponse<ApiResult<unknown>>) {
  // 登录过期处理
  if (res.data?.code === 401 || (res.data?.code === 403 && !getToken())) {
    const { path, fullPath } = unref(router.currentRoute);
    if (!(isWhiteList(path) || isWhiteList(location.pathname))) {
      if (path == LAYOUT_PATH) {
        logout(true, void 0, router.push);
      } else if (path !== '/login') {
        showLogoutConfirm(fullPath);
      }
    }
    return res.data.message;
  }
  // 续期token
  const newToken = res.headers['authorization'];
  if (newToken) {
    setToken(newToken);
  }
}

/** 创建axios实例 */
const service = axios.create({
  baseURL: API_BASE_URL
});

/**
 * 添加响应拦截器
 */
service.interceptors.response.use(
  (res: AxiosResponse<ApiResult<unknown>>) => {
    if (res.data?.encryptedData) {
      res.data = decryptData(res.data.encryptedData);
    }

    const errorMessage = responseInterceptor(res);
    if (errorMessage) {
      return Promise.reject(new Error(errorMessage));
    }
    return res;
  },
  (error) => {
    console.error(error);
    return Promise.reject(new Error('网络错误'));
  }
);

/**
 * 添加请求拦截器
 */
service.interceptors.request.use(
  (config) => {
    requestInterceptor(config);
    return config;
  },
  (error) => {
    console.error(error);
    return Promise.reject(new Error('网络错误'));
  }
);

export default service;
