//文件目录：service/index.ts

// 引入了nuxt/app模块中的UseFetchOptions类型,UseFetchOptions类型是一个用于配置请求选项的接口或类型
import { UseFetchOptions } from "nuxt/app";
import { ElMessage } from "element-plus";
//  HTTP 请求的方法
type Methods = "GET" | "POST" | "DELETE" | "PUT";

// URL 基地址
let BASE_URL = "/api";

// 请求结果数据格式
export interface IResultData<T> {
  code: number;
  data: T;
  message: string;
}

/**
 * 列表数据
 */
export interface ServerList<T> {
  code: number
  message: string
  rows: Array<T>
  total: number
}

export interface ServerListData<T> {
  code: number
  message: string
  data: Array<T>
}

export interface ServerRes<T> {
  code: number
  data: T
  message: string
}

/**
 * api请求封装，使用useFetch函数
 * @param { String } url 请求地址
 * @param { String } method 请求方法
 * @param { Object } data 请求数据
 * @param { UseFetchOptions } options 请求选项
 */

let isLoginExpired = false;
/**
 * options常用参数说明
 * @param { boolean } lazy    是否在加载路由后才请求该异步方法，默认为false
 * @param { boolean } server  是否在服务端请求数据，默认为true
 */
class HttpRequest {
  request<T = any>(url: string, method: Methods, data: any, options?: UseFetchOptions<T>) {
    return new Promise(async (resolve, reject) => {
      // 不使用代理，直接全网址拿来请求，获取配置url  useRuntimeConfig() 获取配置
      BASE_URL = useRuntimeConfig().public.apiBase
      // 继承UseFetchOptions类型，包含了baseURL和method两个属性
      const newOptions: UseFetchOptions<T> = {
        baseURL: BASE_URL,
        method,
        ...options,
      };
      if (url.indexOf("/cart/getCartList") < 0 && url.indexOf("/oss/fileUploadWithPath") < 0 && url.indexOf("/shop/bom/matchBom") < 0) {
        data = {
          ...data,
          language: 1,
        }
      }
      // console.log(useRuntimeConfig().public)
      // 根据请求方法处理请求的数据
      if (method === "GET" || method === "DELETE") {
        // 将数据设置为newOptions的params属性 
        newOptions.params = data;
      }
      if (method === "POST" || method === "PUT") {
        // 将数据设置为newOptions的body属性 
        newOptions.body = data;
      }
      const isLogin = useCookie('tokenKey')
      let headers: any = {
        'access-token': isLogin.value || null,
      };
      let downFalg = url.indexOf("/download") > -1 ? true : false
      let downFalg2 = url.indexOf("/downloadFailResult") > -1 ? true : false //批量下单接口不支持 application/x-www-form-urlencoded
      let downFalg3 = url.indexOf("/oss/fileUploadWithPath") > -1 ? true : false //图片上传接口不支持 application/x-www-form-urlencoded
      if (downFalg && !downFalg2 && !downFalg3) {
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
      }
      const defaultOptions: object = {
        headers: headers,
        //响应拦截
        onResponse({ response }: { response: Response }) {
          const res = response._data;
          if (res.httpCode === 424 || res.httpCode === 425) {
            if (!isLoginExpired) { //防止重复弹出消息
              ElMessage.closeAll();
              ElMessage.warning('登录过期，请重新登录')
              const user = useUserStore()
              const tokenKey = useCookie("tokenKey");
              user.value.isLogin = false
              tokenKey.value = ''
              const route = useRoute();
              setTimeout(() => {
                navigateTo({ path: "/login", query: { redirect: route.fullPath }, replace: true });
              }, 300);
            }
          }
          else if (res.httpCode === 500) {
            ElMessage({
              type: 'error',
              message: res.message,
            })
          } else if (res.httpCode !== 200 && !res.token) {
            if (!downFalg && res.httpCode != 5003) {
              ElMessage({
                type: 'error',
                message: res.message,
              })
            }
          }
        },
        //响应错误拦截
        onResponseError({ response }: { response: Response }) {
          console.log("response-error", response);
          const res = response._data;
          ElMessage.error(response.statusText)

          //后端返回401时导航到登录界面
          if (response.status == 401) {
            const route = useRoute();
            if (route.fullPath.indexOf('/login/club') < 0) { //社区的不重置回登录
              navigateTo({ path: "/login", query: { redirect: route.fullPath }, replace: true });
            }
          }
        },
      };
      const finallyOptions: object = { ...defaultOptions, ...newOptions };
      if (!process.server) {
        $fetch(url, finallyOptions)
          .then((res: any) => {
            resolve(JSON.parse(JSON.stringify(res)));
          })
          .catch((error: any) => {
            reject(error);
          });
      } else {
        // 发送请求
        useFetch(url, finallyOptions)
          .then((res: any) => {
            resolve(res.data.value);
          })
          .catch((error: any) => {
            reject(error);
          });
      }

    });
  }

  // 封装常用方法
  get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
    return this.request(url, "GET", params, options);
  }


  post<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
    return this.request(url, "POST", data, options);
  }


  Put<T = any>(url: string, data: any, options?: UseFetchOptions<T>) {
    return this.request(url, "PUT", data, options);
  }


  Delete<T = any>(url: string, params: any, options?: UseFetchOptions<T>) {
    return this.request(url, "DELETE", params, options);
  }
}

const httpRequest = new HttpRequest();

export default httpRequest;