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

    <!-- 下方列表展示信息 start -->
    <div class="group-bottom">
      <div class="group-portrait">
        <div class="group-portrait-head">
          <div class="group-portrait-swipe" @click="switchAnimation">
            <swipeCustomerInfo v-model="showSwipe" />
          </div>
          <div class="group-portrait-ul">
            <groupSwiper v-if="avatorData.length" :avator-data="avatorData" />
          </div>
          <!-- <ul class="group-portrait-ul" :class="animate">
            <li
              v-for="(imgItem, imgIndex) in gpImagePathArray"
              :key="imgIndex"
              class="group-portrait-image"
            >
              <cr-image :src="imgItem" />
            </li>
          </ul> -->
        </div>
        <div class="group-portrait-num" @click="showSwipe = !showSwipe">
          已有 {{ topicCfg.groupBuyUserCount }}人 参与拼单
        </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">距结束：</span>
            <count-down :end-time="gpCountDown" />
          </div>
        </div>
        <cr-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <goods-card
            v-for="(item, index) in goodsList"
            :key="index"
            :index="index"
            :goods-item="item"
            @on-button-click="handleBtnClick"
          />
        </cr-list>
      </div>
      <!-- 下方列表展示信息 end -->
    </div>
    <dl v-if="!isShowShare" class="group-share" @click="openShareEvent">
      <dt class="group-share-icon">
        <cr-image src="@/assets/images/share.png" />
      </dt>
      <dd class="group-share-text">分享</dd>
    </dl>
    <goods-share ref="gdShare" />
  </div>
</template>
<script>
import { mapState } from 'vuex';
import store from '@/store';
import groupBuyApi from '@/api/groupBuy';
import goodsShare from '@/components/groupShare';
import countDown from '@/components/countDown';
import swipeCustomerInfo from '@/components/swipeCustomerInfo';
import gpImagePath from '@/assets/images/groupBuy/bg-top.png';
import goodsCard from './components/goodsCard';
import groupSwiper from '@/components/groupSwiper';
import { isNull } from '@/service/validation.service';
import { handleRemainTime, handleDateFormat } from './components/utils';
import localStorage from '@/service/localStorage.service';
let topicIndex;
export default {
  // beforeRouteEnter(to, from, next) {
  //   next(vm => {});
  // },
  // eslint-disable-next-line vue/name-property-casing
  name: 'groupBuyList',
  components: { countDown, swipeCustomerInfo, goodsCard, groupSwiper, goodsShare },
  data() {
    return {
      showShare: false,

      avatorData: [],

      animate: {
        animateAuto: false,
        transition: true,
        blue: true,
        green: false,
        animation: false
      },

      showSwipe: false,
      gpImagePath,
      gpBackColor: '#FA494E',
      gpImagePathArray: [
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_01.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_02.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_03.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_04.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_05.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_06.png',
        'https://activitystatic.lkbang.net/mall-free-ui/img/avator_07.png'
      ],

      // goodsSpecialId	是

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

      topicIndex: 0,
      topicList: [],

      goodsList: [],
      loading: false,
      finished: false
    };
  },
  computed: {
    ...mapState({
      isPrimordialBrowser: state => state.pay.isPrimordialBrowser,
      isWeixinBrowser: state => state.pay.isWeixinBrowser
    }),
    isShowShare() {
      return this.isPrimordialBrowser || this.isWeixinBrowser;
    },

    // 更具goodsSpecialId 获取查询活动模板列表-对应数据项
    topicCfg() {
      const { topicList, topicIndex } = this;
      const info = topicList[topicIndex] || { items: [] };
      return info;
    },

    gpCountDown() {
      const { endTime } = this.topicCfg;
      return +new Date(endTime);
    }
  },
  created() {
    console.log(this.isShowShare);
    this.hasLogin = !!localStorage.get('vccToken');
  },
  mounted() {
    // todo 曝光埋点
    this.$nextTick(() => {
      // this.avatorTimeSyncChange();
      this.getAvatorList();
    });
  },
  beforeRouteEnter(to, from, next) {
    // if (;topicIndex) {
    //   next();
    // }

    const { activityId } = to.query;
    if (!activityId || isNaN(activityId)) {
      next({
        path: '/error',
        replace: true
      });
      return;
    } else {
      if (isNull(topicIndex)) {
        getActivityList(to.query, next);
      } else {
        next();
      }
    }
  },
  methods: {
    openShareEvent() {
      this.$refs.gdShare.open();
    },
    avatorTimeSyncChange() {
      setInterval(() => {
        this.showSwipe = false;
        this.getAvatorList();
        // clearTimeout(timer);
      }, 3000);
    },
    showSwipeSync(avatorData) {
      let timer = setTimeout(() => {
        this.avatorData = avatorData;
        this.showSwipe = true;
        clearTimeout(timer);
      }, 1000);
    },
    async getAvatorList() {
      try {
        const [data] = await groupBuyApi.getGroupAvator();
        this.showSwipeSync(data);
      } catch (err) {
        console.log(err);
      }
    },
    switchAnimation() {
      this.animate.animateAuto = !this.animate.animateAuto;
    },
    handleBtnClick(item) {
      console.log(item.skuNo);
      // skuNo /groupBuy/skuInfo
      // this.$router.push(`/groupBuy/skuInfo?skuNo=${item.skuNo}`);
      this.$router.push(`/groupBuy/skuInfoSmallPic?skuNo=${item.skuNo}`);
    },
    onLoad() {
      if (this.topicCfg.goodsSpecialId) {
        this.getGoodsList();
      }
    },

    async getGoodsList() {
      const { pageSize, pageNo, activityId } = this;
      const { goodsSpecialId, templateDetailId } = this.topicCfg;
      this.loading = true;
      this.finished = false;
      try {
        const [res] = await groupBuyApi.getGoodsList({
          goodsSpecialId,
          templateDetailId,
          pageSize,
          pageNo,
          activityId
        });
        if (res.size) {
          this.loading = false;
          this.showLoading = false;
          this.goodsList = res.items || [];
          if (!res.hasNext) {
            this.finished = true;
          } else {
            this.pageNo++;
          }
        }
      } catch (error) {
        this.loading = false;
        this.finished = true;
      }
    }
  }
};
async function getActivityList(urlQuery, next) {
  const { activityId, goodsSpecialId } = urlQuery;
  // eslint-disable-next-line prettier/prettier
  let nextFns = function(cb) {
    cb(next);
  };
  if (typeof next === 'function') {
    nextFns = next;
  }
  const [result] = await groupBuyApi.getTemplateList(activityId);
  if (result && result.length) {
    const list = result.map(i => {
      const { endTime, startTime } = i;
      i.remainTime = handleRemainTime('', endTime)[0];
      // i.hasStop = i.remainTime < 1;
      i.hasStop = 0 < 1;
      i.willTime = handleRemainTime('', startTime)[0];
      i.hasStart = handleRemainTime(startTime, '')[0] > 0;
      i = { ...i, ...handleDateFormat(startTime, endTime) };
      i.stateTxt = !i.hasStart ? '即将开始' : i.hasStop ? '已结束' : '热购中';
      return i;
    });
    // .filter(i => !i.hasStop);
    let activityIndex = list.findIndex(item => {
      if (goodsSpecialId) {
        return item.goodsSpecialId == goodsSpecialId;
      } else {
        return item.hasStart;
      }
    });
    activityIndex = activityIndex > -1 ? activityIndex : 0;
    const { title } = list[activityIndex] || { items: [] };
    store.commit('CHANGE_TITLE', title || '活动页');
    nextFns(vm => {
      vm.activityId = activityId;
      vm.topicList = list;
      vm.topicIndex = activityIndex;
      // const { hasStop } = vm.topicCfg;
      // if (hasStop || !list.length) {
      //   vm.showOverTip = true;
      // }
      // vm.getGoodsList();
      vm.reload = false;
    });
  } else {
    nextFns(vm => {
      vm.$toast({ type: 'danger', message: '当前活动不存在' });
    });
    return;
  }
}
</script>
<style lang="less" src="./index.less" scoped></style>
