<template>
  <div v-if="showPage" class="goods" style="height: 100%">
    <div class="goods-share-button" @click="setShareData">
      <cr-image
        src="@/assets/images/share-icon.png"
        width=""
        height=""
        class="goods-share-button-img"
      />
    </div>
    <!-- 主体 -->
    <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" 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="avatorInfo.showInfo"
            :avatar="avatorInfo.src"
            :name="avatorInfo.name"
          />
        </div>
      </div>
      <div class="goods-group-buy-info">
        <div class="goods-group-buy-info-price">
          <p class="price">
            成团价¥<span class="group-price">0</span>售价¥<span class="sale-price">{{
              detailInfo.activityPrice
            }}</span>
            <!-- :class="{ scaleFont: parseInt(detailInfo.activityPrice) < 10000 }" -->
          </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 :group-info="detailInfo.groupBuyInfo || {}" />
      </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="1"
            :max="1"
            disable-input
          />
          <div v-if="detailInfo.limitCount" class="goods-popup-num-limit">
            仅限购买1件
          </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"
      :group-id="groupId"
      :info="detailInfo.groupBuyInfo || {}"
      @buy="goVccOrDetail"
    />
  </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 localStorage from '@/service/localStorage.service';
import goodsCheckMixin from '@/mixins/goodsCheck.mixin';
import { EventBus } from '@/service/utils.service';
import { saTrackEvent } from '@/service/sa.service';
import { isApp, isWxMp } from '@/service/validation.service';
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'goodDetail',
  components: {
    goodsCell,
    bottomNav,
    swipeCustomerInfo,
    countDown,
    avatorGroup,
    successInfo,
    rules,
    groupDescInfo
  },
  filters: {
    Img2Thumb
  },
  mixins: [goodsCheckMixin],
  data() {
    return {
      timestemp: '', // 大活动结束时间
      groupTimestemp: '', // 小团结束时间
      inProgress: false, // 活动是否已经开始
      countDownText: '',
      showPage: false, // 是否显示页面，当查询完团与人的关系后进行处理，如果用户已经参与了此商品此活动的团，navigateto small else showpage = true
      groupId: 0, // 团id
      // 以下是原有的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,
      avatorInfo: state => state.pay.avatorInfo
    })
  },
  created() {
    this.hasLogin = localStorage.get('vccToken') ? true : false;
    this.detailParam = { ...this.$route.query };
    localStorage.remove('orderData');
    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.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,
        // groupBuyGroupId: this.groupId, // 分享出去不携带团id，故注释掉
        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,
        activityId: this.detailParam.activityId,
        skuImg: this.detailInfo.thumbImageUrl,
        activityPrice: this.detailInfo.activityPrice,
        skuNo: this.detailParam.skuNo,
        peoplePhotoList: [], // 原本是avatorList，如上方注释，因与产品确认过商品详情页分享出去不携带团id，故头像传递空数组即可
        endTime: this.detailInfo?.groupBuyInfo.currentGroupEndTime || this.detailInfo?.endTime || ''
      };
      EventBus.$emit('goods_share_info', {
        shareInfo: sharePicData,
        type: 2
      });
    },
    onChange(index) {
      this.swiperCurrent = index;
    },
    // ka渠道逻辑
    async goVccOrDetail(res) {
      if (!res) {
        this.currentPopupType = '';
        this.currentPopupName = '';
        return;
      }
      const buttonNameMap = {
        3: '立即参团',
        1: '立即开团',
        2: '自己做团长'
      };
      if (!this.hasLogin) {
        this.checkLogin();
        return;
      }
      const checkParams = {
        activityHundredGroupId: this.groupId || '',
        skuNo: this.detailParam.skuNo
      };
      if (res == 1 || res == 2) {
        delete checkParams.activityHundredGroupId;
      }
      const [checkStatus] = await goods.checkGroupBuyCreateOrder(checkParams);
      if (!checkStatus.verifyResult) {
        // 校验是否允许开团或者参团
        this.$dialog({
          message: checkStatus.failedReason || '',
          cancelButtonText: '知道了',
          showConfirmButton: false,
          cancelButtonColor: '#ec1500',
          closeOnClickOverlay: !isApp && !isWxMp ? false : true
          // confirmButtonText: '返回活动',
          // onConfirm: () => {
          //   this.$router.replace({
          //     path: '/groupBuy/list',
          //     query: {
          //       activityId: this.detailParam.activityId
          //     }
          //   });
          // }
        });
        return;
      }
      saTrackEvent('H5_GroupZeroYuanPurchaseActivityDetailPageBtnClick', {
        sku_no: this.detailInfo.skuNo,
        buttons_name: buttonNameMap[res]
      });
      this.toOrder(res);
    },
    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.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);
      // canJoinGroupBuyAgain  groupStatus
      try {
        if (res.groupBuyInfo?.groupId) {
          // localStorage.set('groupBuyGroupId', res.groupBuyInfo.groupId || ''); // 设置groupBuyGroupId，用于下单
          this.groupId = +res.groupBuyInfo.groupId || 0;
        }
        if (res.groupBuyInfo?.joinGroup) {
          // 如果当前用户参了团到拼团详情
          const query = { ...this.$route.query };
          return this.$router.replace({ name: 'groupBuySkuInfoSmallPic', query });
        }
        this.imgList = res.imageUrl || [];
        this.detailInfo = res;
        this.setStartStatus(res);
        this.showPage = true;
        try {
          this.detailInfo.contentDetailUrl = this.detailInfo.contentDetailUrl.replace(
            'http://',
            'https://'
          );
          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: '',
            closeOnClickOverlay: !isApp && !isWxMp ? false : true,
            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);
      } catch (e) {
        this.$toast('获取商品详情失败');
      }
    },
    async getAddr() {
      if (!this.hasLogin) {
        this.checkLogin();
        return;
      }
      const [addressInfo] = await goods.addrList();
      if (addressInfo) {
        this.addressList = (addressInfo && addressInfo.addrReceiverList) || [];
        this.show = true;
      } else {
        this.addAddress();
      }
    },
    addAddress() {
      if (!this.hasLogin) {
        this.checkLogin();
        return;
      }
      this.show = false;
      this.$router.push({ name: 'addressManage' });
    },
    toOrder(type) {
      if (!this.hasLogin) {
        this.checkLogin();
        return;
      }
      if (this.detailInfo.stock === 0) {
        this.$toast('库存不足！');
        return;
      }
      this.show = false;
      const order = {
        groupId: this.groupId || '', // 唐峰确认订单页加
        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');

      // const buttonNameMap = {
      //   3: '立即参团',
      //   1: '立即开团',
      //   2: '自己做团长'
      // };
      const query = {};
      localStorage.set('groupBuyGroupId', type == 3 ? this.groupId : '');
      this.$router.push({
        name: 'createOrder',
        query
      });
    },
    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;
      if (eventType == 'sku') {
        saTrackEvent(
          'H5_GroupZeroYuanPurchaseActivityDetailPageSpecificationSelectionPopupConfirmBtnClick',
          {
            sku_no: this.detailInfo.skuNo
          }
        );
      }
      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.checkLogin();
        return;
      }
      this.getAddr();
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
