<template>
  <!-- 配置活动背景色 -->
  <div class="group" :style="{ backgroundColor: goodsTemp.bgcolor }">
    <!-- <cr-skeleton v-if="showLoading" class="loading" /> -->
    <div class="group-puzzle" @click="goToMyorder">我的拼团</div>
    <!-- 配置头部动态信息 start -->
    <div class="group-top">
      <!-- 动态活动背景图 -->
      <cr-image width="100%" height="100%" class="group-top-image" :src="goodsTemp.img" />
    </div>
    <!-- 配置头部动态信息 end -->

    <!-- 下方列表展示信息 start -->
    <div id="groupScroll" class="group-bottom" :class="{ padtop: isShowSwiper }">
      <div v-if="!isShowSwiper" class="group-portrait">
        <div class="group-portrait-head">
          <div class="group-portrait-swipe">
            <swipeCustomerInfo v-model="showSwipe" :avatar="customers.src" :name="customers.name" />
          </div>
          <div class="group-portrait-ul">
            <groupSwiper
              v-if="showLoops && goodsTemp.groupBuyUserInfoList.length"
              ref="swipeRota"
              :bg-color="goodsTemp.bgcolor"
              :avator-data="goodsTemp.groupBuyUserInfoList"
              @animation-event-start="animationEventStart"
              @animation-event-end="animationEventEnd"
            />
          </div>
        </div>
        <div class="group-portrait-num">
          已有 <b>{{ goodsTemp.groupBuyUserCount }}</b
          >人 参与拼团
        </div>
      </div>
      <div class="group-list">
        <div class="list-title">
          <b class="list-title-text">今日拼团</b>
          <div class="list-count">
            <span class="list-count-label">{{ goodsTemp.stateTxt }}：</span>
            <count-down :end-time="gpCountDown" @finish-time="finishTimeChange" />
          </div>
        </div>
        <cr-list
          v-if="!reload"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          :immediate-check="false"
          @load="onLoad"
        >
          <goods-card
            v-for="(item, index) in goodsList"
            :key="index"
            :index="index"
            :goods-item="item"
            :topic-cfg="goodsTemp"
            @on-button-click="handleBtnClick"
          />
        </cr-list>
      </div>
      <!-- 下方列表展示信息 end -->
    </div>
    <div class="group-share" @click="openShareEvent">&nbsp;</div>
  </div>
</template>
<script>
import store from '@/store';
import groupBuyApi from '@/api/groupBuy';
import countDown from '@/components/countDown';
import swipeCustomerInfo from '@/components/swipeCustomerInfo';
import goodsCard from './components/goodsCard';
import groupSwiper from '@/components/groupSwiper';
import { handleRemainTime, handleDateFormat } from './components/utils';
import localStorage from '@/service/localStorage.service';
import goodsCheckMixin from '@/mixins/goodsCheck.mixin';
import { setAppTitleColor, EventBus } from '@/service/utils.service';
import { saTrackEvent } from '@/service/sa.service';
// import { isNull } from '@/service/validation.service';
// let topicIndex;
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: 'groupBuyList',
  components: { countDown, swipeCustomerInfo, goodsCard, groupSwiper },
  mixins: [goodsCheckMixin],
  data() {
    return {
      showShare: false,

      showSwipe: false,
      showLoops: false,
      customers: {},

      showLoading: true,
      pageNo: 1, //	是
      pageSize: 10, //	否
      activityId: '', //是

      goodsTemp: {},

      goodsList: [],
      loading: false,
      finished: false
    };
  },
  computed: {
    isShowShare() {
      return this.$store.state.pay.isPrimordialBrowser;
    },

    isShowSwiper() {
      const { hasStart, hasStop } = this.goodsTemp;
      return (!hasStart && !hasStop) || (hasStart && hasStop);
    },
    gpCountDown() {
      const { startTime, endTime, hasStart, hasStop } = this.goodsTemp;
      if (!hasStart && !hasStop) {
        // 活动未开始
        return +new Date(startTime || 0);
      }
      return +new Date(endTime || 0);
    }
  },
  watch: {
    // $route(to) {
    //   if (to.name !== 'groupBuyList') {
    //     this.setTitleColor();
    //     return;
    //   }
    //   this.setTitleColor(this.goodsTemp.bgcolor);
    // }
  },
  created() {
    this.showLoops = true;
    this.reload = true;
  },
  beforeDestroy() {
    this.setTitleColor();
  },
  // deactivated() {
  //   this.showLoops = false;
  // },
  // activated() {
  //   this.showLoops = true;
  // },
  beforeRouteEnter(to, from, next) {
    const { activityId } = to.query;
    if (!activityId || isNaN(activityId)) {
      next({
        path: '/error',
        replace: true
      });
      return;
    } else {
      getActivityList(to.query, next);
      // if (isNull(topicIndex)) {
      //   getActivityList(to.query, next);
      // } else {
      //   if (localStorage.get('activityId') !== +activityId) {
      //     getActivityList(to.query, next);
      //     return;
      //   }
      //   next(vm => {
      //     store.commit('CHANGE_TITLE', vm.goodsTemp.title || '活动页');
      //   });
      // }
    }
  },
  methods: {
    animationEventStart() {
      this.showSwipe = false;
    },
    animationEventEnd(avator) {
      this.customers = avator;
      this.showSwipe = true;
    },
    async finishTimeChange() {
      const info = this.goodsTemp;
      this.goodsTemp = await computedTemplate(info);
    },
    async goToMyorder() {
      const hasLogin = localStorage.get('vccToken') ? true : false;
      if (!hasLogin) {
        this.checkLogin();
        return;
      }
      this.$router.push('/orderList/0');
    },
    async openShareEvent() {
      const shareInfo = await this.getShareData();
      EventBus.$emit('goods_share_info', {
        shareInfo,
        type: 0
      });
      saTrackEvent('H5_GroupZeroYuanPurchaseActivityPageSharePopupBtnClick', {
        activity_id: this.activityId
      });
    },
    async getShareData() {
      const {
        sharePosterTemplateUrl,
        shareTitle,
        shareSubTitle,
        shareIconUrl,
        img,
        title
      } = this.goodsTemp;
      const { activityId } = this;
      return Promise.resolve({
        skuName: shareTitle || title,
        desc: shareSubTitle,
        skuImg: shareIconUrl || img,
        posterUrl: sharePosterTemplateUrl,
        activityId
      });
    },
    setTitleColor(bgcolor = '#ffffff') {
      setAppTitleColor(bgcolor);
    },
    handleBtnClick(item) {
      const { activityId } = this;
      const { goodsSpecialId, templateId, templateDetailIds } = this.goodsTemp;
      const { skuNo } = item;
      if (item.goodsCount !== 0) {
        this.$router.push({
          path: '/groupBuy/skuInfo',
          query: {
            skuNo,
            goodsSpecialId,
            templateId,
            templateDetailIds,
            activityId,
            vccToken: localStorage.get('vccToken') || ''
          }
        });
      } else {
        this.$notify({ type: 'warning', message: '该商品已抢完' });
      }
    },
    onLoad() {
      if (this.goodsTemp) {
        this.getGoodsList();
      }
    },

    async getGoodsList(cover) {
      const { pageSize, pageNo, activityId } = this;
      const { goodsSpecialIds, templateDetailIds } = this.goodsTemp;
      this.loading = true;
      this.finished = false;
      try {
        const [res] = await groupBuyApi.getGoodsList({
          goodsSpecialIds,
          templateDetailIds,
          pageSize,
          pageNo,
          activityId
        });
        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++;
          }
          store.dispatch('change_group_loading', false);
        }
      } catch (error) {
        this.loading = false;
        this.finished = true;
        store.dispatch('change_group_loading', false);
      }
    }
  }
};
async function computedTemplate(info = {}) {
  if (!Object.keys(info).length) return info;
  info.endTime = info.endTime.replace(/-|\./g, '/');
  info.startTime = info.startTime.replace(/-|\./g, '/');
  const { endTime, startTime } = info;
  info.remainTime = handleRemainTime('', endTime)[0];
  info.hasStop = info.remainTime < 1;
  info.willTime = handleRemainTime('', startTime)[0];
  info.hasStart = handleRemainTime(startTime, '')[0] > 0;
  info = { ...info, ...handleDateFormat(startTime, endTime) };
  info.stateTxt = !info.hasStart ? '即将开始' : info.hasStop ? '活动已结束' : '距结束';
  return info;
}

async function getActivityList(urlQuery, next) {
  const { activityId } = urlQuery;
  // eslint-disable-next-line prettier/prettier
  let nextFns = function(cb) {
    cb(next);
  };
  if (typeof next === 'function') {
    nextFns = next;
  }
  store.dispatch('change_group_loading', true);
  const [result] = await groupBuyApi.getTemplateList(activityId);
  if (result?.templateInfo) {
    let t = result.templateInfo;
    // 即将开始
    // t.startTime = '2021-10-01 20:00:00';
    // t.endTime = '2021-10-02 20:02:00';
    // 正在活动中
    // t.startTime = '2021-09-30 00:00:00';
    // t.endTime = '2021-10-02 00:00:00';
    // // 活动已结束
    // t.startTime = '2021-09-23 10:45:00';
    // t.endTime = '2021-09-23 19:17:20';
    t = await computedTemplate(t);
    t.groupBuyUserInfoList = (t.groupBuyUserInfoList || []).reverse();
    // t.groupBuyUserInfoList = [
    //   {
    //     name: '皱眉',
    //     avatar:
    //       'https://img.lkbang.net/avator/0c8c1cfeb1cfdfffd77ac74af83377a17812a3585027-OKt5j9_fw658.jpeg'
    //   },
    //   {
    //     name: '空白人生',
    //     avatar:
    //       'https://img.lkbang.net/avator/e684de0d4db0fcd3a04945ff7ed394abb678ce577dba5-VJbncW_fw658.jpeg'
    //   },
    //   {
    //     name: '逅黄昏',
    //     avatar:
    //       'https://img.lkbang.net/avator/900b3be08740dbe4e38f7c3b7a73b613538a2f2edac3-yXzWfB_fw658.jpeg'
    //   },
    //   {
    //     name: '桑过后正年轻',
    //     avatar:
    //       'https://img.lkbang.net/avator/7ca48321827385f386d0317a40d3f6201f442fddf99a-xXvv37_fw658.jpeg'
    //   },
    //   {
    //     name: '年少就是不服输',
    //     avatar:
    //       'https://img.lkbang.net/avator/e33db7b617e42367d888e3821e1acd89b4b20319cb42-esiOS3_fw658.jpeg'
    //   }
    // ];
    store.commit('CHANGE_TITLE', t.title || '活动页');
    nextFns(vm => {
      // topicIndex = 0;
      vm.activityId = activityId;
      vm.goodsTemp = t;
      localStorage.set('activityId', activityId);
      vm.setTitleColor(t.bgcolor);
      vm.pageNo = 1;
      vm.getGoodsList(true);
      vm.reload = false;
    });
  } else {
    nextFns(vm => {
      vm.$toast({ type: 'danger', message: '当前活动不存在' });
    });
    return;
  }
}
</script>
<style lang="less" src="./index.less" scoped></style>
