// import md5 from 'md5'

export function request(url, options = {}) {
  const config = useRuntimeConfig();

  const authStore = useAuthStore();

  const defatulOpts = {
    method: "get",
    baseURL: config.public.baseApi,

    headers: {
      ...options.headers,
      // "Content-Type": "application/json",
      // deviceType: config.public.deviceType,
      authorization: authStore.token,
    },
    onRequest({ options }) {
      if (options.method === "post") {
      }
    },
    onRequestError() {
      // showErrorMessage('请求出错，请重试~')
    },
    onResponse({ response: { _data: data } }) {
      if (data && data.errorCode != "NO-ERROR") {
        handleServerError(data.errorCode, data.errorMessage);
      }
    },
    onResponseError({ response }) {
      handleHttpError(response.status);
    },
    ...options,
  };
  return new Promise((resolve, reject) => {
    $fetch(url, defatulOpts)
      .then((res) => {
        const { errorCode } = res;
        errorCode === "NO-ERROR" ? resolve(res) : reject(res);
      })
      .catch((err) => reject(err));
  });
}

const handleHttpError = (status) => {
  showErrorMessage(`${status} 请求出错，请重试~`);
  // switch (status) {
  //   case 400:
  //     showErrorMessage("参数错误");
  //     break;
  //   case 401:
  //     showErrorMessage("请求出错401");
  //     break;
  //   case 403:
  //     showErrorMessage("服务器拒绝访问");
  //     break;
  //   case 404:
  //     showErrorMessage("请求地址错误");
  //     break;
  //   case (502, 503):
  //     showErrorMessage("系统升级中");
  //     break;
  //   default:
  //     showErrorMessage("服务器出错了");
  //     break;
  // }
};

const handleServerError = async (code, msg) => {
  if (code === "UNAUTHORIZED_LOGIN") {
    const authStore = useAuthStore();
    authStore.cleanToken();
    await navigateTo({
      path: "/login",
      replace: true,
    });
    return;
  }
  if (msg) {
    showErrorMessage(msg);
  }
};

const showErrorMessage = (msg) => {
  showToast(msg);
  // const { message } = createDiscreteApi(['message'])
  // if (process.server) return
  // const { message } = useMessage()
  // message.error(msg)
};

export const handleResponse = (response, isNeedData = true) => {
  return new Promise((resolve, reject) => {
    const success = response.success
    switch (success) {
      case true: {
        if (isNeedData) {
          if (response.data && !isEmptyValue(response.data)) return resolve()
          return reject(response)
        }
        return resolve()
      }
      default: {
        return reject(response)
      }
    }
  })
}