import axios, { AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import qs from "qs";
import { openLoading, closeLoading } from "./loading";
import { openErrorMsg } from "./errorMsg";
import {
  fromUrls,
  fileUrls,
  GetUrls,
  PostUrls,
  notLoginUrls,
  baseURL,
  unAuthCode,
  successCode,
} from "./config";
// import { show } from "@/store/case";
import { strToParams } from "@/util";
import { router } from "@/router";
import { RouteName } from "@/router/config";
// import { loginShow, setLoginShow } from "@/store/system";
import { loginShow, setLoginShow } from "@/store/system";

export * from "./urls";
export * from "./config";
export * from "./loading";
export * from "./errorMsg";

export type AuthHook = () => {
  token: string;
  userId: string;
  clear: () => void;
};
export const setLoginHook = (hook: AuthHook) => (getLogin = hook);
let getLogin = () => ({ loginShow: "", userId: "0", setLoginShow: () => {} });
export const setAuthHook = (hook: AuthHook) => (getAuth = hook);
let getAuth: AuthHook = () => ({ token: "", userId: "0", clear: () => {} });

axios.defaults.baseURL = baseURL;
let messageBoxFlag = 0 // 默认 MessageBox 未打开
const source = axios.CancelToken.source();

axios.interceptors.request.use(async (config) => {
  console.log('config.params', config.params);
  if (config.method === "get" && config.params) {
    // for (const key in config.params) {
    //   const val = config.params[key];
    //   console.log('config.params', key, val);
    //   try {
    //     if (typeof val === "string" && !!val) {
    //       config.params[key] = val.replaceAll(/[\[\]]/g, "").trim();
    //     }
    //   } catch (error) {
    //     config.params[key] = val;
    //   }
    // }
  }

  if (!config.url) {
    return config;
  }
  const PageParams = strToParams(window.location.search);
  let pageType = PageParams.show == 'true' ? 'view' : 'edit';
  const { token, userId } = getAuth();
  const route = router.currentRoute.value;
  let caseId = router.currentRoute.value?.params?.caseId
  if (!token && !~notLoginUrls.indexOf(config.url)) {
    console.log('用户未登录', caseId);
    router.replace({ name: RouteName.login});
    // let redirect = encodeURIComponent(`${window.location.href}`);
    // window.location.href = window.location.origin + "/#/login?redirect=" + redirect;
    throw "用户未登录";
  }
  config.headers.token = token;
  config.headers['caseid'] = caseId;
  // config.headers['Location'] = 'http://survey.4dkankan.com/';
  config.headers['page-type'] = pageType;
  config.headers.userid = userId;

  if (~GetUrls.indexOf(config.url)) {
    config.method = "GET";
  } else if (~PostUrls.indexOf(config.url)) {
    config.method = "POST";
    if (!config.data && config.params) {
      config.data = config.params;
    }
  }

  // 处理需要用表单上传的请求
  if (~fromUrls.indexOf(config.url)) {
    config.data = qs.stringify(config.data);
    config.headers["Content-Type"] =
      "application/x-www-form-urlencoded; charset=utf-8;";
  } else if (~fileUrls.indexOf(config.url)) {
    const fromData = new FormData();

    Object.keys(config.data).forEach((key) => {
      if (key === "files") {
        Array.from(config.data[key]).forEach((file) => {
          fromData.append("files", file as any as File);
        });
      } else {
        fromData.append(key, config.data[key]);
      }
    });
    config.data = fromData;
    config.headers["Content-Type"] = "multipart/form-data";
  }
  console.log("config", config);
  if (config.url === "/fusion/ai/getByImage") {
    return config;
  }
  openLoading(config.url);
  return config;
});

const responseInterceptor = (res: AxiosResponse<any, any>) => {
  closeLoading();
  let caseId = router.currentRoute.value?.params?.caseId
  let errMsg = res.data.msg || res.data.message;
  if (res.data.code === 40110) {
      ElMessageBox.alert(errMsg, "提示", {
          confirmButtonText: "去查看",
          type: "none",
          showClose: false,
          callback:async () => {
            window.location.href = window.location.origin + "/mix3d/?show=true#/abstract/"+caseId;
          }
        })
      throw res.data.msg;

  }
  if (res.data.code === 40111) {
    ElMessageBox.alert(errMsg, "提示", {
          confirmButtonText: "返回后台",
          type: "none",
          showClose: false,
          callback:async () => {
            // window.close()
            window.location.href = window.location.origin + "/admin/index.html";
          }
        })
      throw res.data.msg;
  }
  if (res.data.code === 4010 || res.data.code === 7012 ){
    if(messageBoxFlag  === 0) {
      messageBoxFlag = 1  // 修改标记
      ElMessageBox.alert(errMsg||"您没有访问权限", "提示", {
          confirmButtonText: "我知道了",
          type: "none",
          showClose: false,
          callback:async () => {
            // window.close()
            messageBoxFlag = 0  // 修改标记
            router.replace({ name: RouteName.login});
          }
        })
      }
      throw res.data.msg;
      return
    }else if(!successCode.includes(res.data.code) && res.config?.responseType != "blob") {
    let errMsg = res.data.msg || res.data.message;
    openErrorMsg(errMsg);

    if (
      ~unAuthCode.indexOf(res.data.code) ||
      errMsg === "token已经失效，请重新登录"
    ) {
      // let redirect = encodeURIComponent(`${window.location.href}`);
      // window.location.href = window.location.origin + "/admin/#/login?redirect=" + redirect;
      // router.replace({ name: RouteName.login });
      router.replace({ name: RouteName.login});

      // getAuth().clear();
    }
    throw res.data.msg;
  }

  return res.data;
};

axios.interceptors.response.use(responseInterceptor, (error) => {
  closeLoading();
  if (error.response && error.response.data) {
    return responseInterceptor(error.response);
  } else {
    openErrorMsg(
      typeof error === "string" ? error : "请求失败，服务端发生了点小故障！"
    );
    return Promise.reject(error);
  }
});

export { axios };

export type PaggingReq<T> = T & {
  pageNum: number;
  pageSize: number;
};

export type PaggingRes<T> = T & {
  total: number;
  list: T[];
};
