<template>
	<!--product/seckill/seckill.wxml-->
	<view class="seckill">
		<view class="top">
			<image src="/activity/static/activity/images/seckillbg.png" class="background"></image>
			<view class=" tab">
				<image src="/activity/static/activity/images/seckill.png" class="logo"></image>
				<view class="times dflex">
					<view v-for="(item, index) in TabList" :key="index"
						:class="'li ' + (item.active ? 'active' : '') + ' left'" :data-index="index" @tap="switchTab">
						<text :class="item.active ? 'weight' : ''">{{item.label}}</text>
						<view :class="'state ' + (item.active? 'bg' :'')">{{item.state}}</view>
					</view>
				</view>
			</view>
		</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'" lazy-load="true" 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="progress-box" v-if="item.payQuantity&&item.start">
						<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&&!item.start">
						<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" v-if="item.start"><text
							class="black">{{item.start ? '距结束' : '距开始'}}</text><text class="red">{{item.times}}</text>
					</view>
					<view class="endtime" :data-index="index" @tap="toGroupRemind" v-else>
						<text class="date">{{item.date}}</text>
						<text class="hour">{{item.hour}}</text>
						<text class="date">开始</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"
								v-if="item.marketPrice!=0&&item.money<item.marketPrice">￥{{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>
		<view class="nodata" v-if="ishow">
			<image :src="picUrlss+'empty_sp.png'"></image>
			<text>暂无商品</text>
		</view>
	</view>
</template>

<script>
	// product/seckill/seckill.js
	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,
				TabList: [{
					label: '今天',
					active: true,
					state: "抢购中",
					dayType: 1,
					time: ''
				}, {
					label: '明天',
					state: "预热中",
					active: false,
					time: '',
					dayType: 2
				}, {
					label: '后天',
					state: "预热中",
					dayType: 3,
					time: ''
				}, {
					label: '',
					state: "预热中",
					dayType: 4,
					active: false,
					time: ''
				}, {
					label: '',
					state: "预热中",
					dayType: 5,
					active: false,
					time: ''
				}],
				form: {
					page: 1,
					limit: 10,
					type: 2,
					dayType: 1
				},
				isRemind: false,
				page: 1,
				isLoad: true,
				dayType: '',
				activityGroup: [],
				ishow: false,
				activityGroupAll: "",
				hasmore: ""
			};
		},

		components: {},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			// this.loadGroupAll();
			this.query = options;
			// this.getTime();//给tab添加动态时间
			this.initTab();//初始化tab时间
			this.loadGroupAll(); // this.setData({TabList[3].label:})
			// this.laterDay(4)[2]
		},
		onReady: function() {},

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

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() { // this.clearAllTimer();
			// let def = this.data.TabList.findIndex(it => it.active);
			// let d={}
			// d[`TabList[${def}].active`] = false;
			// this.setData(d);
		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() { // this.clearAllTimer();
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			// this.setData({})
			this.form.page++;

			this.loadGroupAll(1); // this.clearAllTimer();
			// console.log(this.form.page)
		},


		methods: {
			fun_data(aa){
				var date1 = new Date(),
				time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
				var date2 = new Date(date1);
				date2.setDate(date1.getDate()+aa);
				// var time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
				var time2 = (date2.getMonth()+1)+"月"+date2.getDate() + "日";
				return time2;
			},
			// 初始化tab导航
			initTab(){
				let tabList = this.TabList;
				tabList[3].label = this.fun_data(4);
				tabList[4].label = this.fun_data(5);
			},
			/**
			 * 
			 * 设置tab导航
			 */
			switchTab(event) {
				let index = event.currentTarget.dataset.index;
				let def = this.TabList.findIndex(it => it.active);
				let d = {};
				// console.log(index, def);
				d[`TabList[${def}].active`] = false;
				d[`TabList[${index}].active`] = true;
				// console.log(d);
				this.isLoad = true;
				this.form.page = 1;
				d['pageList'] = [];
				this.form.dayType = this.TabList[index].dayType;
				this.setData(d);
				this.loadGroupAll(1);
				this.clearAllTimer(); // this.getDate()
			},
			/**
			 * 获取所有产品列表
			 */
			loadGroupAll(type) {
				// console.log(this.isLoad)
				let isShowLoading = false;

				if (this.form.page == 1 && !isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				}
				if (!this.isLoad) return false;
				this.isLoad = false;
				let _ts = this;
				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, res => {
					if (res && res.length == 10) _ts.isLoad = true;
					if (from.page > 1) res = _ts.activityGroup.concat(res);
					let data = res;
					// var data = res.map(it => {
					// 	var allTime = this.getDate(it.startTime);
					// 	it.isRemind = it.remindId, it.num = it.sellStock / it.quantity * 100, it.date =
					// 		allTime.date, it.hour =
					// 		allTime.date1, it.year = new Date(allTime.date2).getTime();
					// 	return it;
					// });
					// console.log(data, _ts.isLoad);
					console.log(data.length)
					if (data.length <= 0) {
						_ts.ishow =  true;
						// return false;
					}else{
						_ts.ishow =  false;
					}
					console.log(isShowLoading)
					this.activityGroup = data;
					// if (type == 1) {
					// 	_ts.setData({
					// 		activityGroup: data,
					// 		hasmore: res && res.length > 0
					// 	});
					// } else {
					// 	data.sort(function(a, b) {
					// 		return Date.parse(a.startTime) - Date.parse(b.startTime);
					// 	});

					// 	/**
					// 	 * 商品日期排序
					// 	 */

					// 	var arr = [];
					// 	var allTime = {}
					// 	for (var i = 0; i < data.length; i++) {
					// 		if (data[i].end != true && data[i].start == true) {
					// 			allTime = this.getDate(data[i].nowTime);
					// 		} else {
					// 			allTime = this.getDate(data[i].startTime);
					// 		}

					// 		arr.push(allTime.date2);
					// 	}

					// 	/**
					// 	 * 数组去重
					// 	 */


					// 	let temp = [...new Set(arr)];
					// 	/**
					// 	 * 判断日期
					// 	 */

					// 	let tabList = [];
					// 	let list = this.TabList;
					// 	// console.log(list, tabList);

					// 	for (let i = 0; i < list.length; i++) {
					// 		tabList.push(list[i].time);
					// 	}

					// 	/**
					// 	 * 拿到日期，把空白填补
					// 	 */


					// 	temp.forEach(item1 => {
					// 		tabList.forEach((item2, j) => {
					// 			// console.log(item2,item1)
					// 			if (item2 == item1) {
					// 				tabList.splice(j, 1);

					// 				if (tabList.length < 6) {
					// 					tabList.splice(j, 0, 1);
					// 				}

					// 				j -= 1;
					// 			}
					// 		});
					// 	});


					// 	/**
					// 	 * 删除没有产品的导航栏
					// 	 */
					// 	let newlist = [];
					// 	for (let i = 0; i < list.length; i++) {

					// 		if (tabList[i] == 1) {
					// 			newlist.push(list[i]);
					// 		}
					// 	}
					// 	// console.log(newlist, list, tabList);
					// 	if (newlist.length != 0) {
					// 		// console.log(this.isLoad, "++++++++++++++++++++++++++", newlist[0]);
					// 		// if (!this.isLoad) return false;
					// 		// this.isLoad = false;
					// 		newlist[0]['active'] = true;
					// 		this.setData({
					// 			TabList: newlist
					// 		});
					// 		var all = new Date().getTime()
					// 		if (newlist[0].dayType == 1) {
					// 			_ts.setData({
					// 				activityGroup: data.filter(it => it.year <= all)
					// 			});
					// 		} else {
					// 			_ts.setData({
					// 				activityGroup: data.filter(it => it.date == newlist[0].times)
					// 			});
					// 		}
					// 		// console.log(data, all)
					// 	}
					// }
					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
					}
					_ts.clearAllTimer();
					_ts.initGroupTimer();
				});
			},

			/**
			 * 
			 * 
			 * 点击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/seckillDetails/seckillDetails?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)
			},

			/**
			 * 生命周期函数--监听页面初次渲染完成
			 */
			initGroupTimer() {
				//社区拼图定时器
				let _ts = this;

				if (this.activityGroup && this.activityGroup.length > 0) {
					let activityGroup = this.activityGroup;
					for (let i = 0, 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); // console.log(data)

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

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

			/**
			 * 
			 *  产品活动开始时间转换 year-month-day hour:minute:00
			 * 
			 */
			getDate(str) {
				var strArr = str.split(' ');
				var time = strArr[0].toString().split('-');
				var hose = strArr[1].toString().split(':');
				var hour = hose[0];
				var minute = hose[1];
				var day = time[2];
				var month = time[1];
				var year = time[0];
				var date = (month + '月' + day + '日').toString();
				var date1 = (hour + ':' + minute).toString();
				var date2 = strArr[0];
				var allTime = {
					date: (month + '月' + day + '日').toString(),
					date1: (hour + ':' + minute).toString(),
					date2: strArr[0]
				}
				return allTime
			},

			/**
			 * 时间转换
			 */
			getda(str) {
				var strArr = str.split('-');
				var day = strArr[2];
				var month = strArr[1];
				var year = strArr[0];
				var date = (month + '月' + day + '日').toString();
				return date;
			},

			/**
			 * 活动产品预约
			 */
			addActivityRemind(event) {
				const index = event.currentTarget.dataset.index;
				const id = event.currentTarget.dataset.id; // 订阅调用


				req.postRequest('/api/activity/remind', {
					activityId: id
				}, res => {
					requsetmessage.remind(res => {
						// console.log(res, "11111111111");
					});
					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);
					});
				}
			},

			/**
			 * 获取当前时间往后退四天
			 */
			laterDay(num) {
				var t = new Date();
				var iToDay = t.getDate();
				var iToMon = t.getMonth();
				var iToYear = t.getFullYear();
				var arr = [];
				var day = []

				for (var i = 1; i < num + 1; i++) {
					var newDate = new Date(iToYear, iToMon, iToDay + i);
					arr.push(newDate.getFullYear() + '-' + (newDate.getMonth() + 1).toString().padStart(2, '0') + "-" +
						newDate.getDate()
						.toString().padStart(2, '0'));
					day.push((newDate.getMonth() + 1).toString().padStart(2, '0') + "月" + newDate.getDate()
						.toString().padStart(2, '0') + "日"
					)
				} // console.log(arr)
				var obj={
					arr:arr,
					day:day
				}
		
				return obj;
			},

			/**
			 * 给tab添加动态时间
			 */
			getTime() {
				const data = this.TabList;
				var t = new Date();
				var iToDay = t.getDate().toString().padStart(2, '0');
				var iToMon = (t.getMonth() + 1).toString().padStart(2, '0');
				var iToYear = t.getFullYear();
				const rq = (iToYear + '-' + iToMon + '-' + iToDay).toString();
				const rq5 = (iToMon + '月' + iToDay + '日').toString()
				const rq1 = this.laterDay(4).arr[0];
				const rq6 =this.laterDay(4).day[0]
				const rq2 = this.laterDay(4).arr[1];
				const rq7 =this.laterDay(4).day[1]
				const rq3 = this.laterDay(4).arr[2];
				const rq8 =this.laterDay(4).day[2]
				const rq4 = this.laterDay(4).arr[3]; // console.log("rq" + "---", rq1, rq2, rq3, rq4)
				const rq9 =this.laterDay(4).day[3]

				data[0].time = rq;
				data[0].times = rq5;
				data[1].time = rq1;
				data[1].times = rq6;
				data[2].time = rq2;
				data[2].times = rq7;
				data[3].label = this.getda(rq3);
				data[3].time = rq3;
				data[3].times = rq8;
				data[4].label = this.getda(rq4);
				data[4].time = rq4;
				data[4].times = rq9;
				this.setData({
					TabList: data
				}); // console.log(this.data.TabList)
			},

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