import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
import { LOGIN_URL } from "@/config";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { useUserStore } from "@/stores/modules/user";
import { ElNotification } from "element-plus";
import router from "@/routers";
import { useToast } from "vue-toastification";
import ToastErrCopy from "@/components/ToastWidget/ToastErrCopy/index.vue";
import { useLockStore } from "@/stores/modules/lock";
import { ifErrorToLogin } from "@/utils/index";
import { omit } from "lodash-es";

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
}

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL: import.meta.env.VITE_USER_NODE_ENV == "production" ? window.location.origin : (import.meta.env.VITE_API_URL as string),
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);
    // axios.defaults.headers.post["Content-Type"] = "application/json";

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        const userStore = useUserStore();
        // 当前请求需要显示 loading，在 api 服务中通过指定的第三个参数: { loading: true } 来控制
        config.loading && showFullScreenLoading();
        if (config.headers && typeof config.headers.set === "function") {
          // config.headers.set("x-access-token", userStore.token);
          userStore.token && config.headers.set("token", userStore.token);
        }
        console.log("++++++拦截器 config :>> ", config.url?.substring(config.url?.lastIndexOf("/") ?? 0 + 1), config);
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        tryHideFullScreenLoading();
        const { data, config } = response;
        console.log("______响应拦截器 response :>> ", config.url?.substring(config.url?.lastIndexOf("/") ?? 0 + 1), response);
        const userStore = useUserStore();
        const lockStore = useLockStore();

        // 登陆失效
        // if (data.code == ResultEnum.OVERDUE) {
        if (data.ErrMsg) {
          let getError = ifErrorToLogin(data.ErrMsg);
          if ((getError && userStore.token == "") || (getError && lockStore.lockInfo?.isLogin)) {
            // 登录失败，拦截重复的失联报错
          } else {
            const toast = useToast();
            let keyIdx = config.url?.lastIndexOf("/") ?? 0;
            let requsetObj = omit(JSON.parse(config.data), ["token", "ifcompress", "dwname"]);
            let requestMsg = "[Request]: " + JSON.stringify(requsetObj);
            toast.error(
              {
                component: ToastErrCopy,
                props: {
                  type: "error",
                  title: "Error Tip:" + config.url?.substring(keyIdx + 1),
                  message: data.ErrMsg,
                  hideMsg: requestMsg
                }
              },
              {
                icon: false,
                timeout: 4000,
                closeButton: false,
                draggable: false,
                toastClassName: "longjoe-toast"
              }
            );
            console.error(data.ErrMsg);
          }

          if (getError) {
            if (userStore.token) {
              lockStore.setLockInfo({
                isLogin: true
              });
            } else {
              userStore.setToken("");
              router.replace(LOGIN_URL);
            }
          }
          return Promise.reject(data);
        }
        // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
        if (data.code && data.code !== ResultEnum.SUCCESS) {
          ElMessage.error(data.msg);
          return Promise.reject(data);
        }
        // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
        // 根据服务器响应的错误状态码，做不同的处理
        if (response) checkStatus(response.status);
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        let _fullPath = router.currentRoute.value.fullPath;
        if (!window.navigator.onLine && _fullPath.indexOf("/500") == -1) {
          let _redirectPath = _fullPath.replace(/&/g, "$and$");
          router.replace("/500" + "?redirect=" + _redirectPath);
        }
        return Promise.reject(error);
      }
    );
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object, _object = {}): Promise<T> {
    console.log("url :>> ", url);
    console.log("params :>> ", params);
    const userStore = useUserStore();
    let _params: any = params || {};
    if (!_params.hasOwnProperty("token")) {
      _params.token = userStore.token;
    }
    return this.service.post(url, _params, _object);
  }
  postUpload<T>(url: string, params?: object, _object = {}): Promise<T> {
    console.log("url :>> ", url);
    console.log("params :>> ", params);
    const userStore = useUserStore();
    let _params: any = params || {};
    if (!_params.hasOwnProperty("token")) {
      _params.token = userStore.token;
    }
    return this.service.post(url, _params, {
      ..._object
      // headers: {
      //   "Content-Type": "multipart/form-data"
      // }
    });
  }
  /**
   * @description 通用接口，自动附带布局信息
   * @param url api地址
   * @param params 请求入参
   * @param dwname 布局名称
   * @param ifcompress 是否加密
   * @param _object
   * @returns
   */
  postCommonDynamic<T>(url: string, params = {}, dwname = "", ifcompress = 0, _object = {}): Promise<T> {
    console.log("url :>> ", url);
    console.log("params :>> ", params);
    const userStore = useUserStore();
    let _params: any = params;
    if (!_params.hasOwnProperty("token")) {
      _params.token = userStore.token;
    }
    _params.dwname = import.meta.env.VITE_GLOB_PRODUCT_CODE;
    _params.itemname = dwname;
    _params.ifcompress = ifcompress;
    return this.service.post(url, _params, _object);
  }
  /**
   * @description 通用接口：调用uo
   * @param url api地址
   * @param params 请求入参
   * @param dwname 布局名称
   * @param ifcompress 是否加密
   * @param _object
   * @returns
   */
  postCommonBill<T>(url: string, params = {}, _object = {}): Promise<T> {
    console.log("url :>> ", url);
    console.log("params :>> ", params);
    const userStore = useUserStore();
    let _params: any = {};
    if (!_params.hasOwnProperty("token")) {
      _params.token = userStore.token;
    }
    _params.CList = [params];
    return this.service.post(url, _params, _object);
  }
  postOri<T>(url: string, params?: object, _object = {}): Promise<T> {
    let _params: any = params || {};
    console.log("_params :>> ", _params);
    return this.service.post(url, _params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

export default new RequestHttp(config);
