<template>
<view>
<!--product/list/list.wxml-->
<view class="ssbox bgfff">
	<view class="search dflex" @tap="search">
		<image src="/static/pages/images/ssico.png"></image>
		<view>搜索你想要的商品</view>
	</view>
</view>
<view class="filter dflex bgfff">
	<view v-for="(item, index) in tabList" :key="index" @tap="swtichTab" :data-index="index" :class="'li ' + (tabIndex == index ? 'active' : '')">{{item.name}}
		<block v-if="item.isSort">
			<image src="/static/pages/images/up.png" class="updown" v-if="item.isAsc == 2"></image>
			<image src="/static/pages/images/down.png" class="updown" v-else-if="item.isAsc == 1"></image>
			<image src="/static/pages/images/jiage.png" class="updown" v-else></image>
		</block>
	</view>
	<!-- <view class="li {{tabIndex == 0 ? 'active' : ''}}">默认</view>
	<view class="li">销量</view>
	<view class="li">价格
		<image src="/pages/images/down.png" class="updown"></image>
	</view> -->
	<!-- <view class="li">筛选</view> -->
</view>
<view class="shequ bgfff mt20">
	<view v-for="(item, index) in pageList" :key="index" class="li">
		<view class="dflex">
			<image :src="item.pic" mode="aspectFit" class="proimg" :data-index="index" @tap="toGroupRemind"></image>
			<view class="flex">
				<view class="proname" :data-index="index" @tap="toGroupRemind">{{item.productName}}</view>
				<view class="endtime" :data-index="index" @tap="toGroupRemind">{{item.start ? '距结束' : '距开始'}} {{item.times?item.times:''}}</view>
				<view class="operate dflex">
					<view class="price proprice">￥<text>{{item.money}}</text><text class="del" v-if="item.marketPrice!=0&&item.marketPrice>item.money">￥{{item.marketPrice}}</text></view>
					<view class="add-cart">
						<image src="/static/pages/images/jia.png" :data-index="index" @tap="toGroupRemind" v-if="item.start"></image>
						<block v-else>
							<view class="remind mbglinear" @tap="cancelActivityRemind" :data-index="index" v-if="item.isRemind">取消提醒</view>
							<view class="remind mbglinear" @tap="addActivityRemind" :data-index="index" v-else>开团提醒</view>
						</block>
					</view>
				</view>
			</view>
		</view>
		<view class="datas dflex" v-if="item.start" :data-index="index" @tap="toGroupRemind">
			<view class="yigou dflex">
				<image v-for="(item, index2) in item.dtoList" :key="index2" :src="item.avatar" mode="aspectFit"></image>
				<image src="/static/pages/images/more1.png" mode="aspectFit" class="more1" v-if="item.dtoList && item.dtoList.length > 0"></image>
				<text>已售{{item.payQuantity}}/剩余{{item.quantity - item.payQuantity}}</text>
			</view>
			<view class="xiaoliang">累计销量 {{item.sellStock}}</view>
		</view>
	</view>
</view>
<view class="nomore dflex" v-if="!ishow">亲，没有更多了</view>
<view class="nodata nosp" v-if="ishow">
		<image :src="picUrlss+'empty_sp.png'"></image>
		<text>暂无商品</text>
	</view>
</view>
</template>

<script>
const app = getApp();
const req = require("../../utils/request.js");
const utils = require("../../utils/util.js");
const requsetmessage = require("../../utils/requestmessage.js");

export default {
  data() {
    return {
		picUrlss: req.public.picUrls,
      form: {
        page: 1,
        limit: 10,
        type: 1
      },
      searchTitle: '',
      pageList: [],
      tabIndex: 0,
      tabList: [{
        name: '默认'
      }, {
        name: '销量'
      }, {
        name: '价格',
        isSort: true
      }],
      isLoad: true,
      ishow: false
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    // console.log(options);
    this.query = options; // this.loadCoupon();
  },

  onShow() {
    this.isLoad = true, this.form.page = 1;
    this.setData({
      pageList: []
    });
    this.loadCoupon();
  },

  onReachBottom() {
    this.form.page++;
    this.loadCoupon();
  },

  onUnload() {
    this.clearAllTimer();
  },

  onHide() {
    this.clearAllTimer();
  },

  methods: {
    search() {
      // app.openPage('pages/search/search?merchantId=' + this.data.merchant.id)
      if (req.getStorage('MERCHANT').id) {
        app.globalData.openPage('pages/search/search?searchTitle=' + this.searchTitle + '&merchantId=' + req.getStorage('MERCHANT').id);
      } else if (this.query.merchantId) {
        app.globalData.openPage('pages/search/search?searchTitle=' + this.searchTitle + '&merchantId=' + this.query.merchantId);
      }
    },

    swtichTab(event) {
      this.clearAllTimer();
      const index = event.currentTarget.dataset.index;
      const tab = this.tabList[index];
      let data = {
        pageList: [],
        tabIndex: index,
        form: {
          page: 1,
          type: 1,
          limit: 10
        },
        isLoad: true
      };

      if (index === 1) {
        data.form['stockSort'] = 1;
      } else if (index === 2) {
        data.form['moneySort'] = tab.isAsc ? tab.isAsc === 1 ? 2 : 1 : 2;
        data['tabList[' + index + '].isAsc'] = tab.isAsc ? tab.isAsc === 1 ? 2 : 1 : 2;
      }

      if (index !== 2) data['tabList[2].isAsc'] = null;
      this.setData(data);
      this.clearAllTimer();
      this.loadCoupon();
    },

    loadCoupon() {
      let isShowLoading = false;

      if (this.form.page == 1 && !isShowLoading) {
        req.loadIng('加载中');
        isShowLoading = true;
      }

      if (!this.isLoad) return false;
      this.isLoad = false;
      // console.log(this.isLoad);
      let that = this;
      let from = this.form;

      if (this.query.merchantId) {
        from.merchantId = this.query.merchantId;
        // console.log("456");
      } else if (req.getStorage('MERCHANT')) {
        from.merchantId = req.getStorage('MERCHANT').id;
        // console.log("123");
      }

      req.getRequest('/api/activity/list', from, data => {
        if (data && data.length == 10) this.isLoad = true;
        data = data.map(it => {
          it.isRemind = it.remindId;
          return it;
        });
        if (that.form.page > 1) data = that.pageList.concat(data);
        that.setData({
          pageList: data
        });

        if (this.pageList.length <= 0) {
          that.setData({
            ishow: true
          });
        } else {
          that.setData({
            ishow: false
          });
        }

        if (isShowLoading) {
          uni.hideLoading();
          isShowLoading = false;
        }

        // console.log(this.pageList);
        this.clearAllTimer();
        that.initGroupTimer();
      });
    },

    initGroupTimer() {
      //社区拼图定时器
      let _ts = this;

      if (this.pageList && this.pageList.length > 0) {
        let pageList = this.pageList;
        const initPage = (parseInt(this.form.page) - 1) * 10;

        for (let i = initPage, len = pageList.length; i < len; i++) {
          let group = pageList[i];
          let nowTime = new Date(group.nowTime.replace(/-/g, '/')).getTime();
          let startTime = new Date(group.startTime.replace(/-/g, '/')).getTime();
          let endTime = new Date(group.endTime.replace(/-/g, '/')).getTime();
          if (!group.start) endTime = startTime;
          let times = parseInt((endTime - nowTime) / 1000);
          let timer = setInterval(() => {
            times--;
            let data = {};

            if (times === 0) {
              //重新加载列表
              data['pageList[' + i + '].end'] = true;
              clearInterval(timer);
            } else {
              let n = utils.formatDayTimes(times);
              data['pageList[' + i + '].times'] = n;
            }

            _ts.setData(data);
          }, 1000);
          let fs = [];
          fs['pageList[' + i + '].timer'] = timer;

          _ts.setData(fs);
        }
      }
    },

    toGroupRemind(event) {
      const index = event.currentTarget.dataset.index;
      const activity = this.pageList[index];
      let merchantId;

      if (this.query.merchantId) {
        merchantId = this.query.merchantId;
      } else if (req.getStorage('MERCHANT')) {
        merchantId = req.getStorage('MERCHANT').id;
      }
	  let url ='product/groupDetail/groupDetail?acid=' + activity.id + "&id=" + activity.productId
	  if(!merchantId){
		  
	  }else{
		  url+="&merchantId=" + merchantId
	  }
      app.globalData.openPage(url);
    },

    clearAllTimer() {
      this.pageList.forEach(it => {
        clearInterval(it.timer);
        clearInterval(it.times);
      });
    },

    addActivityRemind(event) {
      const index = event.currentTarget.dataset.index;
      const page = this.pageList[index]; // 订阅调用

      
      req.postRequest('/api/activity/remind', {
        activityId: page.id
      }, res => {
		  requsetmessage.remind().then(res => res);
        req.msg('订阅提醒成功');
        let data = {};
        data['pageList[' + index + '].isRemind'] = true;
        this.setData(data);
      });
    },

    cancelActivityRemind(event) {
      const index = event.currentTarget.dataset.index;
      const page = this.pageList[index];
	  if(req.header.appId=='ZQ1VK5oc17I387E'){
	  		  
	  }else{
		req.postRequest('/api/activity/cancel/remind', {
		  id: page.id
		}, res => {
		  req.msg('取消提醒成功');
		  let data = {};
		  data['pageList[' + index + '].isRemind'] = false;
		  this.setData(data);
		});  
	  }
    }

  }
};
</script>
<style>
@import "./groupList.css";
</style>