import Taro from "@tarojs/taro";
import { ApiOptions } from "@/types/request";
import { useUserStore } from "@/store/userStore";


/**
 * 请求拦截器
 * @param chain
 */
const requestInterceptor = (chain: Taro.Chain) => {
  const requestParams = chain.requestParams
  const tokenInfo = useUserStore().getTokenInfo()
  const { header } = requestParams;
  const customHeader: Record<string, any> = {}
  //添加token
  tokenInfo && (customHeader[tokenInfo.name] = tokenInfo.value);
  requestParams.header = {
    ...header,
    ...customHeader
  }
  return chain.proceed(requestParams)
}

//所有的拦截器
const interceptors = [requestInterceptor];
//注册拦截器
interceptors.forEach((interceptorItem) => Taro.addInterceptor(interceptorItem));

class CustomRequest {
  BASE_API: string = process.env.TARO_APP_BASE_API;

  private request<T>(url: string, method: keyof Taro.request.Method, options: ApiOptions, params?: object,): Promise<JsonResult<T>> {
    // console.log(this.BASE_API,'0000000')
    return new Promise<JsonResult<T>>((resolve, reject) => {
      if (options.loading) {
        Taro.showLoading({
          title: '请求中...',
        }).then()
        // Taro.showLoading({
        //   title: '请求中...',
        // })
      }
      Taro.request<JsonResult<T>, object>({
        url: this.BASE_API + url,
        data: params,
        method,
        ...options,
        success: (result) => {
          Taro.hideLoading()
          if (result.header['Content-Type'] === 'application/octet-stream') {
            resolve(result.data)
            return
          }
          const jsonResult = result.data
          if (jsonResult.code !== 200) {
            if ([401].includes(jsonResult.code)) {
              // 重新登录 跳转登录页 提示错误
            }
            Taro.showToast({
              title: jsonResult.message,
              icon: 'none',
              mask: true,
              duration: 2000
            }).then()
            reject(jsonResult);
          } else {
            resolve(jsonResult);
          }
        },
        fail: (res) => {
          Taro.hideLoading()
          Taro.showToast({
            title: res.errMsg,
            icon: 'none',
            mask: true,
            duration: 2000
          }).then()
          reject(res.errMsg);
        }
      })
    })
  }

  get<T>(url: string, params?: object, options: ApiOptions = { loading: false }): Promise<JsonResult<T>> {
    options.header = {
      ...options.header,
      "content-type": 'application/x-www-form-urlencoded'
    }
    return this.request<T>(url, "GET", options, params)
  }

  post<T>(url: string, params?: object, options: ApiOptions = { loading: false }): Promise<JsonResult<T>> {
    return this.request<T>(url, "POST", options, params)
  }

  delete<T>(url: string, params?: object, options: ApiOptions = { loading: false }): Promise<JsonResult<T>> {
    options.header = {
      ...options.header,
      "content-type": 'application/x-www-form-urlencoded'
    }
    return this.request(url, "DELETE", options, params)
  }

  put<T>(url: string, params?: object, options: ApiOptions = { loading: false }): Promise<JsonResult<T>> {
    return this.request(url, "PUT", options, params)
  }

}

const api = new CustomRequest();

export default api
