export const defaultTemplateIds = [
  // 上新通知
  "RCG1EiNEzYGGplWonFtNsCm0id2k1xZhZClNm8Y5_7c",
  // 中奖通知
  "rVqzI7034PU8M7u3UKjR8Kd-_Wga5wO1BC8hYJ-hDKA",
  // 签到提醒
  "RigOXUldAYYOYc00nuL7OfdV3SDg8IEA7qLjLKJfEUE",
];

export const activityTemplateId = "O7lrNfk59NeQl2LECgHiTi8WSWHXfstdnW5jLW7fO80";

export const queueTemplateId = "SLDlbwLOgAqlueDwoZBNdlXyy8x2aUzzasu2VLUmsYo";

export function filterAcceptSubs(templateIds = []) {
  // #ifdef MP-WEIXIN
  return new Promise((resolve) => {
    wx.getSetting({
      withSubscriptions: true,
      success({ subscriptionsSetting }) {
        const { mainSwitch = false, itemSettings = {} } =
          subscriptionsSetting || {};

        if (mainSwitch) {
          resolve(
            templateIds.filter(
              (templateId) =>
                itemSettings[templateId] &&
                itemSettings[templateId] === "accept"
            )
          );
        } else {
          resolve([]);
        }
      },
    });
  });
  // #endif
  // #ifndef MP-WEIXIN
  // eslint-disable-next-line no-unreachable
  return Promise.resolve([]);
  // #endif
}

export function isSubAccept(templateId) {
  // #ifdef MP-WEIXIN
  return new Promise((resolve) => {
    wx.getSetting({
      withSubscriptions: true,
      success({ subscriptionsSetting }) {
        const { mainSwitch = false, itemSettings = {} } =
          subscriptionsSetting || {};
        if (
          mainSwitch &&
          itemSettings[templateId] &&
          itemSettings[templateId] === "accept"
        ) {
          resolve(true);
        } else {
          resolve(false);
        }
      },
    });
  });
  // #endif
  // #ifndef MP-WEIXIN
  // eslint-disable-next-line no-unreachable
  return Promise.resolve(false);
  // #endif
}

export function requestSubscribeMessage(templateIds) {
  // #ifdef MP-WEIXIN
  return new Promise((resolve, reject) => {
    wx.requestSubscribeMessage({
      tmplIds: templateIds,
      success: resolve,
      fail: reject,
    });
  });
  // #endif
  // #ifndef MP-WEIXIN
  // eslint-disable-next-line no-unreachable
  return Promise.reject();
  // #endif
}

export function reqSubMsg(templateId) {
  return requestSubscribeMessage([templateId]);
}

export async function reqAcceptSubMsg(templateId) {
  const isAccept = await isSubAccept(templateId);
  if (isAccept) {
    await requestSubscribeMessage([templateId]).catch(() => void 0);
  }
  return isAccept;
}

export async function reqAcceptSubMsgs(templateIds = []) {
  const acceptTemplateIds = await isSubAccept(templateIds).catch(() => []);
  if (acceptTemplateIds.length) {
    await requestSubscribeMessage(acceptTemplateIds).catch(() => void 0);
  }
  return acceptTemplateIds;
}

export default requestSubscribeMessage;
