<template>
	<view class="box">
		<!-- 上面要素值 -->
		<view :class="`bigBox ${show ? 'bigOpen' : ''}`">
			<view class="topInfo">
				<u-row gutter="10">
					<u-col span="3" v-for="item in ElementList">
						<view class="item">
							<view>{{item.value}}</view>
							<view>{{item.unit}}</view>
							<view>{{item.name}}</view>
						</view>
					</u-col>
				</u-row>
				<view class="readmore" v-if="!show" @click="show=true;getHistoryData()">
					查看详情<u-icon name="arrow-down" color="#93FFDE" size="28"></u-icon>
				</view>
			</view>
			<!-- 统计图 -->
			<view class="hisBox" v-show="show">
				<view class="axiosBox">
					<view class="title">
						历史数据
					</view>
					<view class="histimeBox">
						<u-icon name="calendar" color="#C1C1C1" size="24"></u-icon>
						<view class="time" @click="calendarshow = true">{{historyTime.startDate ? historyTime.startDate : '开始'}}</view>
						<view class="">至</view>
						<view class="time" @click="calendarshow = true">{{historyTime.endDate ? historyTime.endDate : '结束'}}</view>
						<u-icon name="close-circle" color="#C1C1C1" size="28" @click="historyTime={};getHistoryData()" v-if="historyTime.startDate"></u-icon>
					</view>
					<u-calendar v-model="calendarshow" mode="range" @change="changeDate"></u-calendar>
					<view class="chartBox">
						<canvas canvas-id="canvasColumnA" id="canvasColumnA" class="charts"
							@touchstart="touchLineA($event)" @touchmove="moveLineA($event)"
							@touchend="touchEndLineA($event)"></canvas>
					</view>
				</view>
				<view class="readmore" @click="show=false">
					收起详情<u-icon name="arrow-up" color="#14A478" size="28"></u-icon>
				</view>
			</view>
		</view>
		<!-- 历史记录弹框 -->
		<u-tabs :list="list" active-color="#14A478" bar-width="300" :is-scroll="false" :current="current"
			@change="change"></u-tabs>
		<!-- 设备图 -->
		<view class="devicePhoto" v-if="current == 0">

		</view>
		<!-- 操作记录 -->
		<view class="consoleList" v-else>
			<view class="histimeBox">
				<u-icon name="calendar" color="#C1C1C1" size="24"></u-icon>
				<view class="time" @click="consoleshow = true">{{consoleTime.startDate ? consoleTime.startDate : '开始'}}</view>
				<view class="">至</view>
				<view class="time" @click="consoleshow = true">{{consoleTime.endDate ? consoleTime.endDate : '结束'}}</view>
				<u-icon name="close-circle" color="#C1C1C1" size="28" @click="clearContime" v-if="consoleTime.startDate"></u-icon>
			</view>
			<u-calendar v-model="consoleshow" mode="range" @change="changeConsoleDate"></u-calendar>
			<view class="tableList tableTitle">
				<view>设备名称</view>
				<view>操作内容</view>
				<view>操作时间</view>
			</view>
			<view class="tableList" v-for="item in tableData" :key="item.uptime">
				<view>{{item.device_name}}</view>
				<view>{{item.operation_content}}</view>
				<view>{{item.uptime}}</view>
			</view>
			<u-loadmore :status="status" />
		</view>
	</view>
</template>

<script>
	import uCharts from '../../components/js_sdk/u-charts/u-charts/u-charts.js';
	var canvaColumnA = null;
	var canvasRing = null;
	export default {
		data() {
			return {
				device_id: '',
				mainBeng: false,
				feiBeng: false,
				calendarshow: false,
				historyTime: {},
				cWidth: '350',
				cHeight: '350',
				pixelRatio: 1,
				facilityvalve: [],
				ElementList: [],
				typename: [
					"-",
					"风机",
					"水泵",
					"增氧机",
					"湿帘",
					"遮阳",
					"开窗",
					"保温",
					"投食机",
				],
				show: false,
				list: [{
					name: '设备控制'
				}, {
					name: '操作记录'
				}],
				current: 1,
				consoleshow: false,
				consoleTime: {},
				tableData: [],
				page: 1,
				total: 0,
				status: 'loadmore'
			}
		},
		methods: {
			// 选择日期
			changeDate(e) {
				console.log(e)
				this.historyTime = e;
				this.getHistoryData()
			},
			// 绘制折线图
			showColumn(id, xtitle, xinfo) {
				var _self = this
				canvaColumnA = new uCharts({
					canvasId: id,
					type: 'line',
					legend: {
						position: "top"
					},
					fontSize: 11,
					background: '#FFFFFF',
					pixelRatio: 1,
					animation: true,
					dataLabel: false,
					categories: xtitle,
					series: xinfo,
					enableScroll: true, //开启图表拖拽功能
					xAxis: {
						disableGrid: true,
						type: 'grid',
						gridType: 'dash',
						itemCount: 4, //x轴单屏显示数据的数量，默认为5个
						scrollShow: true, //新增是否显示滚动条，默认false
						// scrollAlign: 'left', //滚动条初始位置
						scrollBackgroundColor: '#F7F7FF', //默认为 #EFEBEF
						scrollColor: '#DEE7F7', //默认为 #A6A6A6

					},
					yAxis: {},
					width: _self.cWidth * 1,
					height: _self.cHeight * 1,
					extra: {
						line: {
							type: 'curve'
						}
					}
				});
			},
			touchLineA(e) {
				// console.log(e)
				canvaColumnA.scrollStart(e);
			},
			moveLineA(e) {
				canvaColumnA.scroll(e);
			},
			touchEndLineA(e) {
				canvaColumnA.touchLegend(e);
				// canvaColumnA.showToolTip(e);
				canvaColumnA.scrollEnd(e);
				//下面是toolTip事件，如果滚动后不需要显示，可不填写
				canvaColumnA.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},
			// 时间戳转换
			timestampToDateTime(timestamp) {
				var date = new Date(timestamp * 1000); // 将时间戳转换为毫秒并创建一个日期对象
				var year = date.getFullYear(); // 获取年份
				var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，并补零
				var day = ('0' + date.getDate()).slice(-2); // 获取日期，并补零
				return year + '-' + month + '-' + day;
			},
			// 历史数据
			async getHistoryData() {
				const {
					historyTime
				} = this;
				let begin = historyTime.startDate ? new Date(historyTime.startDate).getTime() / 1000 : '';
				let end = historyTime.endDate ? new Date(historyTime.endDate).getTime() / 1000 : '';
				//折线图数据
				let res = await this.$myRequest({
					url: "/api/api_gateway?method=weather.weather.sf_data_chart",
					data: {
						device_id: this.device_id,
						begin: begin,
						end: end,
					},
				})
				console.log(res);
				var conf = res.conf.eleName;
				var dat = res.dat;
				//console.log(dat);
				conf = conf.split("/");
				// var arr1 = [];
				var regroupData = []; //重组数据
				let options = [];
				var timeList = [];
				for (var i = 0; i < conf.length; i++) {
					// var arr = [];
					if (conf[i] != "-") {
						var optionobj = {};
						optionobj.value = i;
						optionobj.label = conf[i];
						options.push(optionobj);
						var reddata = [];
						dat.forEach((item, index) => {
							if (timeList.length < dat.length) {
								timeList.push(this.timestampToDateTime(item.uptime));
							}
							var status = item.device_status.split(",");
							// //console.log(status);
							var arr = [];
							for (var j = 0; j < status.length; j++) {
								if (status[j].indexOf("e") + 1) {
									arr.push(status[j]);
								}
							}
							// //console.log(arr)
							var dataobj = {};
							for (var k = 0; k < arr.length; k++) {
								var indexs = arr[k].indexOf(":");
								// //console.log(arr[k])
								if (k == 0) {
									dataobj[arr[k].slice(1, indexs).trim()] = arr[k]
										.substr(indexs + 1)
										.trim();
								} else {
									dataobj[arr[k].slice(0, indexs).trim()] = arr[k]
										.substr(indexs + 1)
										.trim();
								}
							}
							// //console.log(dataobj)
							for (var key in dataobj) {
								// //console.log(i)
								var str = "'e" + (i + 1) + "'";
								// //console.log(key,str);
								if (key == str) {
									if (Number(dataobj[key]) == 32767) {
										// reddata.push([]);
									} else {
										reddata.push(Number(dataobj[key]));
									}
								}
							}
						});
						regroupData.push({
							name: conf[i],
							type: "spline",
							fillColor: {
								linearGradient: [0, 0, 0, 300],
							},
							data: reddata,
						});
					}
				}
				// console.log(timeList);
				this.showColumn('canvasColumnA', timeList, regroupData)
			},
			// 切换选项卡
			change(index) {
				this.current = index;
			},
			// 获取要素实时数据
			async getElmentInfo() {
				let res = await this.$myRequest({
					url: "/api/api_gateway?method=xphsp.views.device_elements",
					data: {
						device_id: this.device_id,
					},
				})
				var conf = res.conf.eleName.split('/');
				var dataList = res.data;
				if (dataList.length == 0) return
				this.ElementList = [];
				conf.forEach((item, index) => {
					let obj = {}
					if (item == '-') return
					obj.name = item;
					let valList = dataList[0].device_data[`e${index + 1}`].split('#');
					obj.value = valList[0];
					obj.unit = valList[1];
					obj.time = dataList[0].uptime;
					this.ElementList.push(obj)
				})
				// console.log(this.ElementList)
			},
			async getEquipstatus() {
				this.facilityvalve = [];
				let res = await this.$myRequest({
					url: "/api/api_gateway?method=xphsp.views.device_info",
					data: {
						device_id: this.device_id,
					},
				})
				console.log(res)
				var conf = res.conf.relayName;
				var dataobj = res.device_status;
				var relayNum = res.conf.relayNum;
				var arr = [];

				function numberToArray(number) {
					// 将数字转换为字符串
					let numString = number.toString();

					// 创建一个空数组，用于存储结果
					let result = [];

					// 遍历字符串的每个字符，并将其转换为对应的数字
					for (let i = 0; i < numString.length; i++) {
						result.push(parseInt(numString.charAt(i)));
					}

					return result;
				}
				for (var i = 0; i < dataobj.length; i++) {
					// if (offobj[i].indexOf("j") + 1) {
					arr.push(offobj[i]);
					// }
				}
				conf = conf.split("/");
				relayNum = relayNum.split("/");
				var arr1 = [];
				var reg = /\d/;
				let totalP = Math.ceil((conf.length) / 32); //总圈数
				for (var i = 0; i < conf.length; i++) {
					var obj = {};
					obj.name = conf[i];
					// if (reg.test(conf[i])) {
					//   obj.name2 = conf[i].slice(0, conf[i].length - 1);
					// } else {
					//   obj.name2 = conf[i];
					// }
					obj.name2 = this.typename[relayNum[i]];
					obj.number = i;
					obj.type = `j${i + 1}`;
					obj.disabled = false;
					// "state": 1 继电器打开 ;"state": 0 继电器关闭
					// 处理开关值
					// J开头表示状态，总共只有32长度，超过32则从头赋值 位数多一位 
					// 例：1和33是都在J1里面，返回值是一个二进制数 倒数第一位表示第一个 第二位表示33状态 以此类推
					// 根据总长度 为超过32的j赋值
					// 当前是循环的第几轮
					let baseP = Math.ceil((i + 1) / 32);
					if (i > 31) {
						dataobj[`j${i + 1}`] = dataobj[
							`j${(i + 1) % 32 == 0 ? 32 : (i + 1) % 32}`]; // 当前脚标/32取余 当恰好整除的时候  取32
					}
					dataobj[`j${i + 1}`] = dataobj[`j${i + 1}`].slice(-totalP); // 截取当前圈数的最后几位数字
					let baseOff = numberToArray(dataobj[`j${i + 1}`]); // 把当前值根据位数 转换为数组 
					obj.off = baseOff[baseP - 1] == '0' ? false : true; // 根据当前圈数，取对应的数组的值
					arr1.push(obj);
				}
				for (var i = 0; i < arr1.length; i++) {
					if (arr1[i].name != "-") {
						this.facilityvalve.push(arr1[i]);
					}
				}
				this.facilityvalve.forEach(item => {
					if (item.type == 'j9' && item.off == true) {
						// 判断注水泵是否打开
						this.mainBeng = true;
					}
					if (item.type == 'j10' && item.off == true) {
						// 判断施肥阀是否打开
						this.feiBeng = true;
					}
				})
				console.log(this.facilityvalve)
			},
			getEquipcontrol(num, state) {
				//设备控制
				this.$axios({
					method: "POST",
					url: "/api/api_gateway?method=xphsp.views.control_order",
					data: this.qs.stringify({
						device_id: this.device_id,
						relayNum: num,
						relayState: state,
					}),
				}).then((res) => {
					//console.log(res.data.data);
					if (res.data.data && res.data.data.controlState) {
						this.$message({
							message: "指令下发成功",
							type: "success",
						});
					} else {
						// for (var i = 0; i < this.facilityvalve.length; i++) {
						//   //console.log(this.facilityvalve[i].number, res.data.data.relayNum);
						//   if (
						//     this.facilityvalve[i].number == Number(num)
						//   ) {
						//     //console.log(this.facilityvalve[i]);
						//     this.facilityvalve[i].off = !state;
						//   }
						// }
						this.getEquipstatus()
						this.$message({
							message: res.data.message,
							type: "warning",
						});
					}
				});
			},
			// sf_control_data
			// 操作记录日期
			changeConsoleDate(e) {
				this.consoleTime = e;
				this.tableData = [];
				this.page = 1;
				this.getEquipcontroldata()
			},
			clearContime() {
				this.consoleTime = {};
				this.tableData = [];
				this.page = 1;
				this.getEquipcontroldata()
			},
			//操作记录
			async getEquipcontroldata() {
				const {
					consoleTime
				} = this;
				let begin = consoleTime.startDate ? new Date(consoleTime.startDate).getTime() / 1000 : '';
				let end = consoleTime.endDate ? new Date(consoleTime.endDate).getTime() / 1000 : '';
				//操作记录
				let res = await this.$myRequest({
					method: "POST",
					url: "/api/api_gateway?method=xphsp.views.control_log",
					data: {
						device_id: this.device_id,
						page_num: this.page,
						page_size: 15,
						start: begin,
						end: end,
					},
				})
				// this.tableData = [];
				var record = res.result;
				this.tableData = [...this.tableData, ...record];
				this.total = res.count;
				if (this.page * 15 > this.total) {
					this.status = 'nomore'
				} else {
					this.status = 'loadmore'
				}
				console.log(this.tableData);
			},
			switchchange(e, state, item, index) {
				item.off = e;
				if (item.type == 'j9') {
					// 判断注水泵是否打开
					this.mainBeng = e;
				}
				if (item.type == 'j10') {
					// 判断施肥阀是否打开
					this.feiBeng = e;
				}
				if (['j1', 'j2', 'j3', 'j4', 'j5', 'j6'].indexOf(item.type) > 0) {
					let changeIndex = index;
					if ((index + 1) % 2 == 0) {
						// 偶数 往前取值
						this.facilityvalve[index - 1].disabled = true;
						changeIndex = index - 1;
					} else if ((index + 1) % 2 == 1) {
						// 基数 往后取值
						this.facilityvalve[index + 1].disabled = true;
						changeIndex = index + 1;
					}
					item.disabled = true;
					this.changeTimeStatus(item, changeIndex);
				}
				//console.log(Number(e), state);
				this.getEquipcontrol(state, Number(e));
			},
		},
		onReachBottom() {
			if (this.current == 1 && this.status == 'loadmore') {
				this.page++;
				this.getEquipcontroldata()
			}
		},
		onLoad(option) {
			let deviceItem = JSON.parse(option.shebei)
			this.device_id = deviceItem.device_id;
			this.getEquipstatus();
			this.getElmentInfo();
			this.getEquipcontroldata();
		}
	}
</script>

<style scoped lang="less">
	.box {
		position: relative;
		width: 100%;
		height: 100vh;
	}

	.bigBox {
		width: 100%;
	}

	.bigOpen {
		overflow: hidden;
		height: 100%;
	}

	/deep/ .u-flex {
		display: flex;
		justify-content: center;
	}

	.topInfo {
		background: #14A478;
		color: #fff;
		font-size: 28rpx;
		padding-bottom: 32rpx;
		box-sizing: border-box;
		border-bottom-left-radius: 16rpx;
		border-bottom-right-radius: 16rpx;

		.u-col {
			box-sizing: border-box;
			margin-top: 32rpx;

			.item {
				text-align: center;

				view:first-child {
					font-size: 40rpx;
				}

				view:nth-child(2) {
					font-size: 24rpx;
					line-height: 40rpx;
					opacity: .72;
				}
			}
		}
	}

	.readmore {
		text-align: center;
		font-size: 26rpx;
		line-height: 40rpx;
		margin-top: 32rpx;
		color: #93FFDE;

		.u-icon {
			margin-left: 15rpx;
		}
	}

	.histimeBox {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 56rpx;
		padding: 6rpx 24rpx;
		box-sizing: border-box;
		border-radius: 8rpx;
		margin-top: 54rpx;
		border: 2rpx solid var(--neutral-color-border-light, #E4EDEA);
		.u-icon{
			z-index: 10;
		}
		.time {
			width: 280rpx;
			color: #C1C1C1;
		}

		view {
			color: #333333;
			text-align: center;
		}
	}

	.hisBox {
		padding-bottom: 100rpx;

		.axiosBox {
			padding: 48rpx 32rpx;

			.title {
				color: #333333;
				font-size: 28rpx;
				font-weight: 700;
			}

			.chartBox {
				margin-top: 32rpx;
				height: 700rpx;

				#canvasColumnA {
					width: 100%;
					height: 700rpx;
				}
			}
		}

		.readmore {
			color: #14A478;
		}
	}

	.consoleList {
		padding: 0 32rpx;
		.histimeBox{
			margin: 32rpx 0;
		}

		.tableTitle {
			background: #E8F3F0;
			color: #333;
			font-weight: 600;
		}

		.tableList {
			font-size: 28rpx;
			height: 78rpx;
			color: #666666;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 2rpx solid var(--neutral-color-border-base, #DCE6E3);

			view {
				text-align: center;
			}

			view:nth-child(1) {
				width: 120rpx;
			}

			view:nth-child(2) {
				width: 280rpx;
			}

			view:nth-child(3) {
				width: 280rpx;
			}
		}
	}
</style>