<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">超值0元购，正在拼团中</div>
        <div class="goods-group-buy-head-content-swipe">
          <swipe-customer-info
            v-model="avatorInfo.showInfo"
            :avatar="avatorInfo.src"
            :name="avatorInfo.name"
            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
            class="goods-product-info-img-img-box"
            width=""
            height=""
            :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">0</span>
            </div>
            <div class="goods-product-info-desc-price-market">
              售价¥{{ detailInfo.activityPrice }}
            </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>
        <avatorGroup :group-info="detailInfo.groupBuyInfo || {}" />
        <group-desc-info
          :group-info="detailInfo.groupBuyInfo || {}"
          :timestemp="groupTimestemp"
          :show-button-group="true"
          :sku-no="detailParam.skuNo"
          @changeButtonVisible="changeButtonVisible"
          @share="setShareData"
        />
        <successInfo :group-info="detailInfo.groupBuyInfo || {}" />
        <cr-divider
          hairline
          :style="{
            borderColor: '#ECECEC'
          }"
        />
        <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"
      :current-time="detailInfo.currentTime"
      :end-time="detailInfo.endTime"
      :info="detailInfo.groupBuyInfo || {}"
      :status="2"
      :disabled="false"
      @share="setShareData"
    />
  </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';
import { EventBus, firstGroupShare } from '@/service/utils.service';
// import sharePic from '@/components/sharePic';
import config from '@/config';
import { mapState } from 'vuex';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'goodDetail',
  components: {
    bottomNav,
    swipeCustomerInfo,
    avatorGroup,
    successInfo,
    rules,
    groupDescInfo
    // sharePic
  },
  data() {
    return {
      groupTimestemp: '', // 小团结束时间
      countDownText: '',
      stockPercentage: 0,
      shareInfo: {}, // 调用分享需要的参数
      picUrl: '', // 海报url
      // 以下是原有的data
      detailParam: {
        skuNo: '',
        receiverId: '',
        count: 1
      },
      customers: {},
      detailInfo: {},
      imgList: [],
      detailImgList: [], // 商品详情图像展示
      name: {},
      showButtonNav: false // 是否显示底部按钮
    };
  },
  computed: {
    ...mapState({
      avatorInfo: state => state.pay.avatorInfo
    })
  },
  created() {
    console.log(config.localHost);
    this.detailParam = { ...this.$route.query };
    localStorage.set('templateId', 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);
  },
  methods: {
    setShareData() {
      const avatorList = [];
      if (this.detailInfo?.groupBuyInfo?.groupBuyValidUserInfoList) {
        this.detailInfo.groupBuyInfo.groupBuyValidUserInfoList.map(v => {
          avatorList.push(v.avatar);
        });
      }
      const sharePicData = {
        groupBuySuccessGuys: this.detailInfo?.groupBuyInfo.groupBuySuccessPersonCount,
        salePrice: this.detailInfo.price, // y
        groupBuyGroupId: this.groupId,
        goodsSpecialId: this.detailParam.goodsSpecialId,
        openGroupCnt: this.detailInfo?.groupBuyInfo.groupBuyLimitUserCount,
        templateId: this.detailParam.templateId,
        templateDetailId: this.detailParam.templateDetailId,
        needGuys: this.detailInfo?.groupBuyInfo.groupBuyNeedUserCount,
        skuName: this.detailInfo.goodsName, // y
        activityId: this.detailParam.activityId,
        skuImg: this.detailInfo.thumbImageUrl, // y,
        activityPrice: this.detailInfo.activityPrice, // y
        skuNo: this.detailParam.skuNo,
        peoplePhotoList: avatorList,
        endTime: this.detailInfo?.groupBuyInfo.currentGroupEndTime || this.detailInfo?.endTime || ''
      };
      EventBus.$emit('goods_share_info', {
        shareInfo: sharePicData,
        type: 2
      });
    },
    changeButtonVisible(res) {
      this.showButtonNav = res;
    },
    async init(detailParam) {
      const [res] = await goods.detailInfo(detailParam);
      try {
        firstGroupShare(
          {
            ...this.$route.query,
            skuName: res.goodsName,
            skuImg: res.thumbImageUrl
          },
          2
        );
        if (res.groupBuyInfo.groupId) {
          // localStorage.set('groupBuyGroupId', res.groupBuyInfo.groupId || ''); // 设置groupBuyGroupId，用于下单
          this.groupId = +res.groupBuyInfo.groupId || '';
        }
        if (res.saleCount && res.activitySkuTotalCount) {
          const percentage =
            (+res.activitySkuTotalCount - +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.imgList = res.imageUrl || [];
        this.detailInfo = res;
        this.setStartStatus(res);
        this.detailInfo.contentDetailUrl = this.detailInfo.contentDetailUrl.replace(
          'http://',
          'https://'
        );
        const detailImages = await goods.getDetailPic(this.detailInfo.contentDetailUrl);
        console.log(detailImages);
        // 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 (e) {
        console.log(e);
      }
    },
    setStartStatus(data) {
      const currentTime = new Date(data.currentTime.replace(/\-/g, '/')).getTime();
      const activityStartTime = new Date(data.startTime.replace(/\-/g, '/')).getTime();
      const activityEndTime = new Date(data.endTime.replace(/\-/g, '/')).getTime();
      this.groupTimestemp = data.groupBuyInfo.currentGroupEndTime
        ? new Date(data.groupBuyInfo.currentGroupEndTime.replace(/\-/g, '/')).getTime()
        : -1;
      if (currentTime <= activityStartTime) {
        // 当前时间小于活动开始时间
        this.countDownText = '距活动开始时间';
        return;
      }
      if (currentTime >= activityEndTime) {
        this.countDownText = '活动已结束';
        return;
      }
      if (currentTime > activityStartTime && currentTime < activityEndTime) {
        this.countDownText = '距活动结束';
        return;
      }
    }
  }
};
</script>
<style lang="less" src="./smallPic.less" scoped></style>
