/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-17 10:24:00
 * @LastEditors: HJ
 * @LastEditTime: 2021-03-18 16:46:47
 */

const _ERROR_CODE = {
  10001: "参数传空了",
  10002: "网络问题，请求消息列表失败",
  10003: "网络问题，订阅请求发送失败",
  10004: "参数类型错误",
  10005: "无法展示 UI，一般是小程序这个时候退后台了导致的",
  20001: "没有模板数据，一般是模板 ID 不存在 或者和模板类型不对应 导致的",
  20002: "模板消息类型 既有一次性的又有永久的",
  20003: "模板消息数量超过上限",
  20004: "用户关闭了主开关，无法进行订阅",
  20005: "小程序被禁封",
};

export const _SUCCESS = (res, ids) => {
  const { errMsg } = res;
  return errMsg && errMsg.includes("ok")
    ? ids.filter((i) => res[i] === "accept")
    : "微信返回错误";
};

export const _FAIL = (err) => {
  console.log("debug error", err);
  const { errCode } = err || {};
  return `微信返回错误，错误信息:${_ERROR_CODE[errCode]}`;
};

export const _GET_TMPLIDS = (self) => {
  const { notifyConfig } = wx.$env;
  const { currentflag } = self.data;
  const map = { 1: "WAIMAI", 2: "ZITI", 3: "COUPON" };
  return notifyConfig[map[currentflag]];
};

/**
 * 调用微信的订阅消息
 */
export function notify(e) {
  return new Promise((resolve, reject) => {
    const tmplIds = _GET_TMPLIDS(this);
    if (Array.isArray(tmplIds) && tmplIds.length > 0) {
      wx.requestSubscribeMessage({
        tmplIds,
        success(res) {
          const result = _SUCCESS(res, tmplIds);
          if (typeof result !== "string") {
            resolve({ acceptIds: result });
          } else {
            reject(result);
          }
        },
        fail(err) {
          reject(_FAIL(err));
        },
        complete: () => {
          this.navToSuccess();
        },
      });
    } else {
      this.navToSuccess()
      reject("传入的tmplIds错误, tmplIds:" + tmplIds);
    }
  });
}
