<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="true"
            @changeButtonVisible="changeButtonVisible"
            @share="setShareData"
          />
          <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" />
    <sharePic ref="sharePic" :share-pic-data="sharePicData" @outputPicUrl="outputPicUrl" />
  </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 sharePic from '@/components/sharePic';
import config from '@/config';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'goodDetail',
  components: {
    bottomNav,
    swipeCustomerInfo,
    avatorGroup,
    successInfo,
    rules,
    groupDescInfo,
    sharePic
  },
  data() {
    return {
      timestemp: '', // 大活动结束时间
      groupTimestemp: '', // 小团结束时间
      showInfo: false,
      inProgress: false, // 活动是否已经开始
      countDownText: '',
      stockPercentage: 0,
      sharePicData: {}, // 生成海报图所需要的链接
      shareInfo: {}, // 调用分享需要的参数
      picUrl: '', // 海报url
      // 以下是原有的data
      detailParam: {
        skuNo: '',
        receiverId: '',
        count: 1
      },
      detailInfo: {},
      imgList: [],
      detailImgList: [], // 商品详情图像展示
      name: {},
      showButtonNav: false // 是否显示底部按钮
    };
  },
  computed: {
    goodsShareInfo() {
      return this.$store.state.pay.goodsShareInfo;
    }
  },
  watch: {
    goodsShareInfo: {
      immediate: false,
      handler(val) {
        this.onShareEventChange(val);
      }
    }
  },
  created() {
    console.log(config.localHost);
    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: {
    async onShareEventChange({ ev, nativeBridge }) {
      if (ev === 'pic') {
        // 处理图片url
        nativeBridge.openNewUrl({
          newUrl: `/pages/goodshare/index?url=${encodeURIComponent(JSON.stringify(this.picUrl))}`
        });
        this.$store.dispatch('goods_share_close');
      }
      if (ev === 'weixin') {
        nativeBridge.run({
          event: 'showShareView',
          data: this.shareInfo
        });
      }
    },
    outputPicUrl(res) {
      const fullPath = this.$route.fullPath.replace('skuInfoSmallPic?', 'skuInfo?');
      const link =
        fullPath.indexOf('groupBuyGroupId=') > -1
          ? fullPath
          : fullPath + `&groupBuyGroupId=${this.groupId}`;
      this.picUrl = res || '';
      this.shareInfo = {
        title: this.detailInfo.goodsName,
        desc: '',
        link: link || '', // 页面地址
        imgUrl: this.detailInfo.thumbImageUrl, // 图片地
        posterUrl: res || ''
      };
      this.$store.dispatch('goods_share_open', this.shareInfo);
    },
    setShareData() {
      const avatorList = [];
      this.detailInfo.groupBuyInfo.groupBuyValidUserInfoList.map(v => {
        avatorList.push(v.avatar);
      });
      this.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
      };
      this.$refs.sharePic.createAndUploadPic();
    },
    changeButtonVisible(res) {
      this.showButtonNav = res;
    },
    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.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.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).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>
