<template>
  <!-- 领取优惠券 -->
  <div
    class="coupon-row"
    :style="{
      background: `url(${couponPackage.backgroundImageUrl}) no-repeat`,
      backgroundRepeat: 'no-repeat',
      backgroundSize: 'contain',
      backgroundPosition: `100% 100%`
    }"
  >
    <!--packageType 券包类型 1:有倒计时 2:无倒计时 -->
    <!--received 是否领取	 -->
    <div v-if="+couponPackage.packageType === 1 && couponPackage.received" class="query-package">
      <img
        src="https://appsync.lkbang.net/Fg2n5Dj5q_rKfFVEESUlUfKYnqXq"
        alt=""
        @click="queryCoupon()"
      />
    </div>
    <div class="coupon-wrapper">
      <div class="coupon-row-con">
        <div class="coupon-btn">
          <div
            v-if="!couponPackage.received"
            class="once-get"
            @click="getCoupon(couponPackage.received)"
          >
            一键领取
          </div>
          <div
            v-if="+couponPackage.packageType === 2 && couponPackage.received"
            class="query-coupon"
            @click="queryCoupon()"
          >
            查看券包详情>
          </div>
          <div
            v-if="couponPackage.received && +couponPackage.packageType === 1"
            class="count-down"
            @click.stop="() => false"
          >
            <img src="https://img.lkbang.net/shijian.b5af07a0.png" alt="" />
            <cr-count-down
              :time="couponPackage.endTime - couponPackage.currentTime"
              format="距结束 {d}天{h}时{m}分  "
            />
          </div>
        </div>
        <div class="content">
          <div
            :ref="`couponRow${index}`"
            class="content-wrapper"
            @scroll="scrollEvent(index)"
            @touchstart="onTouch"
            @touchmove="onTouch"
            @touchend="onTouch"
          >
            <!-- itm.publishCountFinished发行数量是否已领完： true 领完，false 未领完 -->
            <!-- itm.status  状态：1-未使用，2-已使用、3-已过期 -->
            <div
              v-for="(itm, idx) in couponPackage.coupons"
              :key="idx"
              class="content-item"
              :style="{
                background: `url(${
                  itm.publishCountFinished
                    ? couponPackage.invalidCouponBackgroundImageUrl
                    : couponPackage.couponBackgroundImageUrl
                }) no-repeat`,
                backgroundSize: 'contain',
                backgroundPosition: `100% 100%`,
                filter: ` ${
                  itm.publishCountFinished || [2, 3].includes(+itm.status)
                    ? `grayscale(100%)`
                    : 'none'
                } `
              }"
              @click="
                if (!couponPackage.received) {
                  getCoupon(couponPackage.received);
                } else {
                  handleToDetailsTrack(
                    { jumpUrl: itm.navUrl },
                    'NewUserPageNewUserCouponBag',
                    idx,
                    {
                      coupon_id: itm.id,
                      buttons_name: `${'立即使用'}`
                    }
                  );
                }
              "
            >
              <div class="content-item-sku" :style="{ color: couponPackage.titleColor }">
                {{ itm.name }}
              </div>
              <div class="content-item-money" :style="{ color: couponPackage.faceAmountColor }">
                <span>￥</span>
                <span :style="{ fontSize: calcFontSize(`${itm.faceValue}`) }">{{
                  itm.faceValue
                }}</span>
              </div>
              <div class="content-item-discount" :style="{ color: couponPackage.attrColor }">
                {{ itm.limitDesc }}
              </div>
              <div
                class="content-item-get"
                :style="{
                  background: couponPackage.buttonBackgroundColor,
                  color: couponPackage.buttonTextColor
                }"
                @click="getCoupon(couponPackage.received)"
              >
                <!--received 是否领取 false：未领取 ture：已领取  -->
                <!-- {{ !couponPackage.received ? '立即领取' : '立即使用' }} -->
                {{ showText(itm, couponPackage) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import api from '@/api/newPeopleArea.api';
import mxBll from '../../home/mixin/mxBll';
import { TRACK_EVENT_MAP } from '../model';
import localStorage from '@/service/localStorage.service';

export default {
  mixins: [mxBll],
  props: {
    sourceData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      index: 0,
      calcWidth: 0,
      scrollIndex: 0
    };
  },
  computed: {
    couponPackage() {
      return this.sourceData.couponPackage;
    }
  },
  mounted() {
    if (this.$refs[`couponRow${this.index}`]) {
      this.$refs[`couponRow${this.index}`].addEventListener('scroll', (e, index) => {
        this.handleScroll(e, index);
      });
      this.initCalcWidth();
    }
  },
  methods: {
    // 显示文案
    showText(itm, couponPackage) {
      if (itm.publishCountFinished) {
        return '已抢光';
      }
      if (itm.status && +itm.status === 2) {
        return '已使用';
      }
      if (itm.status && +itm.status === 3) {
        return '已过期';
      }
      if (!couponPackage.received) {
        return '立即领取';
      } else {
        return '立即使用';
      }
    },
    calcFontSize(params) {
      let len = params.length;
      let fontSize = '35px';
      switch (len) {
        case 3:
          fontSize = '30px';
          break;
        case 4:
          fontSize = '20px';
          break;
        case 5:
          fontSize = '18px';
          break;
        case 6:
          fontSize = '14px';
          break;
        default:
          break;
      }
      return fontSize;
    },
    // 查看券包
    queryCoupon() {
      this.$emit('getCoupon', true);
    },
    handleToDetailsTrack(item, area, index, buriedPoint = {}) {
      if (item.needLogin && !localStorage.get('vccToken')) {
        this.$config.signOutFn();
        return;
      }
      const trackInfo = TRACK_EVENT_MAP[area];
      if (trackInfo) {
        this.$track.registeredEvents(
          trackInfo.name,
          {
            position_number: index,
            ...buriedPoint,
            [trackInfo.trackKey]: item[trackInfo.itemKey]
          },
          () => {
            this.mxHandleToDetails({ item, area, index });
          }
        );
      } else {
        this.mxHandleToDetails({ item, area, index });
      }
    },
    initCalcWidth() {
      let scrollWidth = this.$refs[`couponRow${this.index}`].scrollWidth;
      let offsetWidth = this.$refs[`couponRow${this.index}`].offsetWidth;
      this.calcWidth = (offsetWidth / scrollWidth) * 100;
    },
    scrollEvent(index) {
      this.scrollIndex = index;
    },
    // 阻止滚动触发滑动到频道页
    onTouch(e) {
      e.stopPropagation();
    },
    // 专题横线平移滑动
    handleScroll() {
      let index = this.scrollIndex;
      let scrollLeft = this.$refs[`couponRow${index}`].scrollLeft;
      let scrollWidth = this.$refs[`couponRow${index}`].scrollWidth;
      let offsetWidth = this.$refs[`couponRow${index}`].offsetWidth;
      let calcWidth = ((scrollLeft + offsetWidth) / scrollWidth) * 100;
      if (calcWidth >= 100) {
        calcWidth = 100;
      }
      if (calcWidth <= 0) {
        calcWidth = 0;
      }
      this.calcWidth = calcWidth;
      return;
    },
    // 一键领取
    async getCoupon(val) {
      if (val) {
        return false;
      }
      let params = {
        couponPackageId: this.couponPackage.couponPackageId
      };
      this.$track.registeredEvents('H5_NewUserPageNewUserCouponBagOneClickReceiveBtnClick', {
        couponbag_id: params.couponPackageId
      });
      let [data] = await api.getPackageAll(params);
      if (data) {
        this.$toast('领取成功');
        this.$emit('getCoupon', true);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.coupon-row {
  display: flex;
  flex-direction: column;
  // background: url('https://appsync.lkbang.net/FkNapv0Qe4HRvGMwh8cOtIL54aBO') no-repeat;
  // background-size: contain;
  // background-position: 100% 100%;
  min-height: 169px;
  margin: @padding-sm;
  position: relative;
  .query-package {
    position: absolute;
    right: 0px;
    top: 42px;
    z-index: 10;
    max-width: 26px;
    max-height: 122px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  &-con {
    overflow: hidden;
    position: relative;
    .coupon-btn {
      position: absolute;
      display: flex;
      justify-content: flex-end;
      right: 0;
      padding: 20px 12px 0 0;
      .once-get {
        background: linear-gradient(to right, #f58c00, #fa5106, #ec1500);
        color: #fff;
        .text-size(10);
        height: 20px;
        width: 64px;
        text-align: center;
        line-height: 20px;
        border-radius: 25px;
      }
      .query-coupon {
        .text-size(12);
        color: rgba(153, 153, 153, 1);
      }
      .count-down {
        display: flex;
        justify-content: flex-end;
        border-radius: 25px;
        align-items: center;
        padding: 2px;
        white-space: pre-wrap;
        background: linear-gradient(to right, #f58c00, #fa5106, #ec1500);
        &-text {
          .text-size(12);
        }
        img {
          width: 16px;
          height: 15px;
          padding-right: 4px;
          flex-shrink: 0;
        }
        .cr-count-down {
          .text-size(10);
          color: #fff;
        }
      }
    }
    .query-package {
      right: 0;
    }
    .content {
      overflow: hidden;
      &-wrapper {
        overflow-x: scroll;
        overflow-y: hidden;
        display: flex;
        flex-flow: row nowrap;
        height: 110px;
        margin: 49px 0 16px 16px;
        &::-webkit-scrollbar {
          width: 0 !important;
          display: none;
        }
      }
      &-item {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;
        flex-shrink: 0;
        background: url('https://appsync.lkbang.net/FkjsnxsOEvLxxKl_EoJc0-viYkA_') no-repeat;
        background-size: contain;
        background-position: 100% 100%;
        margin-right: 8px;
        min-width: 90px;
        min-height: 104px;
        position: relative;
        &-sku {
          padding-top: 16px;
          .text-size(10);
          color: #fa4528;
          text-align: center;
          white-space: nowrap;
          width: 70px;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &-money {
          color: #fa4528;
          letter-spacing: -1px;
          font-weight: @font-weight-bold;
          line-height: 0;
          max-width: 100px;
          span:first-child {
            .text-size(14);
          }
          span:last-child {
            .text-size(32);
            text-align: center;
            line-height: 30px;
            padding-right: 12px;
            letter-spacing: -1px;
            font-weight: @font-weight-bold;
          }
        }
        &-discount {
          .text-size(10);
          color: #fa4528;
        }
        &-get {
          position: absolute;
          bottom: 6px;
          border-radius: 8px;
          padding: 0 8px;
          background: linear-gradient(to right, #ffffff, #ffece6);
          .text-size(9);
          color: #fa4528;
        }
      }
      &-item:last-child {
        margin-right: 30px;
      }
    }
    .progress {
      margin: 0 auto;
      width: 36px;
      padding: 10px 0;
    }
  }
}
</style>
