import { router } from "@/router";
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { syMessage as ElMessage } from "cqk-sy-ui";
import { getLoginCode } from "./storage";
export interface ResBase {
  code: number;
  data: any;
  msg: string;
}
// get请求
export interface GetParam {
  type: "get" | "delete";
  url: string;
  params?: { [key: string]: any };
  header?: any;
  config?: any;
}
// post请求
export interface PostParam {
  type: "post" | "put" | "patch" | "delete";
  url: string;
  params?: any;
  header?: any;
  config?: any;
}
//获取对象的长度
function length(o: any) {
  let count = 0;
  for (const i in o) {
    count++;
  }
  return count;
}
// ajax
async function $ajax(
  param: PostParam | GetParam,
  { doNotToastErr } = { doNotToastErr: false }
) {
  try {
    const type = param.type.toLowerCase();
    const result: AxiosRequestConfig = {
      method: type,
      url: (param || {}).url,
      params: {},
      headers: {
        Authorization: "Bearer " + getLoginCode(),
        ...(param.header || {}),
      },
      ...(param.config || {}),
    };
    if (param.params) {
      if (["get"].includes(type)) {
        let restfulUrl = (param || {}).url + `?`;
        const params = (param as GetParam).params || [];
        let num = length(params);
        Object.keys(params).forEach(function (key) {
          if (Array.isArray(params[key])) {
            (params[key] || []).forEach((i: string) => {
              restfulUrl += `${key}=${i}&`;
            });
            num--;
          } else {
            if (num === 1) {
              restfulUrl += `${key}=${params[key]}`;
            } else {
              restfulUrl += `${key}=${params[key]}&`;
              num--;
            }
          }
        });
        (result || {}).url = restfulUrl;
      } else {
        result.data = param.params;
      }
    }
    // 返回res
    const res: AxiosResponse<ResBase> = await axios(result);
    if (param && param.config && param.config.responseType === "blob") {
      return {
        code: 200,
        msg: "",
        data: res.data as unknown as Blob,
      };
    }
    if (res.data.code === 200) {
      // mock 为 0
      return res.data || {};
    } else if (res.data.code == 403) {
      ElMessage.warning("登录过期,请刷新页面");
      sessionStorage.removeItem("user");
      // router.push({ path: "/" });
      return null;
    } else {
      if (doNotToastErr) return res.data;
      if ([11032, 11033, 11097, 11002, 7000].indexOf(res.data.code) == -1) {
        ElMessage(res.data.msg);
        return null;
      }
      return res.data;
    }
  } catch (e) {
    if (axios.isCancel(e)) {
      return null;
    }
    ElMessage.error("网络异常");
    sessionStorage.removeItem("user");
    router.push({ path: "/" });
  }
}
export { $ajax };
