<template>
  <view class="warp">
    <view  v-if="isPay" @click="dispatchEvent">
      <slot name="pay"></slot>
    </view>
    <view  v-else-if="isAd" @click="dispatchEvent">
      <slot name="ad"></slot>
    </view>
    <view v-else @click="dispatchEvent">
      <slot name="attent" ></slot>
    </view>

  </view>
</template>

<script>
import { debounce,dateFormat,compareVersion } from '../../common/utils';
import { doPay,getPayStatus,postAdOrder } from '../../common/api'
import { mapState } from 'vuex';
export default {
  name: 'yt-ad',
  props:{
    statistics:{ /* 组件内部是否统计广告 */
      type:Boolean,
      default:true
    },
    initiative:{ /* 是否触发广告,为false时由父级refs调用trigger() */
      type:Boolean,
      default:true
    },
    usePay:{ /* 强制使用支付功能 */
      type:Boolean,
      default:false
    },
  },
  data() {
    return {
      isAd:true,
      product_id:null,
      startTime:0
    }
  },
  computed: {
    canFollowed(){
      // 判断基础库版本是否符合要求
      const { SDKVersion,appName } = uni.getSystemInfoSync();
      if(SDKVersion && appName==='Douyin'){
        return compareVersion(SDKVersion,'1.68.0')
      }else {
        return false
      }
    },
    free_again() {
      if(this.$store.state.exam){
        return uni.getStorageSync('free_again') || this.$store.state.exam.free_again || 0// 再测一次次数
      }
      return 0
    },
    isPay(){
      const appName = this.systemInfo?.appName || this.systemInfo?.AppPlatform;
      return this.usePay || (appName === 'Toutiao' && this.$slots['pay'])
    },
    ...mapState('index',[
      'openid',
      'agent_name',
      'agent_id',
      'spread_id',
      'ad_config',
      'systemInfo',
      'price',
      'mid'
    ]),
  },
  
  mounted(){
    const routers = getCurrentPages()
    const { product_id } = routers[routers.length - 1].options
    this.product_id = product_id || this.$store.state.index.product_id
    // #ifdef MP-TOUTIAO
    if(this.$slots['attent']){
      const { flow_dy,max_evoke_ad } = this.ad_config
      const current_ad_number = parseInt(uni.getStorageSync('ad' + dateFormat(null,'MMdd')) || 0);
      if(max_evoke_ad <= current_ad_number && flow_dy && this.canFollowed){
        this.checkFollowAwemeState().then(hasFollowed => {
          if(!hasFollowed){
            this.isAd = false
          }
        })
      }
    }
    // #endif
  },
  methods: {
    dispatchEvent(e){
      if(this.initiative){
        if(this.isPay){
          this.onPay()
        }else if(this.isAd){
          this.onVideo()
        }else{
          this.onAttent()
        }
      }else{
        this.$emit('trigger',e)
      }
    },
    trigger(){
      if(this.isPay){
        this.onPay()
      }else if(this.isAd){
        this.onVideo()
      }else{
        this.onAttent()
      }
    },
    checkFollowAwemeState(){
      /* 校验当前是否关注过 */
      return new Promise(function(resolve){
        let hasFollowed = false
        tt.checkFollowAwemeState({
          complete: function(res) {
            try{
                hasFollowed = res.hasFollowed;
            // eslint-disable-next-line no-empty
            }catch(e){}
            resolve(hasFollowed)
          }
        })
      })
    },
    // 进行支付
    onPay:debounce(function(){
      if (this.systemInfo?.platform === 'ios') {
        uni.showModal({
          content:'IOS端暂不支持虚拟支付！',
          showCancel:false
        })
        return false
      }
        uni.$yt.uv('pay')
        uni.showLoading({
          title: '请稍侯',
          mask:true
        });

        const { openid,mid,price,agent_id,product_id,spread_id } = this
        const service = 5
        const params = {
            openid,
            miniapp_id:mid,
            amount:price,
            agent_id,
            product_id,
            spread_id,
            service,
            return_url:'/pages/index/index'
        }

          doPay(params).then(({data:orderInfo,out_order_no}) => {
            uni.hideLoading();
            uni.getProvider({ 
              service:'payment',
              success:({ provider }) => {
                uni.requestPayment({
                  service,
                  provider:provider[0],
                  orderInfo,
                  getOrderStatus: (order) => {
                      uni.showLoading({
                        title: '正在查询订单...',
                        mask:true
                      });
                      return new Promise((resolve) => {
                        // 递归查询订单状态，以防遗漏
                        const checkPayStatus = (count) => {
                          getPayStatus({ out_trade_no:out_order_no }).then(res => {
                              if(res.status) {
                                  uni.hideLoading();
                                  resolve({ code: 0 })
                              } else {
                                if(count > 0){
                                  setTimeout(() => {
                                    checkPayStatus(--count)
                                  },1000)
                                }else{
                                  uni.hideLoading();
                                  resolve({ code: 2 })
                                }
                              }
                          }).catch(err => {
                            if(count > 0){
                              setTimeout(() => {
                                checkPayStatus(--count)
                              },1000)
                            }else{
                              uni.hideLoading();
                              resolve({ code: 2,err })
                            }
                          })
                        }
                        checkPayStatus(4)
                      })
                  },
                  success: (pay_info) => {
                      if (pay_info.code === 0) {
                        uni.$yt.uv('payed')
                        this.$emit('success',1)
                      } else {
                        uni.showToast({
                            title: '支付失败！',
                            duration: 1500,
                            icon: 'none'
                        })
                      }
                  },
                  fail: (pay_err) => {
                      uni.showToast({
                          title: '支付错误:' + pay_err.errCode,
                          duration: 2000,
                          icon: 'none'
                      });
                  }
              })
            }
          })
        }).catch(() => {
            uni.hideLoading();
            uni.showToast({
              title: '唤起支付失败',
              duration: 2000
            });
        })
    },500,true),
    onVideo:debounce(async function(){
      uni.$yt.uv('reward')
      /* 后台广告配置
        flow_dy : 是否关注抖音号
        max_evoke_ad : 广告最大播放次数
        overflow_evoke:超出次数后是否允许继续测试
        current_ad_number : 当前播放次数
      */
      // eslint-disable-next-line prefer-const
      if(/\d+/.test(this.free_again) && this.free_again > 0){
        const num = this.free_again - 1
        console.log('再测一次剩余次数',num);
        this.$store.commit('exam/set_free_again',num);
        uni.setStorageSync('free_again', num)
        this.$emit('success',9)
        return
      }
      let { max_evoke_ad,overflow_evoke } = this.ad_config
      const current_ad_number = parseInt(uni.getStorageSync('ad' + dateFormat(null,'MMdd')) || 0);
      console.log('当前广告播放次数',current_ad_number);
      if(current_ad_number >= max_evoke_ad){
        if(overflow_evoke){
          this.$emit('success',7)
          console.log('测试次数已达上限,继续测试但不记录广告');
        }else{
          uni.showModal({
            title: '提示',
            content: '测试次数已达上限,请明天继续测试!',
            showCancel:false
          })
        }
      }else{
        this.startTime = Date.now();
        this.$yt.rewardedAd(!!this.agent_name).then(({ code }) => {
          const duration = parseInt((Date.now() - this.startTime)/1000)
          if(code){
            if(code === 2){
              // 广告播放完毕
              if(this.statistics){
                const params = {
                  mid:this.mid,
                  openid:this.openid,
                  agent_id:this.agent_id,
                  product_id:this.product_id,
                  spread_id:this.spread_id,
                  ad_time:duration
                }
                postAdOrder(params)
              }
              uni.$yt.uv('rewarded')
              uni.setStorageSync('ad' + dateFormat(null,'MMdd'),current_ad_number + 1)
            }
            this.$emit('success',code,duration)
          }else{
            this.$emit('close-ad')
          }
        })
      }
    },500,true),
    // 关注抖音号事件
    onAttent(){
      const that = this
      that.checkFollowAwemeState().then(canFollowed => {
        if(!canFollowed){
          tt.openAwemeUserProfile({
            complete: function(res) {
              const { hasFollowed } = res;
              tt.showToast({
                title: `关注${hasFollowed ? '成功' : '失败'}`,
                icon:hasFollowed ? 'success' : 'none'
              });
              if(hasFollowed){
                that.isAd = true
                that.$emit('success',8)
              }
            }
          })
        }
      })
    }
  }
 }
</script>
