<template>
  <div>
    <van-tabs v-model="active" :before-change="beforeTabChange" sticky>
      <div id="cardBox">
        <van-tab title="未使用">
          <!-- <div class="exchange_btn" @click="handleExchange">
            <p>
              <van-icon name="coupon-o" />
              兑换优惠券
            </p>
            <van-icon name="arrow" />
          </div> -->
          <div class="card_item" :class="{'big':item.picsArr.length>1,'margin_bottom':item.desShow}" v-for="(item,index) in cardList" :key="index">
            <div class="left">
              <div class="top" @click="handleUseCard(index)">
                <template v-if="item.picsArr.length==1">
                  <img :src="item.picsArr[0]" alt="">
                  <p class="title">仅该商品可用：<span>{{item.proNameArr[0]}}</span></p>
                </template>
                <template v-if="item.picsArr.length>1">
                  <p class="bigtext">{{item.title}}</p>
                  <template v-for="(img,index2) in item.picsArr">
                    <img class="bigimg" v-if="index2<3" :src="img" :key="index2" alt="">
                  </template>
                </template>
              </div>
              <p class="end_time" @click="item.desShow=!item.desShow">
                <span>有效期至：{{item.couponEndTimeVo}}</span>
                <van-icon v-if="item.desShow" name="arrow-up" />
                <van-icon v-else name="arrow-down" />
              </p>
            </div>
            <div class="right" @click="handleUseCard(index)">
              <p class="discount" :class="item.couponState==1?'':'disable'"><span>¥</span>{{item.couponPrice}}</p>
              <p class="usenow" v-if="item.couponState==1">立即使用</p>
              <p class="usenow disable" v-else>{{item.couponState==2?'已使用':'已过期'}}</p>
            </div>
            <p class="des" v-if="item.desShow">仅限领券中心品类券指定商品内使用</p>
          </div>

          <van-empty v-if="cardList.length==0" description="暂无优惠券" />
        </van-tab>
        <van-tab title="领券中心">
          <div class="card_item" :class="{'big':item.picsArr.length>1,'margin_bottom':item.desShow}" v-for="(item,index) in reCardList" :key="index">
            <div class="left">
              <div class="top">
                <template v-if="item.picsArr.length==1">
                  <img :src="item.picsArr[0]" alt="">
                  <p class="title">仅该商品可用：<span>{{item.proNameArr[0]}}</span></p>
                </template>
                <template v-if="item.picsArr.length>1">
                  <p class="bigtext">{{item.title}}</p>
                  <template v-for="(img,index2) in item.picsArr">
                    <img class="bigimg" v-if="index2<3" :src="img" :key="index2" alt="">
                  </template>
                </template>
              </div>
              <p class="end_time" @click="item.desShow=!item.desShow">
                <span v-if="item.lifeFlag==1">领取后当天生效，有效期为：{{item.lifeDay}}天</span>
                <span v-else>有效期至：{{item.lifeTime}}</span>
                <van-icon v-if="item.desShow" name="arrow-up" />
                <van-icon v-else name="arrow-down" />
              </p>
            </div>
            <div class="right" @click="reCard(item)">
              <p class="discount" :class="item.geted?'disable':''"><span>¥</span>{{item.couponPrice}}</p>
              <p class="usenow disable" v-if="item.geted">已领取</p>
              <p class="usenow" v-else>立即领取</p>
            </div>
            <p class="des" v-if="item.desShow">仅限领券中心品类券指定商品内使用，每人仅可领取一次！</p>
          </div>
          <van-empty v-if="reCardList.length==0" description="暂无优惠券" />

        </van-tab>
      </div>
    </van-tabs>
  </div>
</template>
<script>
export default {
  name: 'CardBoxXST',
  data () {
    return {
      cardList: [],
      reCardList: [],
      centerNo: '',
      active: 0,
      pickerArr: []
    }
  },
  mounted () {
    let active = this.$route.query.active;
    if (active) {
      this.active = Number(active)
    }
    this.centerNo = sessionStorage.getItem('centerNo')
    this.getAllCard()
    this.getReCard()
  },
  methods: {
    beforeTabChange (item) {
      if (item == 0) {
        this.getAllCard()
      } else {
        this.getReCard()
      }
      return true;
    },
    // 获取所有优惠券
    getAllCard () {
      this.mgop({
        api: 'mgop.sz.hswsy.CouponList', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "userId": this.centerNo,
          "state": '',//状态 1-正常 2-已使用 3-已过期 不传为全部,
          "pageNum": '1',
          "pageSize": '999'
        },
        onSuccess: res => {
          console.log('所有优惠券：', res)
          if (res.data.rows) {
            let cardList = res.data.rows
            for (let i in cardList) {
              // cardList[i].useEndTime = this.Moment(cardList[i].useEndTime.replace(/\-/g, "/")).format("YYYY-MM-DD")
              cardList[i].picsArr = cardList[i].pics.split(',');
              cardList[i].proNameArr = cardList[i].proName.split(',');
              cardList[i].desShow = false;
            }
            this.cardList = cardList
            if (this.reCardList.length > 0) {
              this.$nextTick(() => {
                this.resetReCardList()//设置领券中心券的状态
              })
            }
          }
          else {
            this.$toast.fail(res.data.message);
          }

        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },

    //待领取的优惠券
    getReCard () {
      this.mgop({
        api: 'mgop.sz.hswsy.getNormalCoupons', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "unionId": this.centerNo,
        },
        onSuccess: res => {
          console.log('待领取的优惠券：', res)
          if (res.data.rows) {
            let reCardList = res.data.rows
            for (let i in reCardList) {
              reCardList[i].lifeTime = this.Moment(new Date(reCardList[i].lifeTime)).format("YYYY-MM-DD HH:mm:ss")
              reCardList[i].picsArr = reCardList[i].pics.split(',');
              reCardList[i].proNameArr = reCardList[i].proName.split(',');
              reCardList[i].desShow = false;
            }
            this.reCardList = reCardList
            if (this.reCardList.length > 0) {
              this.$nextTick(() => {
                this.resetReCardList()//设置领券中心券的状态
              })
            }
          } else {
            this.$toast.fail(res.data.msg);
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });

    },
    //设置领券中心券的状态
    resetReCardList () {
      let cardList = this.cardList;
      let reCardList = this.reCardList;
      for (let i = 0; i < reCardList.length; i++) {
        for (let j = 0; j < cardList.length; j++) {
          if (reCardList[i].id == cardList[j].id) {
            reCardList[i].geted = true
          }
        }
      }
      console.log(this.reCardList)
      this.reCardList = reCardList
      this.$forceUpdate()

    },
    //领取优惠券
    reCard (item) {
      this.mgop({
        api: 'mgop.sz.hswsy.CouponGet', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "unionId": this.centerNo,
          "proId": item.proId,
          "proName": item.proName,
          "pic": item.pics,
          "couponId": item.id,
        },
        onSuccess: res => {
          console.log('领取优惠券：', res)
          if (res.data.code == 200) {
            this.$toast('领取成功！')
            this.$nextTick(() => {
              this.resetReCardList()//设置领券中心券的状态
            })
          } else {
            this.$toast.fail(res.data.message);
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });

    },
    // 使用优惠券
    handleUseCard (index) {
      const item = this.cardList[index];
      // 未使用才触发后续操作
      if (item.couponState == 1) {
        let proIdArr = item.proId.split(',')
        if (proIdArr.length == 1) {
          // 单个商品直接跳转商品
          this.$router.push({ name: 'ServiceAbroadDetail', query: { courseId: proIdArr[0] } })
        } else {
          // 多个商品跳转优惠券详情页
          sessionStorage.setItem('cardCousreCardId', item.id)
          sessionStorage.setItem('cardCousreCardPrice', item.couponPrice)
          sessionStorage.setItem('cardCousreCardTitle', item.title)
          sessionStorage.setItem('cardCousreProId', item.proId)
          sessionStorage.setItem('cardCousreProName', item.proName)
          sessionStorage.setItem('cardCousrePics', item.pics)
          sessionStorage.setItem('cardCousreGeted', true)//设置详情页优惠券状态为已领取
          this.$router.push({ name: 'CardCourseList' })
        }
      }
    },

    handleCard (index) {
      const item = this.reCardList[index];
      let proIdArr = item.proId.split(',')
      // 单个商品直接跳转商品
      if (proIdArr.length == 1) {
        this.$router.push({ name: 'ServiceAbroadDetail', query: { courseId: proIdArr[0] } })
      } else {
        // 多个商品跳转优惠券详情页
        sessionStorage.setItem('cardCousreCardId', item.id)
        sessionStorage.setItem('cardCousreCardPrice', item.couponPrice)
        sessionStorage.setItem('cardCousreCardTitle', item.title)
        sessionStorage.setItem('cardCousreProId', item.proId)
        sessionStorage.setItem('cardCousreProName', item.proName)
        sessionStorage.setItem('cardCousrePics', item.pics)
        sessionStorage.setItem('cardCousreGeted', false)//设置详情页优惠券状态为待领取
        this.$router.push({ name: 'CardCourseList' })
      }

    },
  }
}
</script>
<style lang="scss" scoped>
#cardBox {
  width: 100%;
  min-height: 100vh;
  background: rgb(246, 246, 250);
  overflow: hidden;
  box-sizing: border-box;
  padding-bottom: 100px;
  .exchange_btn {
    font-size: 28px;
    width: 710px;
    height: 76px;
    background: #ffffff;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 16px auto;
    box-sizing: border-box;
    padding: 0 16px;
  }
  .card_item {
    width: 726px;
    height: 210px;
    background: url("../../assets/service/card.png");
    background-size: 100%;
    background-repeat: no-repeat;
    margin: 0 auto;
    margin-top: 20px;
    position: relative;
    &.margin_bottom {
      margin-bottom: 60px;
    }
    &.big {
      height: 250px;
    }
    p {
      width: 100%;
      margin: 0;
    }
    .left {
      display: inline-block;
      width: 68%;
      height: 100%;
      vertical-align: top;
      box-sizing: border-box;
      padding: 24px 40px;
      padding-right: 0;
      padding-bottom: 10px;
      .top {
        display: flex;
        flex-wrap: wrap;
        img {
          width: 66px;
          height: 66px;
          background: #d8d8d8;
          border-radius: 6px;
        }
        .title {
          font-size: 24px;
          font-weight: bold;
          margin-left: 10px;
          word-break: break-all;
          max-width: 370px;
          span {
            color: #7f5316;
          }
        }
        .bigtext {
          font-size: 24px;
          width: 400px;
          font-weight: bold;
          margin-bottom: 10px;
        }
        .bigimg {
          width: 120px;
          height: 120px;
          margin-right: 16px;
        }
      }
    }
    .right {
      width: 32%;
      height: 100%;
      display: inline-flex;
      align-content: center;
      flex-wrap: wrap;
      position: relative;
    }
    .end_time {
      font-size: 24px;
      color: #999;
      left: 40px;
      position: absolute;
      bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 450px;
    }
    .discount {
      text-align: center;
      font-size: 60px;
      font-weight: bold;
      span {
        font-size: 24px;
      }
      &.disable {
        color: #999;
      }
    }
    .usenow {
      font-size: 32px;
      text-align: center;
      font-weight: bold;
      margin-top: 10px;
      &.disable {
        color: #999;
      }
    }
    .des {
      font-size: 26px;
      padding: 10px;
      color: #999;
    }
  }
}
</style>