<template>
  <uni-popup ref="subscribeDialog" type="dialog">
    <uni-popup-dialog
      :subscribe-message="true"
      type="input"
      :show-title="false"
      content="非常感谢亲对羊小咩的关注，您可以关注【羊小咩 信用钱包】公众号获取最新的活动资讯，点击【订阅消息】即可哦~"
      message=""
      :duration="2000"
      :before-close="true"
      confirm-txt="订阅消息"
      @confirm="authSubscribe"
      @cancel="bundleCancelClick"
    />
  </uni-popup>
</template>
<script>
import uniPopup from "@/components/uni-popup/uni-popup";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import { getVaildSubTmplIds, subscribe } from "@/api/home.api";
import { saTrackEvent } from "@/utils/sa.js";
import { getVaildTmplIds, submitSubcribeInfo, getAcceptList } from "@/utils/subscribe";
import config from "@/config";
const tmplIds = [
  config.SUB_MSG_LIST.GROUP_BUY_REFUND,
  config.SUB_MSG_LIST.GROUP_SUCCESS,
  config.SUB_MSG_LIST.ACTIVITY_START
]; // 需要变更为消息通知
let vaildTmplIds = [];
export default {
  name: "ActionSheet",
  components: {
    uniPopup,
    uniPopupDialog
  },
  async created() {
    // #ifdef MP-WEIXIN
    this.getVaildSubTpl();
    // #endif
  },
  methods: {
    /**
     * @exposed-api
     */
    open() {
      // 非羊小咩不触发订阅消息
      if (this.$config("yxm")) this.$refs.subscribeDialog.open();
    },
    /**
     * @exposed-api
     */
    close() {
      this.$refs.subscribeDialog.close();
    },
    authSubscribe() {
      // 非羊小咩不触发订阅消息
      if (this.$config("yxm")) {
        wx.requestSubscribeMessage({
          tmplIds: vaildTmplIds,
          success: async res => {
            console.log(res);
            await subscribe({
              enable: 1
            });
            this.submitInfo(res);
            const vaildTmplIds = getVaildTmplIds(res);
            saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
              trigger_node: "登录成功后（百人团）",
              check_content: vaildTmplIds,
              buttons_name: "允许"
            });
            this.$emit("confirm");
            this.$refs.subscribeDialog.close();
          },
          fail: err => {
            console.error("requestSubscribeMessage", err);
            saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
              trigger_node: "登录成功后（百人团）",
              check_content: "退款通知,拼团成功提醒,活动开始提醒",
              buttons_name: "取消"
            });
            this.$emit("confirm");
            this.$refs.subscribeDialog.close();
          }
        });
      } else {
        this.$emit("confirm");
        this.$refs.subscribeDialog.close();
      }
    },
    submitInfo(res) {
      const acceptList = getAcceptList(res);
      submitSubcribeInfo(acceptList);
    },
    bundleCancelClick() {
      this.$emit("cancel");
    },
    async getVaildSubTpl() {
      vaildTmplIds = await getVaildSubTmplIds(tmplIds);
    }
  }
};
</script>
