<style lang="less">
</style>

<template>
  <div class="component-follow-btn" v-if="tracked !== null">
    <div v-if="tracked">
      <slot name="tracked-content"></slot>
    </div>
    <div v-else v-on:click="toTrack">
      <slot name="un-tracked-content"></slot>
    </div>
  </div>
</template>

<script>
import wepy from '@wepy/core';
import store from '@/store';
import { mapState } from '@wepy/x';
import { trackMessages } from '@/service/subscribeMessage';
import { trackOrder, checkOrderSubscribed } from '@/api/subscribe';

wepy.component({
  store,
  mame: 'FollowBtn',
  data: {
    tracked: null,
    linkUrl: ''
  },
  options: {
    multipleSlots: true
  },
  props: {
    templateId: String, //该订阅消息模版，
    businessId: String, //事务id
    businessType: String //业务类类型 1身份认证 ,2发票
  },
  created() {
    if (this.token) {
      this.getData();
    }
  },
  computed: {
    ...mapState({ token: state => state.user.token })
  },
  watch: {
    token(curVal, oldVal) {
      if (curVal && !oldVal) {
        this.getData();
      }
    }
  },
  methods: {
    getData() {
      // 判断当前id 是否跟踪过
      checkOrderSubscribed({
        businessId: this.businessId,
        msgSubscriptionType: Number(this.businessType) //业务类类型 1身份认证 ,2发票
      }).then(res => {
        let result = res.data;
        this.tracked = result;
      });
    },
    toTrack() {
      trackMessages(this.templateId).then(res => {
        // 如果返回的是订阅消息拒绝过，就不再订阅
        if (res && res.reject) {
          return;
        }
        setTimeout(()=> {
          //发请求跟踪消息
          trackOrder({
            businessId: this.businessId,
            msgSubscriptionType: Number(this.businessType) //业务类类型 1身份认证 ,2发票
          }).then(() => {
            this.tracked = true;
          });
        }, 3e3);
       
      });
    }
  }
});
</script>