<template>
	<!-- 温湿度 -->
	<view>
		<u-navbar title="温湿度记录" autoBack placeholder></u-navbar>
		<view class="card_qiucharts" v-if="userType == 'customer'">
			<view class="card_echart">
				<qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
			</view>
			<view class="card_echart">
				<qiun-data-charts type="gauge" :opts="opts1" :chartData="chartData1" />
			</view>
		</view>
		<view v-else>
			<view v-if="humitureList.length > 0">
				<view class="card_particulars" v-for="(item,index) in humitureList" :key="index">
					<view class="card_describe">
						<view @click="selectChangeil(item)">
							<x-checkbox :label="item.title" :isChecked="item.isChecked"></x-checkbox>
						</view>
						<!-- <view class="describe_title">{{item.title}}</view> -->
						<!-- <view class="describe_time">{{item.startTime}}</view>
						<view class="describe_time">{{item.endTime}}</view> -->
					</view>
					<view class="dateTime_card" style="margin: 20rpx 10rpx;">
						<uni-datetime-picker v-model="item.datetimeRange" type="datetimerange"
							@change="changeDatetime($event,item)" />
					</view>
					<view class="humiture_details" @click="foldingPanel(item)">
						<view class="title_details">温湿度</view>
						<view style="display: flex;">
							<view class="title_blue title_details">查看详情</view>
							<u-icon name="arrow-down"></u-icon>
						</view>
					</view>
					<view v-show="item.collapseil">
						<x-humiture ref="humiture" :startTime="item.datetimeRange[0]" :endTime="item.datetimeRange[1]"
							:taskId="item.id" :waybillNo="waybillNo" :current="item.presentNum"
							:probeList="item.deviceSensorList"></x-humiture>
					</view>
				</view>
			</view>
			<view style="margin-top: 30%;" v-else>
				<u-empty mode="data" text="当前没有温湿度记录"></u-empty>
			</view>
		</view>
		<view style="width: 100%;height: 230rpx;"></view>
		<view class="card_btn"
			v-if="humitureList.length > 0 && waybillData.status != 1 || waybillData.status != 2 || waybillData.status != 3 || waybillData.status != 9">
			<u-button style="margin-bottom: 20rpx;" type="primary"
				@click="humidityRecording('send')">发送温湿度记录PDF</u-button>
			<u-button style="margin-bottom: 20rpx;" type="success"
				@click="humidityRecording('print')">打印温湿度记录</u-button>
		</view>
		<u-modal :show="show" confirmText="停止" showCancelButton :buttonReverse="true" @cancel="cancel"
			@confirm="confirm">
			<view class="slot-content">
				<view>{{stoprecording}}</view>
			</view>
		</u-modal>
		<u-popup :show="shareShow" mode="center" round="5" closeable @close="shareShow = false">
			<view style="padding: 0rpx 30rpx 30rpx 30rpx;margin-top: 50rpx; width: 400rpx;">
				<u-button style="margin: 20rpx 0rpx;" type="success" text="发送邮箱" @click="sendingMailbox"></u-button>
				<u-button type="primary" text="分享微信好友" @click="shareWechatFriends"></u-button>
			</view>
		</u-popup>
		<u-popup :show="emailShow" mode="center" round="5" closeable @close="emailShow = false">
			<view style="padding: 30rpx;">
				<view style="margin-top: 20rpx;width: 600rpx;">
					<view class="email_title" style="margin-bottom: 10rpx;">运单号：{{waybillNo}}</view>
					<view class="card_email">
						<span class="email_title">邮箱地址:</span>
						<view style="margin-top: 20rpx;">
							<u--input v-model="email" placeholder="请输入邮箱" border="surround"></u--input>
						</view>
					</view>
				</view>
				<view style="margin-top: 20rpx;">
					<u-button type="primary" :loading="sendLoading" text="发送" @click="confirmSend"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const FileShare = uni.requireNativePlugin('life-FileShare');
	export default {
		data() {
			return {
				show: false,
				orderList: {},
				humitureList: [],
				userType: '',
				myChart: null,
				chartData: {},
				chartData1: {},
				opts: {
					color: ["#3592FE"],
					padding: undefined,
					title: {
						// name: "66℃",
						fontSize: 25,
						color: "#3592FE",
						offsetY: 0
					},
					subtitle: {
						name: "当前温度",
						fontSize: 15,
						color: "#1890ff",
						offsetY: 0
					},
					extra: {
						gauge: {
							type: "progress",
							width: 20,
							labelColor: "#666666",
							startAngle: 0.75,
							endAngle: 0.25,
							// startNumber: 5,
							// endNumber: 35,
							labelFormat: "",
							splitLine: {
								fixRadius: -10,
								splitNumber: 10,
								width: 15,
								color: "#FFFFFF",
								childNumber: 5,
								childWidth: 12
							},
							pointer: {
								width: 24,
								color: "auto"
							}
						}
					},
				},
				opts1: {
					color: ["#67C23A"],
					padding: 20,
					title: {
						// name: "66℃",
						fontSize: 25,
						color: "#2fc25b",
						offsetY: 0
					},
					subtitle: {
						name: "当前湿度",
						fontSize: 15,
						color: "#67C23A",
						offsetY: 0
					},
					extra: {
						gauge: {
							type: "progress",
							width: 20,
							labelColor: "#000000",
							startAngle: 0.75,
							endAngle: 0.25,
							// startNumber: 0,
							// endNumber: 100,
							labelFormat: "",
							splitLine: {
								fixRadius: -10,
								splitNumber: 10,
								width: 15,
								color: "#67C23A",
								childNumber: 5,
								childWidth: 12
							},
							labelOffset: 20,
							pointer: {
								width: 24,
								color: "auto"
							}
						}
					},
				},
				datetimeRange: [],
				waybillNo: '',
				waybillData: [],
				shareShow: false,
				stoprecording: '打印前需停止记录，是否继续？',
				humitureType: '',
				checkboxValue: [],
				emailShow: false,
				email: '',
				sendLoading: false,
				humidityFlag: false,
			}
		},
		onLoad(option) {
			this.waybillNo = option.waybillNo
			// 获取运单详情
			this.waybillDetails(option.waybillNo)
		},
		mounted() {
			var userInfo = this.$cache.getCache('userInfo')
			this.userType = userInfo.userType
			var orderList = this.$cache.getCache('orderDetails')
			this.orderList = orderList
			if (this.userType == 'customer') {
				this.getServerData();
			} else {
				this.getList()
			}
		},
		methods: {
			getList() {
				this.$api.get('/api/waybill-task', {
					waybillNo: this.waybillNo,
				}).then(res => {
					if (res.code == 200) {
						this.humitureList = JSON.parse(JSON.stringify(res.data.list))
						this.humitureList.forEach((item, index) => {
							this.checkboxValue.push(item.id)
							item.isChecked = true
							item.title = ''
							item.collapseil = false
							item.datetimeRange = []
							item.datetimeRange.push(item.startTime)
							if (item.endTime) {
								item.datetimeRange.push(item.endTime)
							} else {
								item.datetimeRange.push(this.getDateTime(new Date()))
							}
							if (item.car.id) {
								item.title = item.car.carNo
							} else if (item.warehouse.id) {
								item.title = item.warehouse.name
							} else if (item.coolerBox.id) {
								item.title = item.coolerBox.name
							}
						})
					}
				})
			},
			// 获取运单详情
			waybillDetails(waybillNo) {
				this.$api.get('/api/waybill/' + waybillNo).then(res => {
					if (res.code == 200) {
						this.waybillData = res.data
					}
				})
			},
			// 发送邮箱
			sendingMailbox() {
				this.shareShow = false
				this.emailShow = true
			},
			// 分享微信好友
			shareWechatFriends() {
				uni.showLoading({
					title: '获取温湿度记录中,请稍等',
					mask: true,
				});
				this.$api.post('/api/waybill/temperature-pdf-url', {
					waybillNo: this.waybillNo,
					waybillTaskIds: this.checkboxValue,
				}).then(res => {
					if (res.code == 200) {
						let arrData = res.data.split("/");
						var dtask = plus.downloader.createDownload(res.data, {
							filename: "_doc/pdf/" + arrData[3]
						}, function(d, status) {
							// 下载完成
							if (status == 200) {
								FileShare.render({
									type: "WX", //QQ为QQ，微信为WX，系统默认是SYSTEM，不填写默认SYSTEM
									filePath: plus.io.convertLocalFileSystemURL(d.filename),
								}, result => {
									uni.hideLoading()
								});
							} else {
								console.log("Download failed: " + status);
							}
						});
						dtask.start();
					}
					uni.hideLoading()
				}).catch(() => {
					uni.hideLoading()
				})
				return
			},
			// 发送邮箱
			confirmSend() {
				if (this.email) {
					let flag = validateEmail(this.email)
					if (flag) {
						if (!this.sendLoading) {
							this.sendLoading = true
							let arrTo = []
							arrTo.push(this.email)
							this.$api.post('/api/waybill/send-mail', {
								waybillNo: this.waybillNo,
								humidityShow: this.humidityFlag,
								to: arrTo,
								waybillTaskIds: this.checkboxValue,
							}).then(res => {
								if (res.code == 200) {
									uni.$u.toast(res.msg)
									this.email = ''
									this.emailShow = false
								}
								this.sendLoading = false
							}).catch(() => {
								this.sendLoading = false
							})
						}
					} else {
						uni.$u.toast('邮箱格式错误')
					}
				} else {
					uni.$u.toast('请输入邮箱')
				}
				// 如果邮箱格式正确，输出 true，否则输出 false
				function validateEmail(email) {
					const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
					return emailRegex.test(email);
				}
			},
			// 打印温湿度记录
			humidityRecording(type) {
				this.humitureType = type
				if ([4, 5, 10].includes(this.waybillData.status)) {
					if (type == 'send') {
						this.stoprecording = '发送温湿度记录前需停止记录，是否继续？'
					} else {
						this.stoprecording = '打印前需停止记录，是否继续？'
					}
					this.show = true
				} else {
					if (type == 'send') {
						this.shareShow = true
					} else {
						if (this.waybillData.id) {
							this.$cache.setCache('commodity', JSON.stringify(this.waybillData))
							uni.navigateTo({
								url: '/pages/order/quantum?waybillNo=' + this.waybillData.waybillNo +
									'&printType=record'
							});
						} else {
							uni.$u.toast('暂无运单详情数据，无法打印！')
						}
					}
				}
			},
			cancel() {
				this.show = false
			},
			confirm() {
				this.$api.post('/api/waybill/stop-record', {
					waybillNo: this.waybillData.waybillNo,
					startTime: this.getDateTime(new Date()),
				}).then(res => {
					if (res.code == 200) {
						if (this.humitureType == 'send') {
							this.show = false
							this.shareShow = true
						} else {
							if (this.waybillData.id) {
								this.$cache.setCache('commodity', JSON.stringify(this.waybillData))
								uni.navigateTo({
									url: '/pages/order/quantum?waybillNo=' + this.waybillData.waybillNo +
										'&printType=record'
								});
							} else {
								uni.$u.toast('暂无运单详情数据，无法打印！')
							}
						}
					}
					this.show = false
				}).catch(() => {
					this.show = false
				})
			},
			// 折叠面板
			foldingPanel(value) {
				this.humitureList.forEach((item, index) => {
					if (item.id == value.id) {
						if (item.collapseil) {
							item.collapseil = false
						} else {
							this.$refs.humiture[index].getlistil(item.deviceSensorList[0].T_id)
							item.collapseil = true
						}
					}
				})
				this.$forceUpdate()
			},
			change(e) {
				if (e[0].status == 'open') {
					this.humitureList.forEach((item, index) => {
						this.$refs.humiture[index].getlistil(item.deviceSensorList[0].T_id)
					})
				}
			},
			getServerData() {
				this.$api.post('/api/waybill-task/newest-locus', {
					waybillNo: this.waybillNo,
				}).then((res) => {
					if (res.code == 200) {
						this.opts.title.name = res.data.T_t + '℃'
						this.opts.extra.gauge.startNumber = res.data.T_tl
						this.opts.extra.gauge.endNumber = res.data.T_tu
						this.opts1.title.name = res.data.T_rh + '℃'
						this.opts1.extra.gauge.startNumber = res.data.T_rhl
						this.opts1.extra.gauge.endNumber = res.data.T_rhu
						let arr = (res.data.T_t - res.data.T_tl) / (res.data.T_tu - res.data.T_tl)
						let arr1 = (res.data.T_rh - res.data.T_rhl) / (res.data.T_rhu - res.data.T_rhl)
						let value = {
							categories: [{
								"value": 0.2,
								"color": "#1890ff"
							}, {
								"value": 0.8,
								"color": "#2fc25b"
							}, {
								"value": 1,
								"color": "#f04864"
							}],
							series: [{
								data: arr.toFixed(1)
							}]
						};
						let value1 = {
							categories: [{
								"value": 0.2,
								"color": "#1890ff"
							}, {
								"value": 0.8,
								"color": "#2fc25b"
							}, {
								"value": 1,
								"color": "#f04864"
							}],
							series: [{
								data: arr1.toFixed(1)
							}]
						};
						this.chartData = JSON.parse(JSON.stringify(value));
						this.chartData1 = JSON.parse(JSON.stringify(value1));
					}
				})
			},
			// 选择某段温湿度数据
			selectChangeil(value) {
				this.humitureList.forEach((item, index) => {
					if (value.id == item.id) {
						if (value.isChecked) {
							item.isChecked = false
						} else {
							item.isChecked = true
						}
					}
				})
				this.selectChange(value.id)
				this.$forceUpdate()
			},
			// 选择打印
			selectChange(stingId) {
				const result = this.checkboxValue
				const index = result.indexOf(stingId)
				if (index > -1) {
					result.splice(index, 1)
				} else {
					result.push(stingId)
				}
				this.checkboxValue = result
			},
			// 时间范围选择
			changeDatetime(value, item) {
				this.humitureList.forEach((item1, index) => {
					if (item1.id == item.id) {
						setTimeout(() => {
							item.datetimeRange = value
							// this.getDatas()
							this.$refs.humiture[index].getlistil(item.deviceSensorList[0].T_id)
						}, 500)
					}
				})
				this.$forceUpdate()
			},
			getDateTime(date, addZero = true) {
				return `${this.getDate(date, addZero)} ${this.getTime(date, addZero)}`
			},
			getDate(date, addZero = true) {
				date = new Date(date)
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${addZero ? this.addZero(month) : month}-${addZero ? this.addZero(day) : day}`
			},
			getTime(date, addZero = true) {
				date = new Date(date)
				const hour = date.getHours()
				const minute = date.getMinutes()
				const second = date.getSeconds()
				return this.hideSecond ?
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}` :
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}:${addZero ? this.addZero(second) : second}`
			},
			addZero(num) {
				if (num < 10) {
					num = `0${num}`
				}
				return num
			}
		}
	}
</script>

<style lang="scss">
	.card_particulars {
		display: flex;
		flex-direction: column;
		padding-top: 20rpx;
		margin: 30rpx 20rpx 20rpx 20rpx;
		border-radius: 20rpx;
		background-color: #fff;
	}

	.card_describe {
		padding-left: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #EBEEF5;
	}

	.describe_title {
		font-size: 30rpx;
		font-weight: 600;
	}

	.describe_time {
		font-size: 28rpx;
	}

	.humiture_details {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
	}

	.title_blue {
		color: #2979ff;
		margin-right: 10rpx;
	}

	.title_details {
		font-size: 28rpx;
	}

	::v-deep .u-collapse-item__content__text {
		padding: 0rpx 0rpx 30rpx 0rpx;
	}

	::v-deep .u-line {
		display: none;
	}

	.card_qiucharts {
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.card_echart {
		width: 80%;
		height: 500rpx;
	}

	.card_echart {
		width: 80%;
		height: 500rpx;
	}

	.dateTime_card ::v-deep .icon-calendar {
		display: none;
	}

	.card_btn {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-top: 20rpx;
		background-color: #fff;
		padding-bottom: constant(safe-area-inset-bottom); //兼容 IOS<11.2
		padding-bottom: env(safe-area-inset-bottom); //兼容 IOS>11.2
	}
</style>