<template>
  <!-- 配置活动背景色 -->
  <div class="group" :style="{ backgroundColor: goodsTemp.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="goodsTemp.img" />
    </div>
    <!-- 配置头部动态信息 end -->

    <!-- 下方列表展示信息 start -->
    <div 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"
              ref="swipeRota"
              :avator-data="goodsTemp.groupBuyUserInfoList"
              @animation-event-start="animationEventStart"
              @animation-event-end="animationEventEnd"
            />
          </div>
        </div>
        <div class="group-portrait-num" @click="showSwipe = !showSwipe">
          已有 {{ goodsTemp.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">{{ 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>
      <div v-if="showLoading" class="loading">
        <cr-skeleton title :row="5" />
        <cr-skeleton title :row="5" />
        <cr-skeleton title :row="5" />
        <cr-skeleton title :row="5" />
      </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 { 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 { registeredEvents } from '@/service/sa.service';
console.log(EventBus);
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);
    }
  },
  created() {
    this.reload = true;
    // console.log(this.isShowShare);
    // console.log(this.activityId);
    // this.hasLogin = !!localStorage.get('vccToken');
  },
  mounted() {
    this.showLoading = true;
  },
  beforeRouteEnter(to, from, next) {
    const { activityId } = to.query;
    if (!activityId || isNaN(activityId)) {
      next({
        path: '/error',
        replace: true
      });
      return;
    } else {
      getActivityList(to.query, next);
    }
  },
  deactivated() {
    clearTimeout((this.$refs.swipeRota && this.$refs.swipeRota.timer) || null);
    this.showLoops = false;
    // EventBus.$off();
  },
  activated() {
    this.showLoops = true;
    this.$nextTick(() => {
      this.$refs.swipeRota && this.$refs.swipeRota.onSlidePrevChange();
    });
    this.onShareEventChange();
    // this.setTitleColor(this.goodsTemp.bgcolor);
    // store.commit('changeTitle', this.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 isLogin = this.checkLogin();
      if (!isLogin) {
        this.$router.push('/orderList/0');
      }
    },
    async openShareEvent() {
      const activity_id = this.activityId;
      this.$store.dispatch('goods_share_open');
      registeredEvents('H5_GroupZeroYuanPurchaseActivityPageSharePopupBtnClick', {
        activity_id
      });
    },
    onShareEventChange() {
      EventBus.$on('shareClickItem', async function({ ev, nativeBridge }) {
        let shareDic = await this.getShareData();
        if (ev === 'pic') {
          // 分享海报跳转小程序海报分享页面
          nativeBridge.openNewUrl({
            newUrl: `/pages/goodshare/index?url=${encodeURIComponent(
              JSON.stringify(shareDic.posterUrl)
            )}`
          });
        }
        if (ev === 'weixin') {
          // 分享朋友派发微信postMessage事件
          nativeBridge.run({
            event: 'showShareView',
            data: {
              shareDic
            }
          });
        }
      });
    },

    async getShareData() {
      const { sharePosterTemplateUrl, shareTitle, shareSubTitle, shareIconUrl } = this.goodsTemp;
      const link = window.location.href;
      return Promise.resolve({
        title: shareTitle,
        desc: shareSubTitle,
        link: `pages/webview/webview?url=${link}/`, // 页面地址
        imgUrl: shareIconUrl, // 图片地
        posterUrl: sharePosterTemplateUrl
      });
    },
    setTitleColor(bgcolor = '#fff') {
      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 }
        });
      } else {
        this.$notify({ type: 'warning', message: '该商品已抢完' });
      }
    },
    onLoad() {
      if (this.goodsTemp) {
        this.getGoodsList();
      }
    },

    async getGoodsList() {
      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 = res.items || [];
          if (!res.hasNext) {
            this.finished = true;
          } else {
            this.pageNo++;
          }
        }
      } catch (error) {
        this.loading = false;
        this.finished = true;
      }
    }
  }
};
async function computedTemplate(info) {
  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;
  }
  const [result] = await groupBuyApi.getTemplateList(activityId);
  if (result?.templateInfo) {
    let t = result.templateInfo;
    // 即将开始
    t.startTime = '2021-09-23 20:00:00';
    t.endTime = '2021-09-23 20:02:00';
    // 正在活动中
    // t.startTime = '2021-09-23 00:00:00';
    // t.endTime = '2021-09-25 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();
    store.commit('CHANGE_TITLE', t.title || '活动页');
    nextFns(vm => {
      vm.activityId = activityId;
      vm.goodsTemp = t;
      localStorage.set('activityId', activityId);
      vm.getGoodsList();
      vm.reload = false;
    });
  } else {
    nextFns(vm => {
      vm.$toast({ type: 'danger', message: '当前活动不存在' });
    });
    return;
  }
}
</script>
<style lang="less" src="./index.less" scoped></style>
