<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 | 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">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"
      @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 Bridge from '@qg/js-bridge';
import MpBridge from '@/service/mp';
import { isWxMp, isApp } from '@/service/validation.service';
import { EventBus } from '@/service/utils.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: '', // 小团结束时间
      showInfo: false,
      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
    })
  },
  created() {
    this.hasLogin = localStorage.get('vccToken') ? true : false;
    this.detailParam = { ...this.$route.query };
    localStorage.remove('orderData');
    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.init(this.detailParam);
  },
  mounted() {
    // todo 曝光埋点
    setTimeout(() => {
      this.showInfo = true;
    }, 3000);
    setTimeout(() => {
      this.showInfo = false;
    }, 5000);
  },
  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.endTime || ''
      };
      EventBus.$emit('goods_share_info', {
        shareInfo: sharePicData,
        type: 2
      });
    },
    getToken() {
      window.xyqbNativeEvent = function(res) {
        const json = typeof res === 'string' ? JSON.parse(res) : res;
        if (json.event === 'getTokenSuccess') {
          const appData = json.data || {};
          if (appData && appData.token) {
            localStorage.set('vccToken', appData.token);
            window.location.reload();
          }
        }
      };
      this.nativeBridge.getToken();
    },
    checkLogin() {
      const vccToken = localStorage.get('vccToken');
      const needLogin = vccToken ? false : true;
      if (needLogin) {
        if (isApp) this.nativeBridge = new Bridge();
        else if (isWxMp) this.nativeBridge = new MpBridge();
        this.$dialog({
          message: '参与拼团活动需要您先进行登录哦~',
          title: '',
          showCancelButton: false,
          confirmButtonText: '登录',
          onConfirm: () => {
            if (isWxMp) {
              this.nativeBridge.getToken();
            } else if (isApp) {
              // native调用getToken
              this.getToken();
            } else {
              this.$dialog({
                message: '请在App或小程序中参与活动~',
                title: '',
                showCancelButton: false,
                confirmButtonText: '我知道了'
              });
            }
          }
        });
      }
    },
    onChange(index) {
      this.swiperCurrent = index;
    },
    // ka渠道逻辑
    goVccOrDetail(res) {
      if (!this.hasLogin) {
        this.checkLogin();
        return;
      }
      if (res == 1) {
        localStorage.remove('groupBuyGroupId'); // 开团或者自己做团长的时候需要移除groupBuyGroupId，再去调下单
      }
      this.toOrder();
    },
    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);
      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 {
        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.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() {
      if (!this.hasLogin) {
        this.checkLogin();
        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.checkLogin();
        return;
      }
      this.getAddr();
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
