import config from "./index";
import { saDeviceId } from "@/utils/sa";
import { getAppId } from "@/utils/index";
const invalidValueMap = [
  "undefined",
  "null",
  "0",
  "{registerFrom}",
  "{vccChannel}",
  "{sonVccChannel}",
  " "
];
// vccChannel处理
function getVccChannel(channel) {
  if (channel) return channel;
  let vccChannel = uni.getStorageSync("vccChannel");
  if (!vccChannel || invalidValueMap.includes(vccChannel)) {
    vccChannel = config.VCC_CHANNEL;
    uni.setStorageSync("vccChannel", config.VCC_CHANNEL);
  }
  return vccChannel;
}
export default {
  service: {
    response(response) {
      const { res, options } = response;
      const data = res.data;
      const success =
        (data.code === 0 && data.business_code === 0) ||
        (data.code === "0000" && data.businessCode === "0000");
      // 业务完成，返回有效载荷
      if (success) {
        return [data.data, null];
      }
      if (data.businessCode === "401") {
        const token = uni.getStorageSync("token");
        token && uni.removeStorageSync("token");
        uni.navigateTo({
          url: `/pages/user/login`
        });
      }
      // 接下来处理异常业务
      const msg = data.msg || "服务异常";
      if (!options.hideToast) {
        if (!data.noAlert) {
          uni.showToast({ title: msg, icon: "none", duration: 2500 });
        }
      }
      // 给用户提示信息，明确发生错误
      // 请求参数和响应数据都可以控制不提示
      let error = { msg };
      error.response = data;
      console.error(error);
      return [null, error];
    },
    request(cfg) {
      const {
        method,
        hideVccChannel,
        emulateFormData,
        needScDeviceId,
        creditToken,
        customizeChannel
      } = cfg;
      if (!cfg.header) cfg.header = {};
      // appID
      cfg.header["mini-app-id"] = getAppId() || "";
      // 租户ID
      cfg.header["qg-tenant-id"] = uni.getStorageSync("tenantId") || 560761;
      cfg.header["X-Auth-Token"] = uni.getStorageSync("token") || "";
      cfg.header["x-user-terminal"] = config.TERMINAL;
      if (!cfg.header["version"]) {
        cfg.header["version"] = config.VERSION;
      }
      // 使用creditToken
      if (creditToken) {
        cfg.header["X-Auth-Token"] = uni.getStorageSync("creditToken");
      }
      // 添加神策deviceid
      if (needScDeviceId) {
        // const saInfo = uni.getStorageSync("sensorsdata2015_wechat") || {};
        // const saDeviceId = saInfo.anonymous_id || "";
        cfg.header["scDeviceId"] = saDeviceId;
      }
      // 隐藏VccChannel
      if (!hideVccChannel) {
        cfg.header["vccChannel"] = getVccChannel(customizeChannel);
      }
      // 添加sonVccChannel
      // if (sonVccChannel) {
      cfg.header["sonVccChannel"] = uni.getStorageSync("sonVccChannel") || "";
      // }
      // 改为formData
      if (method.toLocaleLowerCase() === "post" && emulateFormData) {
        cfg.header["Content-Type"] = "application/x-www-form-urlencoded";
      }
      return cfg;
    }
  }
};
