<template>
  <div v-if="Object.keys(detailInfo).length > 0" class="goods" style="height: 100%">
    <!-- 主体 -->
    <div class="goods-container">
      <div class="goods-red-bg" />
      <div class="goods-group-buy-head-content">
        <div class="goods-group-buy-head-content-desc">新人拼团，今日疯抢中</div>
        <div class="goods-group-buy-head-content-swipe">
          <swipe-customer-info v-model="showInfo" direction="right" />
        </div>
      </div>
      <div class="goods-product-info">
        <div class="goods-product-info-img">
          <span
            v-if="detailInfo.groupBuyInfo && detailInfo.groupBuyInfo.groupBuyLimitUserCount"
            class="goods-product-info-tag"
            >{{ detailInfo.groupBuyInfo.groupBuyLimitUserCount }}人团</span
          >
          <cr-image width="108px" :src="detailInfo.thumbImageUrl" />
        </div>
        <div class="goods-product-info-desc">
          <div class="goods-product-info-desc-part1">
            <div class="goods-product-info-desc-title">
              {{ detailInfo.goodsName }}
            </div>
            <div class="goods-product-info-desc-progress">
              <cr-progress
                class="group-item-progress"
                stroke-width="5"
                color="#EC1500"
                track-color="#F7F8F9"
                :show-pivot="false"
                :percentage="stockPercentage"
              />
            </div>
            <div class="goods-product-info-desc-num">
              已拼{{ detailInfo.groupBuyInfo ? detailInfo.groupBuyInfo.groupBuySuccessCount : 0 }}团
            </div>
          </div>
          <div class="goods-product-info-desc-price">
            <div class="goods-product-info-desc-price-group">
              成团价 ¥<span class="actualPrice">{{ detailInfo.activityPrice }}</span>
            </div>
            <div class="goods-product-info-desc-price-market">售价¥{{ detailInfo.price }}</div>
          </div>
        </div>
      </div>
      <div class="goods-group-info">
        <div class="goods-group-info-status">
          <cr-image
            v-if="detailInfo.groupBuyInfo.groupBuyStatus == 2"
            width="80"
            src="../../assets/images/success.png"
          />
          <cr-image
            v-if="detailInfo.groupBuyInfo.groupBuyStatus == 3"
            width="80"
            src="../../assets/images/defeat.png"
          />
        </div>
        <template v-if="inProgress == 1">
          <avatorGroup :group-info="detailInfo.groupBuyInfo || {}" />
          <group-desc-info
            :group-info="detailInfo.groupBuyInfo || {}"
            :timestemp="groupTimestemp"
            :show-button-group="showShareButton"
            @changeButtonVisible="changeButtonVisible"
          />
          <successInfo :group-info="detailInfo.groupBuyInfo || {}" />
          <cr-divider
            hairline
            :style="{
              borderColor: '#ECECEC'
            }"
          />
        </template>
        <rules :group-info="detailInfo.groupBuyInfo || {}" />
      </div>
      <span v-if="detailImgList.length" id="goodDetail" class="goods-divider">宝贝详情</span>
      <div class="goods-detail-imgs">
        <cr-image
          v-for="(item, index) in detailImgList"
          :key="index"
          lazy-load
          width=""
          height=""
          style="width: 100%; height: auto; display: block"
          :src="item"
        />
      </div>
    </div>
    <bottom-nav v-if="showButtonNav" :status="2" :disabled="false" @share="shareTo" />
  </div>
</template>
<script>
import goods from '@/api/groupBuy';
import bottomNav from './components/bottomNav';
import swipeCustomerInfo from '@/components/swipeCustomerInfo';
import avatorGroup from '@/components/avatorGroup';
import successInfo from '@/components/groupBuySuccessInfo';
import rules from '@/components/rules';
import groupDescInfo from './components/groupDescInfo';
import localStorage from '@/service/localStorage.service';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'goodDetail',
  components: {
    bottomNav,
    swipeCustomerInfo,
    avatorGroup,
    successInfo,
    rules,
    groupDescInfo
  },
  data() {
    return {
      timestemp: '', // 大活动结束时间
      groupTimestemp: '', // 小团结束时间
      showInfo: false,
      inProgress: false, // 活动是否已经开始
      countDownText: '',
      showShareButton: false, // 是否显示分享按钮
      stockPercentage: 0,
      // 以下是原有的data
      detailParam: {
        skuNo: '',
        receiverId: '',
        count: 1
      },
      detailInfo: {},
      imgList: [],
      detailImgList: [], // 商品详情图像展示
      hasLogin: false,
      name: {},
      showButtonNav: false // 是否显示底部按钮
    };
  },
  created() {
    this.hasLogin = window.localStorage.getItem('vccToken') != 'null' ? true : false;
    this.detailParam = { ...this.$route.query };
    localStorage.set('activityId', this.detailParam.templateId); // 设置活动模板id，用于下单
    if (this.detailParam.groupBuyGroupId) {
      localStorage.set('groupBuyGroupId', this.detailParam.groupBuyGroupId); // 设置groupBuyGroupId，用于下单
      this.groupId = +this.detailParam.groupBuyGroupId;
    } else {
      localStorage.remove('groupBuyGroupId');
      this.groupId = 0;
    }
    this.name = this.$route.params;
    this.imgList = [this.name.goodsimg];
    this.init(this.detailParam);
  },
  mounted() {
    // todo 曝光埋点
    setTimeout(() => {
      this.showInfo = true;
    }, 3000);
    setTimeout(() => {
      this.showInfo = false;
    }, 5000);
  },
  methods: {
    shareTo() {
      // 分享
    },
    changeButtonVisible(res) {
      this.showButtonNav = res;
    },
    // ka渠道逻辑
    goVccOrDetail() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
    },
    async init(detailParam) {
      const [res] = await goods.detailInfo(detailParam);
      if (res.groupBuyInfo.groupId) {
        localStorage.set('groupBuyGroupId', res.groupBuyInfo.groupId || ''); // 设置groupBuyGroupId，用于下单
        this.groupId = +res.groupBuyInfo.groupId || '';
      }
      if (res.saleCount && res.activitySkuTotalCount) {
        const percentage = +res.saleCount / +res.activitySkuTotalCount;
        if (isNaN(percentage)) {
          this.stockPercentage = 0;
        } else {
          this.stockPercentage = Math.floor(percentage) >= 1 ? 100 : Math.floor(percentage * 100);
        }
        console.log(this.stockPercentage);
      }
      this.showShareButton = res.groupBuyInfo.groupBuyStatus == 1 ? true : false;
      this.imgList = res.imageUrl || [];
      this.detailInfo = res;
      this.setStartStatus(res);
      try {
        const detailImages = await goods.getDetailPic(this.detailInfo.contentDetailUrl);
        // const imgReg = new RegExp('(?<=src=").[^"]*', 'g');
        // this.detailImgList = (detailImages || '').match(imgReg);
        let imgReg = /<img.*?(?:>|\/>)/gi;
        // eslint-disable-next-line no-useless-escape
        let srcReg = /src=[\'"]?([^\'"]*)[\'"]?/i;
        let arr = (detailImages || '').match(imgReg);
        let srcArr = [];
        for (let i = 0; i < arr.length; i++) {
          let src = arr[i].match(srcReg)[1].replace('http://', 'https://');
          srcArr.push(src);
        }
        this.detailImgList = srcArr;
      } catch (error) {
        console.error(error);
      }
    },
    setStartStatus(data) {
      const currentTime = new Date(data.currentTime).getTime();
      const activityStartTime = new Date(data.startTime).getTime();
      const activityEndTime = new Date(data.endTime).getTime();
      this.groupTimestemp = data.groupBuyInfo.currentGroupEndTime
        ? new Date(data.groupBuyInfo.currentGroupEndTime).getTime()
        : -1;
      if (currentTime <= activityStartTime) {
        // 当前时间小于活动开始时间
        this.timestemp = activityStartTime;
        this.countDownText = '距活动开始时间';
        this.inProgress = -1;
        return;
      }
      if (currentTime >= activityEndTime) {
        this.timestemp = 0;
        this.countDownText = '活动已结束';
        this.inProgress = 0;
        return;
      }
      if (currentTime > activityStartTime && currentTime < activityEndTime) {
        this.timestemp = activityEndTime;
        this.countDownText = '距成团结束';
        this.inProgress = 1;
        return;
      }
    }
  }
};
</script>
<style lang="less" src="./smallPic.less" scoped></style>
