<template>
  <span class="origin-link-container">
    <span
      v-bound-phone="bindPhoneViewOrigin()"
      class="highlight-text origin-link clickable"
      @click="viewOriginLink"
    >
      查看原文链接
    </span>
    <van-dialog
      v-model="dialog.show"
      title="查看原文链接"
      show-cancel-button
      @confirm="useFreeChance"
    >
      <p class="content-text">
        确定消耗
        <span class="highlight-text">1次</span>
        查看原文链接的机会吗？
      </p>
      <p class="sub-content-text">
        您当前是免费用户，有1次查看原文链接的机会，如需更多查看次数，您可点击
        <span
          class="highlight-text"
          @click="leaveInfo('article_original_more_membership')"
        >升级大会员 ></span>
      </p>
    </van-dialog>
    <van-dialog
      v-model="dialog.see"
      title=""
      class="see-dialog"
      close-on-click-overlay
      confirm-button-text="立即前往"
      @confirm="leaveSource('article_original')"
    >
      <p class="see-content">
        为给您匹配精准的推荐信息，请完善个人信息，免费查看原文
        <AppIcon class="icons" name="close_heidi" @click="dialog.see = false" />
      </p>
    </van-dialog>
  </span>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { LINKS } from '@/data'
import { AppIcon } from '@/ui/'
import { appCallOpenWindow } from '@/utils/callFn/appFn'
import { openAppOrWxPage } from '@/utils/'
import { getArticleOriginalText } from '@/api/modules/article'
import EventBus from '@/utils/eventBus'

export default {
  name: 'OriginLink',
  components: {
    AppIcon
  },
  props: {
    id: {
      type: String,
      required: true,
      default: ''
    },
    beforeLeavePage: Function
  },
  data() {
    return {
      dialog: {
        show: false,
        see: false
      },
      o_url: ''
    }
  },
  computed: {
    ...mapState({
      content: state => state.article.mainModel.content
    }),
    ...mapGetters('user', ['isFree']),
    url() {
      return this.content.originalUrl || this.o_url
    },
    toBCustom() {
      return this.IsCustomTopNet || this.yyszbContent
    },
    yyszbContent() {
      return this.content.yyszbContent || false
    },
    IsCustomTopNet() {
      return this.content.IsCustomTopNet || false
    }
  },
  created() {
    window.t = this
    this.eventBusListening()
  },
  methods: {
    eventBusListening() {
      EventBus.$on('originLink:view', () => {
        this.viewOriginLink()
      })
      // 及时解绑 EventBus 的事件监听
      this.$once('hook:beforeDestroy', () => {
        EventBus.$off('originLink:view')
      })
    },
    async viewOriginLink() {
      if (this.url) {
        // 如果已经获取过链接，则可以直接打开
        return this.openUrl()
      }
      const { inH5 } = this.$envs
      if (inH5) {
        if (this.beforeLeavePage) {
          await this.beforeLeavePage()
        }
        openAppOrWxPage(LINKS.下载APP, {
          query: {
            source: this.$env.platform.toUpperCase()
          }
        })
      }
      else {
        const loading = this.$toast.loading()
        try {
          const {
            error_code: code,
            error_msg: msg,
            data
          } = await this.getText()
          loading.clear()
          if (code === 0 && data) {
            if (data.url) {
              this.o_url = data.url
              this.openUrlAuth()
            }
            else if (data.status === 1) {
              this.leaveInfo('article_original_one', {
                signId: encodeURIComponent(this.id),
                article: this.extractString(location.href)
              })
            }
            else if (data.status === 2) {
              this.dialog.show = true
            }
            else if (data.status === 3) {
              this.leaveInfo('article_original_more', {
                signId: encodeURIComponent(this.id),
                article: this.extractString(location.href)
              })
            }
            else if (data.status === 4) {
              this.$dialog
                .confirm({
                  title: '暂无更多查看原文链接权限',
                  message: '如需开通更多权限获得商机，请联系客服。',
                  className: 'j-confirm-dialog',
                  showCancelButton: true,
                  confirmButtonText: '联系客服',
                  cancelButtonText: '返回',
                  confirmButtonColor: '#2ABDD1',
                  cancelButtonColor: '#171826',
                  width: 303
                })
                .then(async () => {
                  if (this.beforeLeavePage) {
                    await this.beforeLeavePage()
                  }
                  openAppOrWxPage(LINKS.客服)
                })
            }
            else {
              this.$toast(data.msg)
            }
          }
          else {
            console.log(msg)
          }
        }
        catch (error) {
          loading.clear()
        }
      }
    },
    async getText(use) {
      const param = {
        id: this.id
      }
      if (use) {
        param.use = true
      }
      return getArticleOriginalText(param)
    },
    async openUrlAuth() {
      if (!this.url)
        return
      if (this.toBCustom) {
        return this.openUrl()
      }
      if (this.isFree) {
        // 检查是否已经留资。已留资返回true
        const source = 'article_original'
        try {
          const leavedInfo = await this.$leaveInfo.checkNeedLeaveInfo(source)
          if (!leavedInfo) {
            // 没有留资，弹窗留资
            this.dialog.see = true
            return
          }
        }
        catch (error) {
          console.log(error)
        }
      }
      this.openUrl()
    },
    async useFreeChance() {
      try {
        const {
          error_code: code,
          error_msg: msg,
          data
        } = await this.getText(true)
        if (code === 0 && data) {
          if (data.url) {
            this.o_url = data.url
            this.openUrlAuth()
          }
          else {
            if (msg) {
              console.log(msg)
            }
          }
        }
      }
      catch (error) {
        console.log(error)
      }
    },
    openUrl() {
      if (!this.url)
        return
      const { inApp } = this.$envs
      if (inApp) {
        appCallOpenWindow(this.url, '查看原文')
      }
      else {
        this.clickA(this.url)
      }
    },
    clickA(link) {
      const eleLink = document.createElement('a') // 新建A标签
      eleLink.href = link
      eleLink.rel = 'no-referrer'
      eleLink.style.display = 'none'
      document.body.appendChild(eleLink)
      eleLink.click() // 触发点击事件
    },
    extractString(str) {
      const regex = /\/article\/(.*?)\//
      const match = str.match(regex)
      return match ? match[1] : null
    },
    async leaveSource(source, query = {}) {
      if (this.beforeLeavePage) {
        await this.beforeLeavePage()
      }
      openAppOrWxPage(LINKS.留资, {
        query: {
          source,
          ...query
        }
      })
    },
    leaveInfo(key, query = {}) {
      const { platform } = this.$env
      const source = `${platform}_${key}`
      this.leaveSource(source, query)
    },
    bindPhoneViewOrigin() {
      return {
        props: {
          name: '标讯详情页-查看原文链接'
        },
        next: () => {
          this.viewOriginLink()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .van-dialog__header {
    font-size: 18px;
  }
  .van-dialog__content {
    padding: 8px 16px;
  }
  .van-dialog__confirm {
    color: $main;
  }
}
.content-text {
  font-size: 14px;
  color: #5f5e64;
  text-align: center;
}
.sub-content-text {
  margin-top: 16px;
  width: 270px;
  font-size: 12px;
  line-height: 18px;
  color: #9b9ca3;
  text-align: center;
}
.see-dialog {
  width: 270px;
}
.see-content {
  position: relative;
  padding: 22px 12px;
  font-size: 15px;
  line-height: 22px;
  color: #5f5e64;
  .icons {
    position: absolute;
    top: 0;
    right: -8px;
    font-size: 20px;
    color: #ccc;
  }
}

.origin-link {
  color: #05a6f3;
}
</style>
