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";
import {getUrlParam} from "@/utils/utils.ts";

interface IRes {
  uid: any;
  activityId: any;
  orderNo: any;
  success: boolean;
  data: any;
  msg?: string;
  message?: string;
  code?: number | string;
  timeStamp?: number;
  timestamp?: number;
}

const mergeData = {
  user_type: newUser ? '0' : '1',
  is_from_share: isFromShare ? '0' : '1',
  from: getUrlParam("channel") || '2',
  actPlatforms:CFG.actPlatforms || "",
  agentCode:CFG.agentCode || "",
  actId:CFG.actId || "",
}

// 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 {
      return JSON.parse(resp.data);
    } catch (e) {
      return {success: false};
    }
  },
  async (error) => {
    console.error(error);
    return {success: false};
  }
);

export interface IApiCfg {
  uri: string,
  method?: "get" | "post" | "GET" | "POST",
  showMsg?: boolean,
  withToken?: boolean,
  headers?: any,
}

export interface IApiList {
  [key: string]: string | IApiCfg;
}

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

    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 "";
          });
      }

      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.success && showMsg) {
        errorHandler(res);
      }
      return res;
    }
  }

  return api;
}
