<template>
	<view class="timing-page">
		<!-- <store-name></store-name> -->
		<view class="t-title">{{switchInfo.hardware_name}}定时</view>
		<view class="t-box">

			<view class="info-list">
				<view class="il-switch">
					<text class="">时间动作</text>
					<view class="" @click="tapSwitch">开
						<view class="un-select" v-if="!on"></view>
						<image v-else class="" src="../../../../static/images/icon/retail/choose.png" mode=""></image>
					</view>
					<view class="" @click="tapSwitch">关
						<view class="un-select" v-if="on"></view>
						<image v-else src="../../../../static/images/icon/retail/choose.png" mode=""></image>
					</view>
				</view>
				
				<view class="il-select">
					<text class="">时间类型</text>
					<picker @change="bindPickerChangeSingle" :value="sIndex" :range="singleArr">
					<view class="il-input">
							<text>{{singleArr[sIndex]}}</text><image src="../../../../static/images/icon/arrow_b2.png" mode=""></image>
					</view>
					</picker>
				</view>
				<view class="il-select-week" v-if="sIndex==0">
					<block v-for="(e,i) in weekArrSelect" :key="i">
						<view class=""  :class="e?'active':''" @click="clickWeekTab(i)">星期{{weekArrCN[i]}}</view>
					</block>
				</view>

				<block v-if="sIndex==1">
					<view class="il-select" >
						<text class="">具体日期</text>
						<!-- <picker @change="bindPickerChangeDay" :value="dIndex" :range="dayArr"> -->
						<view class="il-input" @click="padConfig.show = true">
								<text>请点击选择</text><image src="../../../../static/images/icon/arrow_b2.png" mode=""></image>
						</view>
						<!-- </picker> -->
					</view>
					<view class="il-select-week">
						<block v-for="(e,i) in dayArrSelect" :key="i">
							<view v-if="e" class=""  :class="e?'active':''" @click="">{{i+1}} 号</view>
						</block>
					</view>
				</block>
				
				<view class="il-select-double" v-if="sIndex==2">
					<text class="">具体时间段</text>
					<view class="il-input">
						<picker mode="date" :value="startTime" :start="startDate" :end="endDate" @change="bindTimeChangeStart">
							<text>{{startTime?startTime+'起':'请选择开始时间'}}</text>
						</picker>
						<view class="">至</view>
						<picker mode="date" :value="endTime" :start="startDate" :end="endDate" @change="bindTimeChangeEnd">
							<text>{{endTime?endTime+"止":"请选择结束时间"}}</text>
						</picker>
					</view>
				</view>
				
				<view class="il-select">
					<text class="">时间点</text>
					<picker mode="time" :value="time" start="00:00" end="23:59" @change="bindTimeChange">
					<view class="il-input">
							<text>{{time}}</text><image src="../../../../static/images/icon/arrow_b2.png" mode=""></image>
					</view>
					</picker>
				</view>
				
			</view>
			
			<view class="save-btn" @click="saveAdd">保存</view>
			<view class="bottom-tips">保存后发布后将会以最新的定时更新到欧轩智能中控，设备首页<text>定时列表</text>可查看最新发布</view>
		</view>
		
		
		<!-- 日期天多选选择弹框 -->
		<view class="voice_control_pad" v-if="padConfig.show" @touchmove.stop.prevent="(()=>{})">
			<view class="cover_bg" @click.stop="padConfig.show=false"  @touchmove.stop.prevent="(()=>{})"></view>
			<view class="v_box" >
				<scroll-view scroll-y="true" >
					<view class="il-select-week">
						<block v-for="(e,i) in dayArrSelect" :key="i">
							<view class=""  :class="e?'active':''" @click.stop="clickDaysTab(i)">{{i+1}} 号</view>
						</block>
					</view>
				</scroll-view>
				
				<view class="v_btns">
					<view class="voice_btn btn_green" @click="padConfig.show=false">确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import util from '../../../../utils/util';
	import store_name from '../../components/store_name/store_name';
	import deviceServer from '../../js/device_server';
	import deviceApi from '../../js/device_api';

	const rootPage = '/subpackage/device'
	const tabArr = [{
			id: 0,
			name: '全部',
			path: ``,
			on: true
		},
	];
	const weekArrCN = ["日", "一", "二","三","四","五","六"];
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			'store-name': store_name
		},
		computed: {
			...mapState({
				storeList: state => state.device.storeList,
				curStoreInfo: state => state.device.curStoreInfo,
			}),
			isDel() {
				return (item) => {
					return item[2] == "删除" ? "true" : ""
				}
			},
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			const dayArrSelect = (()=>{
				let days = []
				for(var i=1;i<=31;i++){
					days.push(false)
				}
				return days
			})()
			return {
				switchInfo:"",//上层页面的选择信息
				on:false,
				singleArr:["星期","具体日期","具体时间段"],
				sIndex:0,
				dayArrSelect:dayArrSelect,//31天 选择
				dIndex:0,
				weekArrCN,
				weekArrSelect:[false,false,false,false,false,false,false],
				date: currentDate,
				time: '00:00-',
				startTime:"",
				endTime:"",
				padConfig:{
					show:false,
					data:[]
				},
				reqData:{//定时请求中控参数 调用sendPacket时传递参数  switchData->postData->reqData(最终请求数据)
				  "device": "00-10-7a-0f-6d-7a",
				  "delay": 1,
				  "data": {
					"name": "set-time-select",
					"value": {
					  "data": "传入设置的json格式字符串,例如:{\"time_arrow_id\":\"c8c39f5c-8dd4-11eb-9aad-4e965989bbce\",\"group\":\"RPIO\",\"type\":\"DAY_OF_WEEK\",\"day_of_week\":[0,1,2,3,6,5,4],\"day_of_month\":null,\"date_slice\":[{\"start\":\"\",\"end\":\"\"}],\"times_on_day\":[\"10:13:00-10:13:10\"],\"expand_tags\":null,\"expand_value\":{\"main\":{\"name\":\"set-rpio\",\"title\":\"测试中控照明9\",\"value\":{\"id\":\"9\",\"status\":\"high\"}}},\"weights\":0,\"extension\":null}"
					}
				  }
				},
				postData:{//定时参数消息结构 reqData.data.value
					"time_arrow_id": "", //不用填 留空
					"group": "RPIO", //照明,风扇,空调固定值,其它不确定
					"type": "DAY_OF_WEEK", //DAY_OF_WEEK/DAY_OF_MONTH/DATE_SLICE , 对应 周,月,单独时间. 
					"day_of_week": [ 
					],
					"day_of_month": null, //数组
					"date_slice": [
						{
							"start": "",
							"end": ""
						}
					],
					"times_on_day": [//时间点
						// "10:13:00-10:13:10" //后台要求,10s期间
					],
					"expand_tags": null,
					"expand_value": {
						"main": { //中控指令
							"name": "set-rpio",
							"title": "",
							"value": {
								"id": "",//设备id
								"status": "high" //low:开, high:关
							}
						}
					},
					"weights": 0,//权重
					"extension": null
				},
				switchData:"",//开关请求中控参数 postData.expand_value.main
				
			}
		},
		async onLoad(option) {
			this.handleOpts(option);	
		},
		onShow() {
			// this.updateList() //更新中控信息
		},
		watch: {
		    curStoreInfo(newVal, oldVal){
				// this.infoArr.length = 1
		        // this.updateList()
		    }
		},
		methods: {
			//处理参数
			handleOpts(option){
				let switchInfo =  JSON.parse(decodeURIComponent(option.switchInfo));
				this.switchInfo = switchInfo //该选择控制设备的所有数据 (目前只使用了hardware_name)
				this.switchData = switchInfo.switchData //开关关联数据
				
				//去掉店铺切换功能
				// try {
				// 	util.showLoad();
				// 	let _brandInfo = await this.$store.dispatch('getBrandInfo');
				// 	await this.$store.dispatch('getStoreList');
				// 	util.hideLoad();
				// } catch (err) {
				// 	util.hideLoad();
				// }
			},
			//点击保存按钮
			saveAdd(){ //switchData(开关命令数据)->postData(后台定时接口数据)->reqData(组成最终小程序端中控定时数据)
				let {switchData,postData,reqData,curStoreInfo,sIndex,time,getWeekRes,getMonthDaysRes,getSliceRes,getDayTimeRes,sendDataToVC} = this;
				
				// ["星期","具体日期","具体时间段"],
				if(sIndex==0)postData.day_of_week = getWeekRes(); //
				if(sIndex==1)postData.day_of_month = getMonthDaysRes(); //当月的多选某天
				if(sIndex==2)postData.date_slice = getSliceRes(); //
				
				if(time=="00:00-") return util.showNone("请先选择定时时间点!")
				postData.times_on_day = getDayTimeRes(); //时间点,固定要传
				
				switchData.data.title = `${this.switchInfo.hardware_name}-${this.singleArr[this.sIndex]}定时`;
				postData.expand_value.main = switchData.data;
				reqData.device = switchData.device
				reqData.data.value.data = JSON.stringify(postData)
				
				console.log("reqData:",JSON.stringify(reqData));
				
				uni.showModal({
					content: `确认要设置${curStoreInfo.venue_name}中 [ ${this.switchInfo.hardware_name} ] 的[ ${this.singleArr[this.sIndex]} ]计划任务 ?`,
					success(res) {
						console.log("确认执行", res.confirm)
						if(res.confirm){
							sendDataToVC();
						}
					},
				})
				
			},
			getWeekRes(){
				console.log(this.weekArrSelect);
				let res = []
				this.weekArrSelect.forEach((e,i)=>{
					if(e)res.push(i)
				})
				return res
			},
			getMonthDaysRes(){
				let res = []
				this.dayArrSelect.forEach((e,i)=>{
					if(e)res.push(i+1)
				})
				return res
			},
			getSliceRes(){
				let res = [],{startTime,endTime} = this;
				if(startTime&&endTime){
					res.push({
						"start": startTime,
						"end": endTime
					})
				}else{
					res.push({
						"start": "",
						"end": ""
					})
				}
				return res
			},
			getDayTimeRes(){
				let res = []
				res.push( `${this.time}:00-${this.time}:10`)
				return res
			},
			tapSwitch(){ //开关切换
				this.on = !this.on
				this.switchData.data.value.status = this.on? "low":"high";
				this.switchData.data.value.o = this.on? "low":"high";
			},
			clickWeekTab(index) {
				if(this.weekArrSelect[index]) {
					this.$set(this.weekArrSelect,index,false)
				}else{
					this.$set(this.weekArrSelect,index,true)
				}
			},
			clickDaysTab(index) {
				if(this.dayArrSelect[index]) {
					this.$set(this.dayArrSelect,index,false)
				}else{
					this.$set(this.dayArrSelect,index,true)
				}
			},
			bindPickerChangeSingle(e){
				console.log('bindPickerChangeSingle，携带值为', e.target.value)
				this.sIndex = e.target.value
				// DAY_OF_WEEK/DAY_OF_MONTH/DATE_SLICE
				this.postData.type = ['DAY_OF_WEEK','DAY_OF_MONTH','DATE_SLICE'][e.target.value]
				this.resetPostData();
			},
			resetPostData(){ //重置选择数据为原始状态
				let _reset = {
					"day_of_week": [ 
					],
					"day_of_month": null, //数组
					"date_slice": [{
							"start": "",
							"end": ""
						}
					],}
				for(var i in _reset){
					console.log("重置:",i);
					this.postData[i] = _reset[i]
				}

			},
			bindTimeChange(e){ //时间选择
				this.time = e.target.value
			},
			bindTimeChangeStart(e){ //日期选择
				if(new Date(this.endTime)-new Date(e.target.value)<0) return util.showNone("开始时间异常")
				this.startTime = e.target.value
			},
			bindTimeChangeEnd(e){ //日期选择
				if(new Date(e.target.value)-new Date(this.startTime)<0) return util.showNone("结束时间异常")
				this.endTime = e.target.value
			},
			bindPickerChangeDay(e){ //月选择
				console.log('bindPickerChangeDay，携带值为', e.target.value)
				 this.dIndex = e.target.value
			},
			//删除计划任务
			delItem(e,i) {
				let that = this
				let delData = {
				  "device": this.curStoreInfo.device_name,
				  "delay": 1,
				  "data": {
				    "name": "delete-time-select",
				    "value": {
				      "uuid": e[3]
				    }
				  }
				}
				uni.showModal({
					content: `确认要删除: ${e[0]}的计划任务 ?`,
					success(res) {
						console.log("确认删除", res.confirm)
						if(res.confirm){
							that.operateReq({
								data: delData,
								succFun: (res) => {
									that.updateList()
								},
								isTip:true
							})
						}
					},
				})
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 0;
				} else if (type === 'end') {
					year = year + 10;//限制可选10年内
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			async sendDataToVC() {
				let that = this
				let timingData = {
				}
				timingData = this.reqData
				
				this.operateReq({
					data: timingData,
					succFun: (res) => {
						console.log("操作结果:",res);
						if(res=="ok"){
							let timing_list = "/subpackage/device/pages/timing/timing_list"
							util.routeTo(`${timing_list}`, 'nT');
						}
					},
					isTip:true
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 操作接口请求
			operateReq({
				data,
				succFun,
				isTip = false,
				isLoad = true,

			}) {
				let that = this
				if (isLoad) util.showLoad();
				deviceServer.post({
						url: deviceApi.ouxuanac,
						data: data,
						isDefaultGet: false,
					})
					.then(res => {
						if (isLoad) util.hideLoad();
						if (res.data.code == 0) {
							if (isTip) util.showNone(res.data.message || '操作成功！');
							succFun(res.data.data)
						} else {
							if (isTip) util.showNone(res.data.message || '操作失败！');
						}
					})
					.catch(err => {
						if (isLoad) util.hideLoad()
					})
			},

		}
	}
</script>

<style lang="scss">
	@import '~style/public.scss';

	.timing-page {

		.t-title {
			font-size: 44rpx;
			color: #1A1A1A;
			font-weight: 900;
			margin: 60rpx auto 72rpx 40rpx;
		}

		.t-box {
			height: 500rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: flex-start;
			width: 100%;

			.info-list {
				margin-bottom: 50rpx;
				padding: 50rpx 30rpx;
				width: 700rpx;
				height: auto;
				background: #FFFFFF;
				border-radius: 10rpx;
				font-size: 32rpx;
				.il-switch{
					width: 580rpx;
					@include centerFlex(space-between);
					> view{
						@include centerFlex(center);
						image{
							margin-left: 20rpx;
							width: 40rpx;height: 40rpx;
						}
						.un-select{
							margin-left: 20rpx;
							background-color: white;
							width: 40rpx;height: 40rpx;
							border-radius: 50%;
							border: 2rpx solid lightgray;
						}
					}
					
				}
				.il-select{
					margin-top: 50rpx;
					width: 100%;
					@include centerFlex(space-between);
					.il-input {
						@include centerFlex(space-between);
						padding: 20rpx;
						margin-left: 20rpx;
						width: 480rpx;
						height: 96rpx;
						background: #FFFFFF;
						border: 2rpx solid #D8D8D8;
						border-radius: 10rpx;
						text{
							color: #9C9C9F;
						}
						image{
							width: 28rpx;
							height: 28rpx;
							transform: rotate(90deg);
						}
					}
				}
				.il-select-double{
					margin-top: 50rpx;
					width: 100%;
					@include centerFlex(flex-start);
					align-items: flex-start;
					flex-direction: column;
					.il-input {
						@include centerFlex(space-between);
						padding: 20rpx;
						margin-top: 20rpx;
						width: 648rpx;
						height: 96rpx;
						background: #FFFFFF;
						border: 2rpx solid #D8D8D8;
						border-radius: 10rpx;
						text{
							color: #9C9C9F;
						}
						> view{
							padding: 0 10rpx;
						}
					
					}
				}
				.il-select-week{
					width: 100%;
					height: auto;
					@include centerFlex(flex-start);
					flex-wrap: wrap;
					> view{
						@include centerFlex(center);
						width: 160rpx;
						height: 88rpx;
						border: 2rpx solid #979797;
						border-radius: 6rpx;
						color: #979797;
						margin-left: 40rpx;
						margin-top: 40rpx;
					}
					.active{
						background: rgba(0,152,116,0.12);
						border: 2rpx solid #009874;color: #009874;
					}
				}

			}
		}
	}
	
	// 底部css
	.save-btn{
		width: 700rpx;
		height: 110rpx;
		text-align: center;
		line-height: 110rpx;
		background: #009874;
		border-radius: 10px;
		color: white;
	}
	.bottom-tips{
		font-size: 28rpx;
		color: #1A1A1A;
		text{
			color: #009874;
		}
		margin: 40rpx;
	}
	
	//弹窗选择
	.voice_control_pad {
		position: fixed;
		top: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		z-index: 1;
		.cover_bg {
			position: fixed;
			top: 0;
			background: rgba($color: #000000, $alpha: .3);
			z-index: 2;
			width: 100%;
			height: 100%;
		}
		.v_box {
			z-index: 3;
			width: 630rpx;
			background-color: white;
			border-radius: 10rpx;
			scroll-view{
				margin-top: 30rpx;
				display: flex;
				flex-direction: row;
				justify-content: flex-start;
				align-items: flex-start;
				border-radius: 5rpx;
				flex-wrap: wrap;
				width: 100%;
				height: 700rpx;
				border-bottom: 1rpx solid #F2F2F7;
				
				.il-select-week{
					width: 100%;
					height: auto;
					@include centerFlex(flex-start);
					flex-wrap: wrap;
					> view{
						@include centerFlex(center);
						width: 160rpx;
						height: 88rpx;
						border: 2rpx solid #979797;
						border-radius: 6rpx;
						color: #979797;
						margin-left: 40rpx;
						margin-top: 40rpx;
					}
					.active{
						background: rgba(0,152,116,0.12);
						border: 2rpx solid #009874;color: #009874;
					}
				}

			}
			
			.voice_btn {
				width: 392rpx;
				height: 112rpx;
				background: #009874;
				border-radius: 5rpx;
				text-align: center;
				line-height: 112rpx;
				color: white;
				font-size: 32rpx;
			}
			
			.btn_active {
				color: black;
				background-color: rgba($color: #000000, $alpha: .4);
			}
			
			.btn_white {
				width: 204rpx;
				height: 88rpx;
				background-color: white;
				color: #009874;
				border: 1rpx solid #009874;
				line-height: 88rpx;
			}
			
			.btn_green {
				width: 204rpx;
				height: 88rpx;
				background-color: #009874;
				color: white;
				line-height: 88rpx;
			}
			
			.v_btns {
				width: 100%;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				margin: 50rpx 0;
			}
		}
	}
	

</style>
