import Store from "@mobileUI/store";
import { token_key } from "@mobileUI/utils/env";
import WlNotice from "@mobileUI/components/WlNotice";
import { removeEmptyField } from "@mobileUI/utils";
import { getQueryVariable } from './index'
/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (const item in obj) {
    arr[idx++] = [item, obj[item]];
  }
  return new URLSearchParams(arr).toString();
}

/**
 * 添加默认请求的参数
 * @param {*} options
 */
function getOptions(options) {
  const { sid = "", corp_id = "", card_resource = "" } = Store ?? {};
  const params = {
    sid,
    corp_id,
    card_resource,
    ...options,
  };
  return obj2String(params);
}

//处理url
const onHandleUrl = (url: string) => {
  const { node_env } = Store;
  const isPersonMiniApp = node_env.includes("xsf");
  if (isPersonMiniApp) {
    return setPersonMiniAppUrl(url);
  }
  return url;
};

//处理个人版小程序的接口
const setPersonMiniAppUrl = (url: string) => {
  let filterUrl = url;
  if (filterUrl.includes("/api/user/share/path")) {
    filterUrl = filterUrl.replace(
      "/api/user/share/path",
      "/apise/material/share/path",
    );
  } else if (filterUrl.includes("/interact/")) {
    filterUrl = filterUrl.replace("/interact/", "/apise/");
  } else if (filterUrl.includes("/api/")) {
    filterUrl = filterUrl.replace("/api/", "/apise/");
  } else if (filterUrl.includes("/wx/track")) {
    filterUrl = filterUrl.replace("/wx/track", "/apise/track/wx/track");
  }
  return filterUrl;
};

/**
 * 真正的请求
 * @param url 请求地址
 * @param options 请求参数
 * @param method 请求方式
 */
function request(url, options, method = "GET") {
  const staticOption = {
    sid: Store.sid,
    corp_id: Store.corp_id,
    tab_change: 0,
  };
  const data = {
    ...staticOption,
    ...options,
  };
  const searchStr = getOptions(removeEmptyField(data));
  const staticSearchStr = getOptions(removeEmptyField(staticOption));
  let initObj = {};
  let params = "";
  if (method === "GET") {
    // 如果是GET请求，拼接url
    initObj = {
      method: method,
      credentials: "include",
      headers: new Headers({
        "access-auth-token": getQueryVariable("msid"),
        [token_key[Store.node_env]]: Store.token,
      }),
    };
    params = searchStr;
  } else if (method === "FormPOST") {
    initObj = {
      method: "POST",
      credentials: "include",
      headers: new Headers({
        [token_key[Store.node_env]]: Store.token,
      }),
      body: options,
    };
    params = staticSearchStr;
  } else {
    initObj = {
      method: method,
      credentials: "include",
      headers: new Headers({
        "access-auth-token": getQueryVariable("msid"),
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
        [token_key[Store.node_env]]: Store.token,
      }),
      body: JSON.stringify(data),
    };
    params = staticSearchStr;
  }
  const filterUrl = onHandleUrl(url) + "?" + params;
  return fetch(filterUrl, initObj)
    .then((res) => {
      const isArea = url.includes("region.json");
      return res.json().then((result) => {
        //地域选择器是前端直接请求，单独处理
        if (result.code === 200 || isArea) {
          return result;
        } else {
          WlNotice({
            message: result.msg ?? "服务器内部错误",
            type: "error",
            duration: 3000,
          });
          throw Error(result);
        }
      });
    })
    .then((res) => {
      return res;
    });
}

/**
 * GET请求
 * @param url 请求地址
 * @param options 请求参数
 */
export const GET = (url, options) => {
  return request(url, options, "GET");
};

/**
 * POST请求
 * @param url 请求地址
 * @param options 请求参数
 */
export const POST = (url, options) => {
  return request(url, options, "POST");
};

/**
 * POST请求 转成formDate参数
 * @param url 请求地址
 * @param options 请求参数
 */
export const FormPOST = (url, options) => {
  const data: any = new FormData();
  for (const key in options) {
    const value = options[key];
    data.append(key, value);
  }
  return request(url, data, "FormPOST");
};
