<template>
  <!-- 配置活动背景色 -->
  <div class="group" :style="{ backgroundColor: topicCfg.bgcolor }">
    <div v-if="!isShowShare" class="group-puzzle" @click="goToMyorder">我的拼团</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" :avatar="customers.src" :name="customers.name" />
          </div>
          <div class="group-portrait-ul">
            <groupSwiper
              v-if="topicCfg.groupBuyUserInfoList"
              :avator-data="topicCfg.groupBuyUserInfoList"
              @animation-event-start="animationEventStart"
              @animation-event-end="animationEventEnd"
            />
          </div>
        </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">{{ topicCfg.stateTxt }}：</span>
            <count-down :end-time="gpCountDown" />
          </div>
        </div>
        <cr-list
          v-if="!reload"
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <goods-card
            v-for="(item, index) in goodsList"
            :key="index"
            :index="index"
            :goods-item="item"
            :topic-cfg="topicCfg"
            @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>
  </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 { isNull } from '@/service/validation.service';
import { handleRemainTime, handleDateFormat } from './components/utils';
import localStorage from '@/service/localStorage.service';
import goodsCheckMixin from '@/mixins/goodsCheck.mixin';
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,

      avatorData: [],

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

      showSwipe: false,
      customers: {},
      // goodsSpecialId	是

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

      topicIndex: 0,
      topicList: {},

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

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

    gpCountDown() {
      const { endTime } = this.topicCfg;
      // if (hasStart) {
      //   return +new Date(endTime || 0);
      // } else {

      // };
      // if (){}

      return +new Date(endTime || 0);
    }
  },
  created() {
    this.reload = true;
    // console.log(this.isShowShare);
    // console.log(this.activityId);
    // this.hasLogin = !!localStorage.get('vccToken');
  },
  mounted() {
    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: {
    animationEventStart() {
      this.showSwipe = false;
    },
    animationEventEnd(avator) {
      this.customers = avator;
      this.showSwipe = true;
    },

    async goToMyorder() {
      const isLogin = this.checkLogin();
      if (!isLogin) {
        this.$router.push('/createOrder');
      }
    },
    async openShareEvent() {
      let options = await this.getShareData();
      this.$store.dispatch('goods_share_open', options);
    },
    async getShareData() {
      return Promise.resolve({
        title: '随便砍砍就能拿，价格你来定',
        desc: '我正在免费拿商品，请你帮帮我',
        link: `${window.location.origin}/activity/zeroBuy`, // 页面地址
        imgUrl: 'https://appsync.lkbang.net/shareIcon.png' // 图片地
      });
      // await
    },
    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) {
      const { activityId } = this;
      const { goodsSpecialId, templateId, templateDetailIds } = this.topicCfg;
      const { skuNo } = item;
      if (item.goodsCount !== 0) {
        this.$router.push({
          path: '/groupBuy/skuInfo',
          query: { skuNo, goodsSpecialId, templateId, templateDetailIds, activityId }
        });
      } else {
        this.$notify({ type: 'warning', message: '该商品已抢完' });
      }
    },
    onLoad() {
      if (this.topicCfg) {
        this.getGoodsList();
      }
    },

    async getGoodsList() {
      const { pageSize, pageNo, activityId } = this;
      const { goodsSpecialIds, templateDetailIds } = this.topicCfg;
      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;
          res.items[5].goodsCount = 0;
          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 } = 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?.t) {
    let t = result.t;
    t.startTime = '2021-09-15 00:00:00';
    t.endTime = '2021-09-22 00:00:00';
    // t.startTime = '2021-09-15 00:00:00';
    // t.endTime = '2021-09-18 00:00:00';
    const { endTime, startTime } = t;
    t.remainTime = handleRemainTime('', endTime)[0];
    t.hasStop = t.remainTime < 1;
    t.willTime = handleRemainTime('', startTime)[0];
    t.hasStart = handleRemainTime(startTime, '')[0] > 0;
    t = { ...t, ...handleDateFormat(startTime, endTime) };
    t.stateTxt = !t.hasStart ? '即将开始' : t.hasStop ? '活动已结束' : '距结束';

    const { title } = t;
    store.commit('CHANGE_TITLE', title || '活动页');
    nextFns(vm => {
      vm.activityId = activityId;
      vm.topicList = t;
      // vm.topicIndex = activityIndex;
      localStorage.set('activityId', activityId);
      // 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>
