<template>
  <div class="course_coupons" v-if="proCoupon.length>0">
    <div>
      <van-tag v-for="(item,index) in proCoupon" :key="index" color="#ffffff" text-color="#FF2B2B">{{proCouponHas?'已领取：':''}}{{item.title}}</van-tag>
    </div>
    <div @click="toCoupons" class="fontBlue">领取 ></div>
  </div>
</template>
<script>
export default {
  props: ['detailDataId', 'centerNo'],
  data () {
    return {
      proCoupon: [],//优惠券
      proCouponHas: false,//优惠券已领取
    }
  },
  mounted () {
    this.getOrderCoupon()
  },
  methods: {
    //获取产品可使用优惠券
    getOrderCoupon () {
      this.mgop({
        api: 'mgop.sz.hswsy.orderCoupon', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "proId": this.detailDataId,
          "userId": this.centerNo,
        },
        onSuccess: res => {
          if (res.data.data) {
            if (res.data.data.has.length > 0) {
              this.proCoupon = res.data.data.has
              localStorage.setItem("proCoupon", JSON.stringify(this.proCoupon))
              this.chooseDefaultUseCard(res.data.data.has)//设置默认选中的优惠券
              this.proCouponHas = true;
            } else if (res.data.data.get.length > 0) {
              this.proCoupon = {
                title: '您有可领优惠券'
              }
            }
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },
    // 设置默认选中的优惠券
    chooseDefaultUseCard (has) {
      if (has.length > 1) {
        let useCard = has[0];
        for (let i in has) {
          console.log(Number(has[i].couponPrice) > Number(useCard.couponPrice))
          if (Number(has[i].couponPrice) > Number(useCard.couponPrice)) {
            useCard = has[i]
          }
        }
        // console.log('useCard', useCard)
        this.proCoupon = [useCard]
        localStorage.setItem('useCard', JSON.stringify(useCard))

      } else {
        localStorage.setItem('useCard', JSON.stringify(this.proCoupon[0]))
      }
    },
    //领券
    toCoupons () {
      this.$router.push({
        name: "CardBoxXST",
      });
    },
  }
}
</script>