// import { Toast } from '@spark/ui'

import { isFromShare, newUser } from '../built-in/duiba-utils';

import { errorHandler } from "@/utils/errorHandler.js";
import { getPxToken } from "@/built-in/getPxToken.js";

import { Axios, AxiosRequestConfig } from 'axios';

import qs from "qs";

interface IRes {
  success: boolean;
  data: any;
  msg: string;
  code: number | string;
}


const mergeData = {
  user_type: newUser ? '0' : '1',
  is_from_share: isFromShare ? '0' : '1',
}

// let tempCookieId = "";
//
// export function setCookieId(cookieId) {
//   tempCookieId = cookieId;
// }

export function resetBackCookie(duibaTempCookieId) {
  return new Promise((resolve) => {
    apiAxios.request({
      url: "/autoLogin/resetCookie",
      params: {
        duibaTempCookieId
      }
    }).then((resp) => {
      return resolve('success');
    }, (e) => {
      return resolve(e);
    });
  });
}

/**
 * 请求方法get、post处理
 * @param {*} value
 * @returns
 */
function getRequestParams(value) {
  if (typeof value === 'string') {
    return { uri: value, method: 'get' };
  } else if (typeof value === 'object') {
    const {
      uri,
      method = 'get',
      showMsg = true,
      headers, withToken,
    } = value;
    return { uri, method, headers, withToken, showMsg };
  } else {
    console.error('getRequestParams: 传参有误');
  }
}


const apiAxios = new Axios({
  timeout: 10000,
});

apiAxios.interceptors.response.use(
  async (resp) => {
    try {
      const res = JSON.parse(resp.data);
      if (res.success) {
        return res;
      } else {
        return { success: false };
      }
    } catch (e) {
      return { success: false };
    }
  },
  async (error) => {
    console.error(error);
    return { success: false };
  }
);

/**
 * 请求API通用处理
 * @returns
 * @param apiList
 */
export function generateAPI(apiList): { [key in string]: (params?, headers?) => Promise<IRes> } {
  const api = {};
  for (const key in apiList) {
    let value = apiList[key];
    if (typeof value === 'string') {
      value = {
        uri: value,
        method: 'get'
      }
    }

    const {
      method = 'get',
      uri,
      headers: mHeaders,
      withToken,
      showMsg = true
    } = value;

    api[key] = async (params: any = {}, headers: any = {}) => {

      const isPost = method.toLowerCase() === 'post';

      // cookie丢失的问题
      // 如遇跳转Cookie丢失，打开如下代码
      // const duibaTempCookieId = localStorage.getItem("db_temp_cookie");
      // // const duibaTempCookieId = tempCookieId;
      //
      // if (duibaTempCookieId) {
      //   localStorage.removeItem("db_temp_cookie");
      //   // tempCookieId = "";
      //
      //   const res = await API.userLogin()
      //     .catch(async () => {
      //       await resetBackCookie(duibaTempCookieId);
      //     });
      //
      //   if (!res || !res.success) {
      //     await resetBackCookie(duibaTempCookieId);
      //   }
      // }

      if (withToken) {   // 是否携带token
        params.token = await getPxToken()
          .catch(() => {
            // Toast('网络异常，请稍后再试~');
            return ({ success: false, data: '' });
          });
      }

      const mergedHeaders = { ...mHeaders, ...headers }
      params = { ...params, ...mergeData };


      const config: AxiosRequestConfig = {
        method,
        url: uri,
        headers: mergedHeaders,
      }

      if (isPost) {
        config.data = qs.stringify(params);
      } else {
        config.params = params;
      }

      const res: IRes = await apiAxios.request(config);

      if (res) {
        if (!res.success && showMsg) {
          errorHandler(res);
        }
        return res;
      } else {
        return { success: false, data: '' };
      }

    }
  }

  return api;
}
