import { questionnaireHas } from '@/plugins/API/apiQuestionnaire';
import { mapGetters } from 'vuex';
const mixin = {
  data() {
    return {
      isJoin: true
    };
  },
  computed: {
    ...mapGetters({
      type: 'type',
      jumpUrls: 'jumpUrls',
      userInfo: 'userInfo',
      channelInfo: 'channelInfo',
      channelConfig: 'channelConfig'
    }),
    isFront() {
      const info = this.channelConfig.questionnaire || {};
      const { isEnable, isFront } = info;
      return isEnable && isFront;
    }
  },
  mounted() {
    this.$Bus.$on('bus-questionnaire', this.questionnaireHas);
  },
  methods: {
    async questionnaireHas(noback) {
      const questionnaireHasRes = await questionnaireHas({
        includeId: this.channelInfo.id,
        uin: this.channelInfo.uin,
        type: this.type,
        referralUrl: window.location.href
      });
      if (questionnaireHasRes.code === 200 && questionnaireHasRes.errorCode === 0) {
        const { url: questionnaire_url, isJoin } = questionnaireHasRes.data;
        if (noback) {
          if (isJoin === 0 && questionnaire_url) {
            if (!this.userInfo.id) {
              const loginUrl = `${this.jumpUrls.login_noback}${encodeURIComponent(
                questionnaire_url
              )}`;
              window.location.replace(loginUrl);
            } else {
              window.location.replace(questionnaire_url);
            }
          } else {
            this.isJoin = false;
          }
        } else {
          if (questionnaire_url) {
            window.location.href = questionnaire_url;
          }
        }
      }
    }
  },
  watch: {
    userInfo() {
      if (this.isJoin && this.isFront) {
        this.questionnaireHas(true);
      }
    }
  },
  beforeDestroy() {
    this.$Bus.$off('bus-questionnaire', this.questionnaireHas);
  }
};
export default mixin;
