<template>
  <div
    class="container"
    :style="{
      backgroundImage: `url(${topicCfg.img})`
    }"
  >
    <div v-if="pageLoading" class="container--loading">
      <cr-loading size="18px">加载中...</cr-loading>
    </div>
    <template v-else-if="topicList && topicList.length">
      <div class="rules" @click="rules">规则</div>
      <div
        class="sticky"
        :style="{
          backgroundImage: `url(${topicCfg.img})`
        }"
      >
        <div class="seckill-title">
          <template v-if="topicList.length">
            <div
              ref="tabsScroll"
              :class="{
                'scene-over-4': topicList.length >= 5,
                'scene-less-4': topicList.length < 5
              }"
            >
              <div
                v-for="(item, index) in topicList"
                :key="`scene-2-${index}`"
                ref="tabs"
                class="scene-item"
                :class="{
                  selected: topicIndex == index
                }"
                @click="setTopicIndex($event, index)"
              >
                <div class="scene-name">
                  {{ item.dateFormat }}
                </div>
                <div class="scene-desc">
                  {{ item.stateTxt }}
                </div>
              </div>
            </div>
          </template>
        </div>
        <div v-if="topicList[topicIndex]" class="timers">
          <span v-if="topicList[topicIndex].hasStart" class="desc">距结束</span>
          <span v-else class="desc">距开始</span>
          <span v-if="timerDesc.day" class="day">{{ timerDesc.day }}天</span>
          <span class="hours">{{ timerDesc.hours }}</span
          >时<span class="mins">{{ timerDesc.mins }}</span
          >分 <span class="secs">{{ timerDesc.secs }}</span
          >秒
        </div>
      </div>
      <div v-if="goodsList.length" class="good-list">
        <cr-list
          v-if="!reload"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :immediate-check="false"
          offset="10"
          @load="handleListLoad"
        >
          <div
            v-for="(item, index) in goodsList"
            :key="index"
            class="good-item"
            @click="toDetail(item)"
          >
            <div class="good-img">
              <img :src="item.thumbImageUrl || item.imageUrl" alt="" />
              <div v-if="item.goodsCount == 0" class="soldout">
                <img src="https://img.lkbang.net/sold-out.1aa2bb3c.png" alt="" />
              </div>
            </div>
            <div class="good-info">
              <div class="top-part">
                <div class="title">
                  {{ item.goodsName }}
                </div>
                <div class="point">{{ item.sellPoint || '' }}</div>
              </div>
              <div class="bottom-part">
                <div class="info">
                  <div class="price">
                    <div class="price-content">
                      <span class="unit">¥</span>
                      <span v-if="item.activityPrice" class="int">{{
                        item.activityPrice.toString().split('.')[0]
                      }}</span>
                      <template
                        v-if="item.activityPrice && item.activityPrice.toString().split('.')[1]"
                      >
                        <span class="int">.</span>
                        <span class="float">{{ item.activityPrice.toString().split('.')[1] }}</span>
                      </template>
                    </div>

                    <div class="tags" :class="{ outTime: !topicCfg.hasStart }">
                      <template v-if="parseFloat(sub(item.presentPrice, item.activityPrice)) > 0"
                        >直降 ¥{{ sub(item.presentPrice, item.activityPrice) }}</template
                      >
                      <template v-else>秒杀</template>
                      <img src="https://img.lkbang.net/low_price.21ccedd.png" class="icon" alt="" />
                    </div>
                  </div>
                  <div class="stock">
                    <cr-progress
                      class="good-list_progress"
                      stroke-width="5"
                      color="#E82424"
                      track-color="#ECECEC"
                      :show-pivot="false"
                      :percentage="handleProgressByStatus(item)"
                    />
                    <span v-if="topicCfg.hasStart">
                      <template v-if="item.saleCount != item.activitySkuTotalCount">
                        已抢{{ item.saleCount }}件
                      </template>
                      <template v-else>
                        已售罄
                      </template>
                    </span>
                    <span v-else>未开始</span>
                  </div>
                </div>
                <div class="shopcart" @click.stop="addToShopcart(item.skuNo)" />
              </div>
            </div>
          </div>
        </cr-list>
      </div>
    </template>
    <cr-empty v-else :image="empyImg" image-size="4rem" description="没有找到相关活动~" />
    <ShareOverlay v-if="isApp" :activity-id="activityId.toString()" />
    <back-top />
  </div>
</template>
<script>
// import GiftPopup from "../modules/GiftPopup";
import BackTop from '@/components/toTop.vue';
import { spike } from '@/api/activity';
import { goodAdd } from '@/api/shopCart.api';
import { isNull, appVersion } from '@/service/validation.service';
import { isColor, setAppTitleColor } from '@/service/color.service';
import empyImg from '@/assets/images/electronicInvoice/empy.png';
import { handleRemainTimeForSeckillV2, handleDateFormatForSeckillV2 } from './components/utils';
import { sub, compareVersion } from '@/service/utils.service';
import Bridge from '@qg/js-bridge';
import Cookies from '@/service/cookieStorage.service';
import localStorage from '@/service/localStorage.service';
import ShareOverlay from '@/components/ShareOverlay.vue';

let topicIndex;
function checkApp(query) {
  const { vccChannel } = query;
  const h5VccChannel = localStorage.get('vccChannel');
  return !!vccChannel || !h5VccChannel;
}

export default {
  components: {
    BackTop,
    ShareOverlay
  },
  data() {
    return {
      showLoading: true,
      topicList: [],
      activityId: '',
      topicIndex: 0,
      goodsList: [],
      pageSize: 20,
      pageNo: 1,
      finished: false,
      loading: false,
      reload: false,
      isApp: false,
      pageLoading: true,
      empyImg,
      tabChangeTimer: null,
      timerDesc: {
        day: '',
        hours: '',
        mins: '',
        secs: ''
      },
      timer: null,
      currentTime: 0
    };
  },
  computed: {
    topicCfg() {
      const { topicList, topicIndex } = this;
      const info = topicList[topicIndex] || { items: [] };
      if (!isColor(info.bgcolor)) info.bgcolor = '#ffffff';
      return info;
    },
    topicState() {
      let _state = 0;
      const { hasStart, hasStop } = this.topicCfg;
      if (!hasStart) {
        _state = 1;
      } else if (hasStop) {
        _state = 2;
      } else {
        _state = 0;
      }
      return _state;
    }
  },
  beforeRouteEnter(to, from, next) {
    // if (;topicIndex) {
    //   next();
    // }
    const { activityId } = to.query;
    const isApp = checkApp(to.query);
    if (!activityId || isNaN(activityId)) {
      next({
        path: '/error',
        replace: true
      });
      return;
    } else {
      if (isNull(topicIndex)) {
        getActivityList(to.query, next, isApp);
      } else {
        next();
      }
    }
  },
  created() {
    this.isApp = checkApp(this.$route.query);
  },
  mounted() {
    setAppTitleColor(['#ff5d42', '#fe3d31']);
  },
  methods: {
    sub,
    toDetail(sku) {
      // 去秒杀商品详情页，要判断客户端版本，低于8.8.80, 走H5秒杀页
      const { skuNo } = sku;
      const { templateDetailId, templateId } = this.topicCfg;
      const { activityId } = this;
      if (this.isApp && compareVersion(appVersion, '8.8.80') > -1) {
        const nativeBridge = new Bridge();
        nativeBridge.openNewUrl({
          data: {
            newUrl: `xyqb://homepage/goodsdetail?skuNo=${skuNo}`
          }
        });
        return;
      }
      this.$router.push({
        path: '/goodDetail',
        query: { skuNo, templateId, templateDetailId, activityId }
      });
    },
    async addToShopcart(skuNo) {
      const [res] = await spike.getSkuInfo({
        skus: [skuNo]
      });
      let skus = res.skus;
      const goods = skus[0] || null;
      if (!goods) return;
      if (goods.status === 2) {
        this.$toast('商品已下架');
        return;
      }
      if (goods.status === 1) {
        this.$toast('来晚了已经卖完了~');
        return;
      }
      try {
        await this.getTokenFromApp();
        const { skuNo, skuSource } = goods;
        const params = [{ skuId: skuNo, skuNum: 1, skuSource, type: 1 }];
        const [res] = await goodAdd({
          shopCartBaseList: params,
          selected: true
        });
        if (res) {
          this.$toast.success('添加成功');
          if (this.isApp) {
            const nativeBridge = new Bridge();
            nativeBridge.run({
              event: 'shopCarAddGoodsNotification',
              data: {
                count: res.count
              }
            });
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    getTokenFromApp() {
      return new Promise((resolve, reject) => {
        if (Cookies.get('vccToken')) {
          resolve(Cookies.get('vccToken'));
          return;
        }
        if (this.isApp) {
          this.getTokenFromNative(resolve, reject);
        } else {
          const token = localStorage.get('vccToken');
          token ? resolve(token) : reject();
        }
      });
    },
    getTokenFromNative(resolve = () => {}, reject = () => {}) {
      const nativeBridge = new Bridge();
      window.xyqbNativeEvent = function(res) {
        const json = typeof res === 'string' ? JSON.parse(res) : res;
        console.log(json, 'res');
        if (json.event === 'getTokenSuccess' || json.event === 'loginAndLogoutNotification') {
          const appData = json.data || {};
          if (appData && appData.token) {
            Cookies.set('vccToken', appData.token);
            resolve(appData.token);
          } else {
            reject();
          }
        } else {
          reject();
        }
      };
      nativeBridge.getToken();
    },
    setTopicIndex(e, index) {
      this.topicIndex = index;
      this.goodsList = [];
      this.pageNo = 1;
      this.posiTab();
      this.getGoodsList(true);
    },
    rules() {
      window.location.href = 'https://page.q-gp.com/miao-sha-huo-dong-gui-ze-shuo-ming/';
    },
    async getGoodsList(cover) {
      const { pageSize, pageNo, activityId } = this;
      const { goodsSpecialId, templateDetailId } = this.topicCfg;
      console.log('this.topicCfg :>> ', this.topicCfg);
      this.loading = true;
      this.finished = false;
      try {
        const config = {};
        if (this.isApp) {
          config.useAppTerminal = true;
          config.headers = {
            'x-user-terminal': 'ios'
          };
        }
        const [res] = await spike.goodslist(
          {
            goodsSpecialId,
            pageSize,
            pageNo,
            activityId,
            templateDetailId
          },
          config
        );
        if (res.size) {
          this.loading = false;
          this.showLoading = false;
          this.goodsList = cover ? res.items : [...this.goodsList, ...res.items] || [];
          if (!res.hasNext) {
            this.finished = true;
          } else {
            this.pageNo++;
          }
          this.setTimer();
        }
      } catch (error) {
        // 2021-10-04 测试回归百人团时候发现秒杀活动时间到之后进行不下去，因为此判断模版数据list为空
        this.showLoading = false;
        this.loading = false;
        this.finished = true;
      }
    },
    handleListLoad() {
      this.getGoodsList();
    },
    handleProgressByStatus(item) {
      if (!item.saleCount) return 0;
      if (!item) return 0;
      let percentage = 0;
      const { saleCount, activitySkuTotalCount } = item;
      percentage = (saleCount / activitySkuTotalCount) * 100;
      percentage = percentage < 0 ? 0 : percentage;
      percentage = !this.topicCfg.hasStart ? 0 : percentage;
      return Math.round(percentage * 100) / 100;
    },
    posiTab() {
      /**
       * 1)先让选中的元素滚到可视区域的最左边 scrollLeft
       * 2)接着向右移动容器一半的距离 containWidth / 2
       * 3)最后向左移动item一半的距离 offsetWidth / 2
       */
      if (!this.$refs.tabsScroll || !this.$refs.tabs) return;
      let left = this.$refs.tabsScroll.scrollLeft;
      const nextSpace = 7; //每次移动距离
      let scrollItemTimer = setInterval(() => {
        this.$nextTick(() => {
          let offsetWidth = this.$refs.tabs[this.topicIndex].offsetWidth; //item
          let scrollLeft = this.$refs.tabs[this.topicIndex].offsetLeft; //选中的元素滚到可视区域的最左边
          const containWidth = this.$refs.tabsScroll.offsetWidth; //容器的宽度
          let resultSpot = scrollLeft + offsetWidth / 2 - containWidth / 2; //最终要停留的点
          if (Math.abs(left - resultSpot) < nextSpace) {
            clearInterval(scrollItemTimer);
          }
          if (resultSpot >= left) {
            left = left + nextSpace;
          } else {
            left = left - nextSpace;
          }
          // this.$refs.tabsScroll.scrollTo(lastSpot, 0);
          this.$refs.tabsScroll.scrollTo({
            left: left,
            top: 0,
            behavior: 'smooth'
          });
        });
      }, 5);
    },
    setTimer() {
      const { hasStart, startTime, endTime } = this.topicCfg;
      const targetTime = hasStart
        ? new Date(endTime.replace(/-|\./g, '/')).getTime()
        : new Date(startTime.replace(/-|\./g, '/')).getTime();
      if (this.timer) clearInterval(this.timer);
      this.calcTime(targetTime);
      this.timer = setInterval(() => {
        this.currentTime += 1000;
        this.calcTime.bind(this)(targetTime);
      }, 1000);
    },
    calcTime(targetTime) {
      this.currentTime = new Date().getTime();
      const surplus = targetTime - this.currentTime;
      if (surplus <= 0)
        return (this.timerDesc = {
          day: '',
          hours: '',
          mins: '',
          secs: ''
        });
      let day = parseInt(surplus / (1000 * 60 * 60 * 24));
      let hours = parseInt((surplus % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = parseInt((surplus % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = parseInt((surplus % (1000 * 60)) / 1000);
      this.timerDesc = {
        day,
        hours: hours < 10 ? '0' + hours : hours,
        mins: minutes < 10 ? '0' + minutes : minutes,
        secs: seconds < 10 ? '0' + seconds : seconds
      };
    }
  }
};
async function getActivityList(urlQuery, next, isApp) {
  const { activityId } = urlQuery;
  const nextFns =
    typeof next === 'function'
      ? next
      : function(cb) {
          cb(next);
        };
  const config = {};
  if (isApp) {
    config.useAppTerminal = true;
    config.headers = {
      'x-user-terminal': 'ios'
    };
  }
  const [res] = await spike.activityList(activityId, config);
  if (res && res.list && res.list.length) {
    console.log('res.list :>> ', res.list);
    const list = res.list
      .map(i => {
        const { endTime, startTime } = i;
        i.remainTime = handleRemainTimeForSeckillV2('', endTime)[0];
        i.hasStop = i.remainTime < 1;
        i.willTime = handleRemainTimeForSeckillV2('', startTime)[0];
        i.hasStart = handleRemainTimeForSeckillV2(startTime, '')[0] > 0;
        i = { ...i, ...handleDateFormatForSeckillV2(startTime, endTime) };
        i.stateTxt = '';
        // !i.hasStart ? "即将开始" : i.hasStop ? "已结束" : "热卖中";
        if (!i.hasStart) {
          if (new Date(startTime.replace(/-|\./g, '/')).getDate() == new Date().getDate()) {
            i.stateTxt = '即将开始';
          } else {
            i.stateTxt = '明天开始';
          }
        } else {
          if (i.hasStop) {
            i.stateTxt = '已结束';
          } else {
            i.stateTxt = '热卖中';
          }
        }
        return i;
      })
      .filter(i => !i.hasStop);

    const currentTime = new Date().getTime();
    let activityIndex = 0;
    const dataMap = {};
    const timesArr = [];
    list.map((item, index) => {
      // const dataMap = {};
      if (!item.hasStop) {
        const sub = currentTime - new Date(item.startTime.replace(/-|\./g, '/')).getTime();
        if (sub > 0) {
          dataMap[sub] = index;
          timesArr.push(sub);
        }
      }
    });
    if (Object.keys(dataMap).length && timesArr.length) {
      const min = Math.min(...timesArr);
      activityIndex = dataMap[min];
    }
    activityIndex = activityIndex > -1 ? activityIndex : 0;
    console.log('list :>> ', list);
    nextFns(vm => {
      vm.pageLoading = false;
      vm.activityId = activityId;
      vm.topicList = list;
      vm.topicIndex = activityIndex;

      vm.$nextTick(() => {
        vm.posiTab();
      });
      vm.getGoodsList(true);
      vm.reload = false;
    });
  } else {
    nextFns(vm => {
      vm.pageLoading = false;
      vm.$toast({ type: 'danger', message: '当前活动不存在' });
    });
    return;
  }
}
</script>
<style lang="less" src="./index.less" scoped></style>
