import { importOpenId } from "@/api/home.api.js";
import config from "../config/index";
const { SUB_MSG_LIST, tmplIdsList } = config;
export async function submitSubcribeInfo(tmplIds) {
  const userInfo = uni.getStorageSync("userAuthInfo") || {};
  const openid = uni.getStorageSync("openid");
  if (userInfo && openid) {
    const params = {
      appId: wx.getAccountInfoSync().miniProgram.appId,
      openId: openid,
      templateIdList: tmplIds,
      messageType: 7,
      userId: userInfo.userId
    };
    await importOpenId(params);
  }
}
export function getVaildTmplIds(res) {
  const acceptList = getAcceptList(res);
  const vaildTmplIds = acceptList.map(item => {
    for (const name in SUB_MSG_LIST) {
      if (SUB_MSG_LIST[name] === item) {
        return tmplIdsList[name];
      }
    }
  });
  return vaildTmplIds.join(",");
}
export function getAcceptList(res) {
  const acceptList = [];
  for (const key in res) {
    if (res[key] === "accept") {
      acceptList.push(key);
    }
  }
  return acceptList;
}
export function onLaunchSubmit() {
  wx.getSetting({
    withSubscriptions: true,
    async success(res) {
      let {
        subscriptionsSetting: { mainSwitch, itemSettings }
      } = res;
      if (mainSwitch) {
        itemSettings = itemSettings || {};
        const vaildTmplIds = getAcceptList(itemSettings);
        if (vaildTmplIds && vaildTmplIds.length) {
          await submitSubcribeInfo(vaildTmplIds);
        }
      }
    }
  });
}
