<template>
  <div class="coupons">
    <div class="content">
      <div class="coupon-banner">
        <img src="~/assets/images/coupon-center.jpg" alt />
      </div>
      <div class="coupons-con" v-if="dataList.length">
        <div class="tit">
          <span class="bg-l"></span>{{$t('coupons.generalCoupon')}}
          <span class="bg-r"></span>
        </div>
        <div class="con-box">
          <div
            :class="['item', (item.canGoUse) ? 'received' : ((!item.stocks) ? 'robbed' : '')]"
            v-for="(item, index) in dataList"
            :key="item.couponId"
          >
            <div class="text">
              <div class="coupon-price">
                <span class="symbol" v-if="item.couponType === 1">￥</span>
                <span class="big" v-if="item.couponType === 1">{{item.reduceAmount}}</span>
                <span class="big" v-if="item.couponType === 2">{{item.couponDiscount}}</span>
                <span class="symbol-s" v-if="item.couponType === 2">{{$t('fold')}}</span>
                <span class="limit" v-if="$t('full')=='满'">{{$t('full')}}{{$t('yuan')}}{{item.cashCondition}}{{$t('available')}}</span>
                <span class="limit" v-if="$t('full')!='满'" style="maxWidth:110px">{{$t('available')}} {{$t('over')}}{{$t('yuan')}}{{item.cashCondition}}</span>
              </div>
              <div class="range" v-if="item.suitableProdType == 0">{{$t('coupons.canUsedPurchaseFullRangeOfProducts')}}</div>
              <div class="range" v-if="item.suitableProdType != 0">{{$t('coupons.onlySomeProductsOnThePlatformCanPurchased')}}</div>
              <div class="time" v-if="item.validTimeType === 1" style="lineClamp:2">{{$t('coupons.validUntil')}}：{{item.endTime}}</div>
              <div class="time" v-if="item.validTimeType === 2" style="lineClamp:2">{{$t('coupons.onlyAfterCouponing')}} {{item.validDays}} {{$t('coupons.useWithinDays')}}</div>
            </div>
            <div class="rest">
              <div
                class="number"
              >{{item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed')+parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%'}}</div>
              <div class="scale">
                <span
                  class="percent"
                  :style="{width:[item.stocks === 0?'100%' : ((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                ></span>
              </div>
              <a
                href="javascript:void(0);"
                class="btn"
                v-if="!item.canGoUse && item.stocks"
                @click="receiveCoupon(item,index,1)"
              >{{$t('coupons.getItNow')}}</a>
              <a
                href="javascript:void(0);"
                class="btn"
                v-if="item.canGoUse"
                @click="useCoupon(item)"
              >{{$t('coupons.goToUse')}}</a>
              <a href="javascript:void(0);" class="btn" v-if="!item.canGoUse && !item.stocks">{{$t('coupons.soldOut')}}</a>
            </div>
            <div class="icon received-icon" v-if="item.canGoUse && language == 'zh'"></div>
            <div class="icon-en" v-if="item.canGoUse && language == 'en'">
              <img src="~/assets/images/coupon-received-en.png" alt="">
            </div>
            <div class="icon robbed-icon" v-if="!item.canGoUse && !item.stocks && language == 'zh'"></div>
            <div class="icon-en" v-if="!item.canGoUse && !item.stocks && language == 'en'">
              <img src="~/assets/images/coupon-robbed-en.png" alt="">
            </div>
          </div>
        </div>
      </div>

      <div class="coupons-con" v-if="dataListProd && dataListProd.length">
        <div class="tit">
          <span class="bg-l"></span>{{$t('coupons.recommendedCoupons')}}
          <span class="bg-r"></span>
        </div>
        <div class="con-box">
          <div
            :class="['s-item' , (item.canGoUse) ? 'received' : ((!item.stocks) ? 'robbed' : '') , (item.prods.length == 1) ? 'single': '']"
            v-for="(item,index) in dataListProd"
            :key="item.couponId"
          >
            <!-- 多商品 -->
            <div class="goods-box" v-if="item.prods.length > 1">
              <div class="shop-msg">
                <div class="logo">
                  <img :src="item.shopLogo" alt />
                </div>
                <div class="name">{{item.shopName}}</div>
              </div>
              <div class="prods">
                <div class="p-item" v-for="(prod,index) in item.prods" :key="index">
                  <div class="img">
                    <img v-if="prod.pic" :src="prod.pic" alt @error="handlePicError" />
                    <img v-else src="~/assets/img/def.png" alt />
                  </div>
                  <div class="price">￥{{prod.price}}</div>
                </div>
              </div>
            </div>
            <div class="rest" v-if="item.prods.length > 1">
              <div class="coupon-price">
                <span class="symbol" v-if="item.couponType === 1">￥</span>
                <span class="big" v-if="item.couponType === 1">{{item.reduceAmount}}</span>
                <span class="big" v-if="item.couponType === 2">{{item.couponDiscount}}</span>
                <span class="symbol-s" v-if="item.couponType === 2">{{$t('fold')}}</span>
              </div>
              <!-- <div class="limit">{{$t('full')}}{{item.cashCondition}}{{$t('yuan')}}{{$t('available')}}</div> -->
              <div class="limit" v-if="$t('full')=='满'">{{$t('full')}}{{$t('yuan')}}{{item.cashCondition}}{{$t('available')}}</div>
              <div class="limit" v-if="$t('full')!='满'" style="maxWidth:110px">{{$t('available')}} {{$t('over')}}{{$t('yuan')}}{{item.cashCondition}}</div>
              <div class="scale">
                <div
                  class="number"
                >{{item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed') + parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%'}}</div>
                <div
                  class="percent"
                  :style="{width:[item.stocks === 0?'100%' : parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                ></div>
              </div>
              <a
                href="javascript:void(0);"
                class="btn"
                v-if="!item.canGoUse && item.stocks"
                @click="receiveCoupon(item,index,2)"
              >{{$t('coupons.getItNow')}}</a>
              <a
                href="javascript:void(0);"
                class="btn"
                v-if="item.canGoUse"
                @click="useCoupon(item)"
              >{{$t('coupons.goToUse')}}</a>
              <a href="javascript:void(0);" class="btn" v-if="!item.canGoUse && !item.stocks">{{$t('coupons.soldOut')}}</a>
            </div>
            <!-- /多商品 -->
            <!-- 单商品 -->
            <div class="single-box" v-if="item.prods.length == 1">
              <div class="img">
                <img :src="item.prods[0].pic" alt @error="handlePicError"/>
              </div>
              <div class="text-box">
                <div class="goods-name">{{item.prods[0].prodName}}</div>
                <div class="scale-box">
                  <div
                    class="number"
                  >{{item.stocks === 0?$t('coupons.soldOut'):$t('coupons.robbed') + parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%'}}</div>
                  <div class="scale">
                    <div
                      class="percent"
                      :style="{width:[item.stocks === 0?'100%' : parseInt((item.sourceStock - item.stocks) * 100 /item.sourceStock)+'%']}"
                    ></div>
                  </div>
                </div>
                <div class="coupon-info">
                  <div class="coupon-price">
                    <span class="symbol" v-if="item.couponType === 1">￥</span>
                    <span class="big" v-if="item.couponType === 1">{{item.reduceAmount}}</span>
                    <span class="big" v-if="item.couponType === 2">{{item.couponDiscount}}</span>
                    <span class="symbol-s" v-if="item.couponType === 2">{{$t('fold')}}</span>
                   <div class="limit" v-if="$t('full')=='满'">{{$t('full')}}{{$t('yuan')}}{{item.cashCondition}}{{$t('available')}}</div>
                   <div class="limit" v-if="$t('full')!='满'" style="maxWidth:110px">{{$t('available')}} {{$t('over')}}{{$t('yuan')}}{{item.cashCondition}}</div>
                  </div>
                  <a
                    href="javascript:void(0);"
                    class="btn"
                    v-if="!item.canGoUse && item.stocks"
                    @click="receiveCoupon(item,index,2)"
                  >{{$t('coupons.getItNow')}}</a>
                  <a
                    href="javascript:void(0);"
                    class="btn"
                    v-if="item.canGoUse"
                    @click="useCoupon(item)"
                  >{{$t('coupons.useNow')}}</a>
                  <a
                    href="javascript:void(0);"
                    class="btn"
                    v-if="!item.canGoUse && !item.stocks"
                  >{{$t('coupons.soldOut')}}</a>
                </div>
              </div>
            </div>
            <!-- /单商品 -->
            <div class="icon received-icon" v-if="item.canGoUse && language == 'zh'"></div>
            <div class="icon-en" v-if="item.canGoUse && language == 'en'">
              <img src="~/assets/images/coupon-received-en.png" alt="">
            </div>
            <div class="icon robbed-icon" v-if="!item.canGoUse && !item.stocks"></div>
            <div class="icon-en" v-if="!item.canGoUse && !item.stocks && language == 'en'">
              <img src="~/assets/images/coupon-robbed-en.png" alt="">
            </div>
          </div>
        </div>
      </div>
      <pagination v-model="current" :pages="pages" @changePage="getProdCouponList"></pagination>
      <!-- 商品列表为空 -->
      <div class="empty" v-if="(!dataList.length && !dataListProd.length) || (!dataList && !dataListProd)">
        <div class="img">
          <img src="~/assets/images/emptyPic/coupon-empty.png" alt />
        </div>
        <div class="action">
          <div class="text">{{$t('coupons.sorryNoCouponsAvailable')}}</div>
          <nuxt-link to="/" class="btn">{{$t('backToHome')}}</nuxt-link>
        </div>
      </div>
      <!-- /商品列表为空 -->
    </div>
  </div>
</template>

<script>

import Pagination from '~/components/pagination'
import Cookie from 'js-cookie'
export default {
  components: {
    Pagination
  },
  data () {
    return {
      dataList: [], // 通用券列表
      dataListProd: [],  // 商品券列表
      pages: 0,  // 总页数
      current: this.$route.query.current || 1,  // 当前页数
      selectedCouponId: 0, // 要领取的优惠券id
      language: this.$store.state.locale,
    }
  },
  mounted () {
    document.title = this.$t('userCenter.couponCenter')
    this.getGeneralCouponList()
    this.getProdCouponList(1)
  },
  methods: {
    /**
     * 加载默认图片
     */
    handlePicError(e){
       e.target.src=require('@/assets/img/def.png')
    },
    /**
    * 获取通用券列表
    */
    getGeneralCouponList () {
      let url = Cookie.get('token') ? '/p/myCoupon/generalCouponList' : '/coupon/generalCouponList'
      this.$axios.get(url).then(({ data }) => {
        this.initCouponCanGoUseFlag(data);
        this.dataList = data
      })
    },
    /**
     * 获取商品券列表
     */
    getProdCouponList () {
      let url = Cookie.get('token') ? '/p/myCoupon/getCouponPage' : '/coupon/getCouponPage'
      this.$axios.get(url, {
        params: {
          current: this.current,
          size: 20,
        }
      }).then(({ data }) => {
        console.log(data.records)
        this.initCouponCanGoUseFlag(data.records);
        this.dataListProd = data.records
        this.pages = data.pages
      })
    },
    /**
     * 初始化优惠券去可以使用的标记
     */
    initCouponCanGoUseFlag (couponList) {
      couponList.forEach(coupon => {
        coupon.canGoUse = coupon.curUserReceiveCount >= coupon.limitNum;
      });
    },

    /**
     * 设置优惠券可以去使用的标记
     */
    setCouponCanGoUseFlag (index, couponType) {
      if (couponType == 1) {
        var tempCouponList = this.dataList;
        console.log(tempCouponList)
        tempCouponList[index].canGoUse = true;
        tempCouponList[index].stocks -= 1;
        this.dataList = tempCouponList
      } else if (couponType == 2) {
        var tempCouponList = this.dataListProd;
        tempCouponList[index].canGoUse = true;
        tempCouponList[index].stocks -= 1;
        this.dataListProd = tempCouponList
      }
    },
    /**
    * 领取优惠券
    */
    receiveCoupon (item, index, coupontype) {
      if (item.couponId) {
        this.$axios.post('/p/myCoupon/receive', item.couponId).then(({ data }) => {
          if (data) {
            this.$message({
              message: data,
              type: 'success',
              duration: 1500
            })
          }
          this.setCouponCanGoUseFlag(index, coupontype);
        })
      }
    },
    /**
     * 立即使用
     */
    useCoupon (item) {
      let url = '/list?st=4';
      let couponId = item.couponId;
      let prodList = item.prods
      if (prodList && prodList.length == 1) {
        this.$router.push({ path: '/detail/' + prodList[0].prodId });
      } else {
        if (couponId) {
          url += "&couponId=" + couponId;
        }
        this.$router.push({ path: url });
      }
    },
  }
}
</script>

<style scoped src='~/assets/css/coupons.css'></style>
