import axios from "axios";
import { stringify } from "qs";
import router from "@/router";
import { appConfig } from "@/config";
import useStore from "@/store/index";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

interface IResult {
  code?: number;
  message?: string;
  list?: Array<object>;
  total?: number;
  data?: any;
  [propName: string]: any;
}

const whiteList: Array<string> = appConfig.apiWhiteList || [];
const baseURL: string = appConfig.apiBaseUrl || "/";

const service = axios.create({
  baseURL,
  timeout: 20 * 1000,
  headers: { "Content-Type": "application/json" },
});
service.interceptors.request.use(
  (config) => {
    let useRequestStore = useStore();
    const { useUserStore } = useRequestStore;
    const { token } = storeToRefs(useUserStore);
    if (token && token.value) {
      config.headers = config.headers || {};
      (config.headers as any).token = token.value;
      (config.headers as any).Authorization = `Bearer ${token.value}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    let useResponseStore = useStore();
    let returnData: IResult = {};

    const { useUserStore } = useResponseStore;
    const url = response.config.url;
    const res = response.data;
    let href = window.location.href;

    console.log("当前接口url=========", url);
    // 对于二进制响应（如验证码图片），直接返回，不做业务码拦截
    if (
      response.config &&
      (response.config.responseType === "blob" ||
        response.request?.responseType === "blob")
    ) {
      return res;
    }
    if (whiteList.includes(url)) {
      return res;
    }
    console.log("当前接口返回数据=========", res);
    // 如果业务code为401，拦截并跳转到登录页
    if (res && res.code === 401) {
      ElMessage({ message: "登录失效，请重新登录", type: "warning" });
      try {
        useUserStore.$patch({ token: "", isLogin: false });
      } catch (e) {}
      router.push("/login");
      return { ...res, fail: true };
    }

    if (res.code !== 0) {
      ElMessage({
        message: res.message || "发生意外了错误",
        type: "warning",
      });
      return {
        ...res,
        fail: true,
      };
    } else if (res.data === 0) {
      return res;
    } else if (!res.data && !res.list) {
      return { code: res.code, success: true };
    } else if (res.data && res.data.list) {
      returnData = {
        code: res.code,
        list: res.data.list,
        total: Number(res.data.total),
        object: res.data?.object,
      };

      return returnData;
    }
    return res;
  },
  (error) => {
    console.log("error", error);
    const { response } = error;
    let useErrorStore = useStore();
    const { useUserStore } = useErrorStore;
    if (!response) {
      ElMessage.error("网络连接超时，请稍后再试");
      return;
    }
    // 统一处理 HTTP 401 未授权：清理登录态并跳转登录页
    if (response.status === 401) {
      try {
        useUserStore.$patch({ token: "", isLogin: false, temp: "", other: "" });
      } catch (e) {}
      ElMessage({ message: "登录失效，请重新登录", type: "warning" });
      router.push("/login");
      return Promise.reject(error);
    }
    if (response.status === 450) {
      useUserStore.$patch({
        token: "",
        isLogin: false,
        temp: "",
        other: "",
        user: {},
      });
      ElMessage({
        message: "登陆态已失效，请重新登陆",
        type: "warning",
      });
      // useUserStore.updateredirectUrl(href);
      router.push("/login");
    }
    if (response.status === 502) {
      ElMessage({
        message: response.statusText,
        type: "warning",
      });
    } else {
      ElMessage({
        message: response.data.message || "网关错误",
        type: "error",
      });
    }
    return Promise.reject(error);
  }
);

export default service;

export const request = (config) => {
  return service({ method: "post", ...config });
};

export const requestForm = (config) => {
  return service({
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    method: "post",
    ...config,
    data: stringify(config.data),
  });
};
export const requestIndicesForm = (config) => {
  return service({
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    method: "post",
    ...config,
    data: stringify(config.data, { indices: false }),
  });
};
export const requestRaw = async (config) => {
  let useRequestStore = useStore();
  const { useUserStore } = useRequestStore;
  const { token } = storeToRefs(useUserStore);

  const { status, data } = await axios({
    headers: { token: token.value },
    method: "post",
    ...config,
  });
  returnData(status, data);
};

function returnData(status, data) {
  if (status !== 200 || data.code !== 0) {
    ElMessage({
      message: "系统服务异常，请稍后再试",
      type: "error",
      duration: 5 * 1000,
    });
    return { fail: true };
  }
  if (data.data === 0) {
    return data.data;
  }
  if (!data.data && !data.list) {
    return { success: true };
  }
  return data.data;
}

export const requestRawForm = async (config) => {
  const { status, data } = await axios({
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    method: "post",
    ...config,
    data: stringify(config.data),
  });
  console.log("requestRawForm");
  returnData(status, data);
};

export const requestFormData = async (config) => {
  const formData = new FormData();
  for (let key in config.data) {
    formData.append(key, config.data[key]);
  }
  return service({
    headers: { "Content-Type": "multipart/form-data" },
    method: "post",
    ...config,
    data: formData,
  });
};
