<template>
  <div class="goods" style="height: 100%">
    <!-- 主体 -->
    <div class="goods-container">
      <!-- 轮播图 -->
      <div class="goods-carousel">
        <cr-swipe class="goods-swiper" @change="onChange">
          <cr-swipe-item v-for="(item, index) in imgList" :key="index" class="goods-carousel-item">
            <img :src="item | Img2Thumb" style="width: 100%" />
          </cr-swipe-item>
          <template #indicator>
            <div class="custom-indicator">{{ swiperCurrent + 1 }}/{{ imgList.length }}</div>
          </template>
        </cr-swipe>
        <div class="goods-swipe-avator">
          <swipe-customer-info v-model="showInfo" />
        </div>
      </div>
      <div class="goods-group-buy-info">
        <div class="goods-group-buy-info-price">
          <p class="price">
            成团价¥<span class="group-price">{{ detailInfo.activityPrice }}</span
            >售价¥<span class="sale-price">{{ detailInfo.price }}</span>
          </p>
          <p class="desc">拼团成功/失败，款项原路返回至账户</p>
        </div>
        <div class="goods-group-buy-info-time">
          <p class="goods-group-buy-info-time-desc">{{ countDownText }}</p>
          <count-down v-if="!!timestemp" :end-time="timestemp" />
        </div>
      </div>
      <!-- 商品名称/价格 -->
      <div class="goods-info">
        <div class="goods-info-name">{{ detailInfo.goodsName }}</div>
      </div>

      <div v-if="inProgress == 1" class="goods-param">
        <!-- 商品已选 -->
        <goods-cell title="已选" @click.native="handleParamsClick('sku', '')">
          <span class="goods-param-text">
            <span v-for="(item, index) in specSelected" :key="index">{{ item.attsValue }}</span>
          </span>
          <span v-if="specSelected.length">； &nbsp;</span>
          <span>{{ selectedGoods.skuNum }}件</span>
        </goods-cell>
        <!-- 收货地址 -->
        <goods-cell
          class="goods-param-area"
          title="送至"
          @click.native="handleParamsClick('area', '配送至')"
        >
          <span
            class="iconfont icon-location-line"
            :class="{ noAddr: !selectedAddress.addrFullName }"
          />
          <span>{{ selectedAddress.addrFullName || '添加收货地址' }}</span>
        </goods-cell>
      </div>
      <div class="goods-group-info">
        <!-- {{ detailInfo.groupBuyInfo }} -->
        <template v-if="inProgress == 1">
          <avatorGroup :group-info="detailInfo.groupBuyInfo || {}" />
          <group-desc-info
            :group-info="detailInfo.groupBuyInfo || {}"
            :timestemp="groupTimestemp"
          />
          <successInfo :group-info="detailInfo.groupBuyInfo || {}" />
          <cr-divider
            hairline
            :style="{
              borderColor: '#ECECEC'
            }"
          />
        </template>
        <rules />
      </div>
      <span v-if="detailImgList.length" id="goodDetail" class="goods-divider">宝贝详情</span>
      <!-- <div v-if="skuDetailList.length" class="goods-detail">
        <detail-info-area :sku-detail-list="skuDetailList" :sku-detail-atts="skuDetailAtts" />
      </div> -->
      <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>
    <cr-popup v-model="show" class="popup-head" closeable position="bottom">
      <div class="popup-title">{{ currentPopupName }}</div>
      <div v-if="currentPopupType === 'sku'" class="goods-popup">
        <div class="goods-popup-selected">
          <img :src="detailInfo.thumbImageUrl" />
          <div class="Gp-selected-right">
            <div class="Gps-right-header">
              <div class="Gpsr-header-price">
                <span>¥</span>
                <span>{{ detailInfo.price }}</span>
              </div>
              <div v-if="detailInfo.marketPrice" class="Gpsr-header-discount">
                <span>原价：</span>
                <span>¥{{ detailInfo.marketPrice }}</span>
              </div>
            </div>
            <div v-if="specSelected.length" class="Gps-right-selected">
              已选：
              <span v-for="(sItem, sIndex) in specSelected" :key="sIndex">
                {{ sItem.attsValue }}
              </span>
            </div>
          </div>
        </div>
        <div v-for="(item, index) in specList" :key="index" class="goods-popup-param">
          <span class="Gp-param-name">{{ item.attsName }}</span>
          <div class="Gp-param-list">
            <span
              v-for="(childItem, childIndex) in specChildList"
              v-show="childItem.attsCode === item.attsCode"
              :key="childIndex"
              :disabled="childItem.disabled"
              :class="{
                'Gpp-list-selected': childItem.isSelected && !childItem.disabled,
                'Gpp-list-disabled': childItem.disabled
              }"
              @click="selectSpec(childIndex, childItem)"
            >
              {{ childItem.attsValue }}
            </span>
          </div>
        </div>
        <div class="goods-popup-num">
          <span class="Gp-num-name">购买数量：</span>
          <cr-stepper
            v-model="selectedGoods.skuNum"
            class="Gp-num-step"
            :min="minCount"
            :max="detailInfo.limitCount"
            disable-input
          />
          <div v-if="detailInfo.limitCount" class="goods-popup-num-limit">
            仅限购买{{ detailInfo.limitCount }}件
          </div>
        </div>
        <div class="goods-area-button">
          <button class="goods-bottom-buy" @click="goVccOrDetail">确认</button>
        </div>
      </div>
      <div v-if="currentPopupType === 'area'" class="goods-area">
        <div v-if="addressList && addressList.length">
          <div
            v-for="(item, index) in addressList"
            :key="index"
            class="goods-area-item "
            :class="{
              'goods-area-item_selected': item.addrReceiverId === selectedAddress.addrReceiverId
            }"
            @click="changeAddress(item)"
          >
            <span class="iconfont icon-location-line" />
            <span class="secondText">{{ item.addrFullName }}</span>
          </div>
        </div>
        <span v-else class="goods-area-none">暂未添加地址哦～</span>
        <div class="goods-area-button" @click="addAddress">
          <button class="goods-bottom-buy btn-absolute">添加新地址</button>
        </div>
      </div>
    </cr-popup>
    <bottom-nav
      v-if="!isPrimordialBrowser && !isWeixinBrowser && inProgress == 1"
      type="shoppingCar"
      :disabled="false"
      @buy="goVccOrDetail"
    />
    <sharePic ref="sharePic" />
  </div>
</template>
<script>
import goods from '@/api/groupBuy';
import goodsCell from './components/goodsCell';
import Img2Thumb from '@/filters/img2Thumb.filter';
import bottomNav from './components/bottomNav';
import swipeCustomerInfo from '@/components/swipeCustomerInfo';
import countDown from '@/components/countDown';
import avatorGroup from '@/components/avatorGroup';
import successInfo from '@/components/groupBuySuccessInfo';
import rules from '@/components/rules';
import groupDescInfo from './components/groupDescInfo';
import { mapState } from 'vuex';
import sharePic from '@/components/sharePic';
import localStorage from '@/service/localStorage.service';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'goodDetail',
  components: {
    goodsCell,
    bottomNav,
    swipeCustomerInfo,
    countDown,
    avatorGroup,
    successInfo,
    rules,
    groupDescInfo,
    sharePic
  },
  filters: {
    Img2Thumb
  },
  data() {
    return {
      timestemp: '', // 大活动结束时间
      groupTimestemp: '', // 小团结束时间
      showInfo: false,
      inProgress: false, // 活动是否已经开始
      countDownText: '',
      // 以下是原有的data
      detailParam: {
        skuNo: '',
        receiverId: '',
        count: 1
      },
      specSelected: [],
      detailInfo: {},
      imgList: [],
      detailImgList: [], // 商品详情图像展示
      selectedGoods: {
        skuNum: 1,
        skuId: ''
      },
      addressList: [],
      selectedAddress: {},
      specList: [],
      specChildList: [],
      swiperCurrent: 0,
      // showBackBtn: navBarLeftBtns，
      currentPopupType: '',
      currentPopupName: '',
      show: false,
      hasLogin: false,
      name: {}
    };
  },
  computed: {
    minCount() {
      return this.detailInfo.stock ? 1 : 0;
    },
    ...mapState({
      isPrimordialBrowser: state => state.pay.showMiniappGuide,
      isWeixinBrowser: state => state.pay.isWeixinBrowser
    })
  },
  created() {
    this.hasLogin = localStorage.get('vccToken') != 'null' ? true : false;
    this.detailParam = { ...this.$route.query };
    localStorage.set('activityId', this.detailParam.templateId); // 设置活动模板id，用于下单
    this.name = this.$route.params;
    this.init(this.detailParam);
  },
  mounted() {
    // todo 曝光埋点
    setTimeout(() => {
      this.showInfo = true;
    }, 3000);
    setTimeout(() => {
      this.showInfo = false;
    }, 5000);
  },
  methods: {
    onChange(index) {
      this.swiperCurrent = index;
    },
    // ka渠道逻辑
    goVccOrDetail() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
      this.toOrder();
    },
    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.currentGroupEndTime
        ? new Date(data.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;
      }
    },
    async init(detailParam) {
      const [res] = await goods.detailInfo(detailParam);
      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);
      }

      this.selectedGoods.skuId = this.detailInfo.skuNo;
      if (res.activitySkuTotalCount === 0) {
        this.detailInfo.limitCount = 1;
        this.detailInfo.activityLimitCount = 0;
        this.$dialog({
          message: '哎呀，活动太火爆，该商品已经卖光，换一个商品试试吧！',
          title: '',
          showCancelButton: false,
          confirmButtonText: '查看其他商品',
          onConfirm: () => {
            this.$router.push({ name: 'groupBuyList' });
          }
        });
      }
      this.selectedAddress = res.receiverInfo || {};
      this.specList = res.skuAtts || [];
      let li = [];
      this.specList.forEach(item => {
        item.attsValues.forEach(i => {
          i.attsCode = item.attsCode;
          if (i.isSelected) {
            this.specSelected.push(i);
          }
        });
        li = li.concat(item.attsValues);
      });
      this.specChildList = li;
      // // 收货地址
      // this.getAddr();
      //选择的商品规格
      this.getSelectedSkuNo(this.specSelected);
    },
    async getAddr() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
      const [addressInfo] = await goods.addrList();
      if (addressInfo) {
        this.addressList = (addressInfo && addressInfo.addrReceiverList) || [];
        this.show = true;
      } else {
        this.addAddress();
      }
    },
    addAddress() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
      this.show = false;
      this.$router.push({ name: 'addressManage' });
    },
    toOrder() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
      if (this.detailInfo.stock === 0) {
        this.$toast('库存不足！');
        return;
      }
      this.show = false;
      const order = {
        activityInfoId: this.detailParam.activityId,
        activityTemplateId: this.detailParam.templateId,
        activityTemplateDetailId: this.detailParam.templateDetailId,
        addrReceiverId: this.selectedAddress.addrReceiverId || '',
        selectedSku: {
          skuNo: this.selectedGoods.skuId,
          skuNum: this.selectedGoods.skuNum,
          skuSource: this.detailInfo.skuSource
        }
      };
      localStorage.set('orderData', order);
      localStorage.remove('addressList');
      this.$router.push({ name: 'createOrder' });
    },
    changeAddress(address) {
      // 选取规格需要清空，init会重新赋值
      this.specSelected = [];
      const detailParam = { ...this.$route.query };
      this.detailParam = {
        count: this.selectedGoods.skuNum,
        skuNo: this.selectedGoods.skuId,
        receiverId: address.addrReceiverId,
        ...detailParam
      };
      this.show = false;
      console.log(this.detailParam);
      this.init(this.detailParam);
    },
    // 选择商品规格
    getSelectedSkuNo(specSelected) {
      if (!specSelected || !specSelected.length) {
        this.selectedGoods.skuId = this.detailInfo.skuNo;
        return;
      }
      let list = JSON.parse(JSON.stringify(specSelected));
      const skuNoList = [];
      list.map(item => {
        skuNoList.push(item.skuNos);
      });
      let baseList = skuNoList.shift();
      let finalList = baseList;
      baseList.forEach(item => {
        const index = finalList.indexOf(item);

        skuNoList.forEach(i => {
          if (i.indexOf(item) === -1) {
            finalList.splice(index, 1);
          }
        });
      });
      this.selectedGoods.skuId = finalList.pop();
    },
    //选择规格
    selectSpec(index, sku) {
      if (sku.isSelected || sku.disabled) {
        return;
      }
      let list = this.specChildList;
      list.forEach(item => {
        this.$set(item, 'disabled', true);
        if (item.attsCode === sku.attsCode) {
          this.$set(item, 'isSelected', false);
        }
        item.skuNos.forEach(i => {
          if (sku.skuNos.indexOf(i) !== -1 || item.attsCode === sku.attsCode) {
            this.$set(item, 'disabled', false);
          }
        });
        if (item.disabled) {
          item.isSelected = false;
        }
      });
      this.$set(list[index], 'isSelected', true);
      this.specSelected = [];
      list.forEach(item => {
        if (item.isSelected === true) {
          this.specSelected.push(item);
        }
      });
      this.getSelectedSkuNo(this.specSelected);
    },
    swiperChange(e) {
      this.swiperCurrent = e.detail.current;
    },
    handleParamsClick(eventType, name) {
      if (this.isPrimordialBrowser) return;
      this.currentPopupType = eventType;
      this.currentPopupName = name;
      switch (eventType) {
        case 'sku':
          this.skuPopup();
          break;
        case 'area':
          this.areaPopup();
          break;
        default:
          break;
      }
    },
    skuPopup() {
      if (this.detailInfo.stock === 0) {
        this.$toast('库存不足！');
        return;
      }
      this.show = true;
    },
    areaPopup() {
      if (!this.hasLogin) {
        this.$router.push({ name: 'login' });
        return;
      }
      this.getAddr();
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
