<template>
<view>
<!--product/newbornZone/newbornZone.wxml-->
<view class="banner">
	<image src="/activity/static/activity/images/nbzbg.png" class="background"></image>
</view>
<view class="conunt" v-if="activityGroup.length > 0">
	<view v-for="(item, index) in activityGroup" :key="index" class="li" :data-index="index">
		<image :src="item.pic + '?x-oss-process=style/w210'" mode="aspectFit" class="proimg" :data-index="index" @tap="toGroupRemind" lazy-load="true"></image>
		<view class="flex">
			<view class="proname" :data-index="index" @tap="toGroupRemind">
				{{item.productName}}
			</view>
			<view class="progress-box" v-if="item.payQuantity">
				<progress stroke-width="8" color="red" :percent="item.num" border-radius="25rpx" backgroundColor="#FFB2B8" class="progress" v-if="item.payQuantity"></progress><text>已抢{{item.payQuantity}}</text>
			</view>
			<view class="progress-box" v-if="item.makePerson">
				<progress stroke-width="8" color="red" :percent="item.makePerson" border-radius="25rpx" backgroundColor="#FFB2B8" class="progress" v-if="item.makePerson"></progress><text>已{{item.makePerson}}人预约</text>
			</view>
			<view class="endtime" :data-index="index" @tap="toGroupRemind"><text class="black">{{item.start ? '距结束' : '距开始'}}</text><text class="red">{{item.times}}</text></view>
			<view :class="'operate dflex ' + (item.payQuantity?'noyuyue':'yuyue')" v-if="item.start">
				<view class="price proprice" :data-index="index" @tap="toGroupRemind">￥<text class="pce">{{item.money}}</text><text class="del">￥{{item.marketPrice}}</text></view>
				<view class="add-cart" :data-index="index" @tap="toGroupRemind">
					立即抢购
				</view>
			</view>
			<view :class="'operate dflex ' + (item.makePerson?'noyuyue':'yuyue')" v-else>
				<view class="price proprice" :data-index="index" @tap="toGroupRemind">￥<text class="pce">{{item.money}}</text><text class="del">￥{{item.marketPrice}}</text></view>
				<view :class="(item.isRemind?'add-cart1':'add-cart') + ' car'">
					<image src="/activity/static/activity/images/clock2.png" v-if="!item.isRemind"></image>
					<view class="order or" @tap="cancelActivityRemind" :data-index="index" :data-id="item.id" v-if="item.isRemind">取消预约</view>
					<view class="order" @tap="addActivityRemind" :data-index="index" :data-id="item.id" v-else>预约</view>
				</view>
			</view>
		</view>
	</view>
	<!-- <view class="nomore dflex">亲，没有更多了</view> -->
</view>
<view class="nodata nosp" v-if="ishow">
	<image :src="picUrlss+'empty_sp.png'"></image>
	<text >暂无商品</text>
</view>
</view>
</template>

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

export default {
  data() {
    return {
		picUrlss: req.public.picUrls,
      form: {
        page: 1,
        limit: 10,
        type: 4
      },
      page: 1,
      isLoad: true,
      newuser: true,
      activityGroup: [],
      query: "",
      ishow: false,
      user: false
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.query = options;
    this.setData({
      query: options
    }); // this.newuser()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.isLoad = true;
    this.form.page = 1; // this.data.activityGroup=[]

    this.setData({
      activityGroup: []
    });
    // console.log(this.activityGroup);
    this.loadGroup();
  },

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

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

  methods: {
    /**
     * 获取商品列表
     */
    loadGroup() {
      let isShowLoading = false;

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

      let _ts = this;

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

      if (this.query.merchantId) {
        from.merchantId = this.query.merchantId;
      } else if (req.getStorage('MERCHANT')) {
        from.merchantId = req.getStorage('MERCHANT').id;
      }

      req.getRequest('/api/activity/list', from, data => {
        if (data && data.length == 10) this.isLoad = true;
        data = data.map(it => {
          it.isRemind = it.remindId, it.num = it.payQuantity / it.quantity * 100;
          return it;
        });
        if (_ts.form.page > 1) data = _ts.activityGroup.concat(data);

        _ts.setData({
          activityGroup: data
        });

        // console.log(this.activityGroup);

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

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


        _ts.initGroupTimer();

        // console.log(this.activityGroup);
      });
    },

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

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

        for (let i = initPage, len = activityGroup.length; i < len; i++) {
          let group = activityGroup[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['activityGroup[' + i + '].end'] = true;
              clearInterval(timer);
            } else {
              let n = utils.formatDayTimes(times);
              data['activityGroup[' + i + '].times'] = n;
            }

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

          _ts.setData(fs);
        }
      }
    },

    /**
     * 
     * 点击li获取商品详情
     */
    toGroupRemind(event) {
      const index = event.currentTarget.dataset.index;
      // console.log(event);
      const activity = this.activityGroup[index];
      let merchantId;

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

      app.globalData.openPage(url); // console.log('acid', activity.id)
      // console.log('productId', activity.productId)
    },

    /**
     * 活动产品预约
     */
    addActivityRemind(event) {
      // if (!this.data.user) return req.msg('您不是新用户')
      const index = event.currentTarget.dataset.index;
      const id = event.currentTarget.dataset.id; // 订阅调用

      
      req.postRequest('/api/activity/remind', {
        activityId: id
      }, res => {
		  this.requsetmessage.remind();
        req.msg('预约成功');
        let data = {};
        data['activityGroup[' + index + '].isRemind'] = true;
        this.setData(data);
      });
    },

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

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

    /**
     * 判断是否为新用户，不是，2秒后为用户跳转至该商品的详情页面
     */
    newuserFun() {
      id = this.query.id;
      req.postRequest('/api/order/isnew', {}, res => {
        if (res == 'false') {
          this.setData({
            user: false
          });
          uni.showToast({
            title: '您不是新用户，两秒后将为您跳转至该商品页面',
            icon: 'none',
            success: function () {
              setTimeout(function () {
                uni.redirectTo({
                  url: '/product/detail/detail?id=' + id
                });
              }, 2000);
            }
          });
        }

        // console.log(res);
      });
    }

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