<template>
	<xn-form-container
		:title="formData.id ? '编辑点位' : '新增点位'"
		:width="'800px'"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			layout="inline"
			:label-col="{ style: { width: '110px', justifyContent: 'end' } }"
		>
			<a-row :gutter="10">
				<!-- 选择点位 -->
				<div class="dict">
					<span>点位标签：</span>
					<a-radio-group
						v-model:value="pointName"
						:options="pointOptions"
						option-type="button"
						@change="pointNameChange(pointName)"
					>
					</a-radio-group>
				</div>

				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
					<a-form-item label="监测对象" name="monitorTargetId">
						<a-select
							ref="select"
							v-model:value="formData.monitorTargetId"
							:options="monitorTargetOptions"
							placeholder="请选择监测对象"
							:field-names="{ label: 'name', value: 'id' }"
							disabled
						/>
					</a-form-item>
				</a-col>
				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
					<a-form-item label="点位名称" name="name">
						<a-input :value="formData.name" placeholder="请输入点位名称" allow-clear @input="nameInput" :max="20" />
					</a-form-item>
				</a-col>
				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
					<a-form-item label="传感器类型" name="sensorType">
						<a-select
							ref="select"
							v-model:value="formData.sensorType"
							:options="sensorOptions"
							placeholder="请选择传感器类型"
							@change="sensorTypeChange"
						/>
					</a-form-item>
				</a-col>

				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
					<a-form-item label="监测设备" name="monitorDeviceId">
						<a-select
							ref="select"
							v-model:value="formData.monitorDeviceId"
							:options="memListOptions"
							placeholder="请选择监测设备"
							:field-names="{ label: 'deviceName', value: 'id' }"
							@change="monitorDeviceIdChange"
						/>
					</a-form-item>
				</a-col>

				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="formData.monitorDeviceId">
					<a-form-item label="传感器编号" name="sensorCode">
						<a-input v-model:value="formData.sensorCode" disabled placeholder="请输入传感器编号" allow-clear />
					</a-form-item>
				</a-col>

				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="formData.monitorDeviceId">
					<a-form-item label="传感器路数" name="sensorRoute">
						<a-radio-group v-model:value="formData.sensorRoute">
							<a-radio-button v-for="i in sensorRouteMax" :key="i" :value="i" :disabled="isRouteDisabled(i)">
								{{ i }}路
							</a-radio-button>
						</a-radio-group>
					</a-form-item>
				</a-col>

				<!-- 报警接收人 -->
				<a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<a-form-item label="报警接收人" name="alarmUsers">
						<a-checkbox-group v-model:value="formData.alarmUsers" name="checkboxgroup">
							<a-checkbox
								v-for="option in alarmUsersOptions"
								:key="option.openId"
								:value="option.openId"
								:label="option.nickName"
							>
								{{ option.nickName }}
							</a-checkbox>
						</a-checkbox-group>
					</a-form-item>
				</a-col>

				<!-- 选择冰箱型号 -->
				<div class="dict" v-if="formData.sensorType && formData.monitorDeviceId">
					<span>冰箱型号：</span>
					<a-radio-group v-model:value="fridgeName" option-type="button" @change="fridgeNameChange(fridgeName)">
						<a-radio-button
							v-for="e in filteredFridges"
							:key="e.value"
							:value="e.value"
							:label="e.label"
							:disabled="e.disabled"
						>
							<database-outlined /> {{ e.label }}</a-radio-button
						>
					</a-radio-group>
				</div>

				<div
					class="form_item"
					v-if="formData.sensorType == 'W' || formData.sensorType == 'WS' || formData.sensorType == 'WSC'"
				>
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="温度上限" name="temperatureUp">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.temperatureUp"
								placeholder="请输入温度上限"
								allow-clear
								:min="currentMonitorDevice.temperatureDown"
								:max="currentMonitorDevice.temperatureUp"
								style="width: 100%"
								:disabled="!currentMonitorDevice.temperatureUp"
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="温度下限" name="temperatureDown">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.temperatureDown"
								placeholder="请输入温度下限"
								allow-clear
								:min="currentMonitorDevice.temperatureDown"
								:max="currentMonitorDevice.temperatureUp"
								style="width: 100%"
								:disabled="!currentMonitorDevice.temperatureDown"
							/>
						</a-form-item>
					</a-col>
				</div>

				<div class="form_item" v-if="formData.sensorType == 'WS' || formData.sensorType == 'WSC'">
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="湿度上限" name="humidityUp">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.humidityUp"
								placeholder="请输入湿度上限"
								allow-clear
								:min="currentMonitorDevice.humidityDown"
								:max="currentMonitorDevice.humidityUp"
								style="width: 100%"
								:disabled="!currentMonitorDevice.humidityUp"
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="湿度下限" name="humidityDown">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.humidityDown"
								placeholder="请输入湿度下限"
								allow-clear
								:min="currentMonitorDevice.humidityDown"
								:max="currentMonitorDevice.humidityUp"
								style="width: 100%"
								:disabled="!currentMonitorDevice.humidityDown"
							/>
						</a-form-item>
					</a-col>
				</div>

				<div class="form_item" v-if="formData.sensorType == 'WSC'">
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="CO2上限" name="co2Up">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.co2Up"
								placeholder="请输入CO2上限"
								allow-clear
								:max="currentMonitorDevice.co2Up"
								:min="currentMonitorDevice.co2Down"
								style="width: 100%"
								:disabled="!currentMonitorDevice.co2Up"
							/>
						</a-form-item>
					</a-col>
					<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<a-form-item label="CO2下限" name="co2Down">
							<a-input-number
								id="inputNumber"
								v-model:value="formData.co2Down"
								placeholder="请输入CO2下限"
								allow-clear
								:max="currentMonitorDevice.co2Up"
								:min="currentMonitorDevice.co2Down"
								style="width: 100%"
								:disabled="!currentMonitorDevice.co2Down"
							/>
						</a-form-item>
					</a-col>
				</div>

				<a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<a-form-item label="勿扰设置">
						<a-time-range-picker v-model:value="formData.time" value-format="HH:mm:ss" style="width: 80%" show-time />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>

		<template #footer>
			<a-button class="xn-mr8" @click="onClose">取消</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { message } from 'ant-design-vue'
	import { debounce } from 'lodash-es'

	import tool from '@/utils/tool'
	import { required } from '@/utils/formRules'
	import locationApi from '@/api/basicset/locationApi.js'
	import setupApi from '@/api/basicset/setupApi'
	import memApi from '@/api/basicset/memApi'
	const emit = defineEmits({ successful: null })
	const visible = ref(false) // 默认是关闭状态
	const formRef = ref()
	const formData = ref({ alarmUsers: [], time: [] }) // 表单数据
	const pointOptions = tool.dictList('MONITORPOINT') // 点位名称
	const pointName = ref('上层')
	const currentMonitorObj = ref({}) //当前的监测对象
	const sensorOptions = tool.dictList('SENSORTYPE') // 传感器类型
	const alarmUsersOptions = ref([]) // 报警接收人数据
	const fridgeOptions = tool.dictList('REFRIGERATORSMODEL') // 冰箱型号
	const monitorTargetOptions = ref([]) // 监测对象
	const memListOptions = ref([]) // 监测设备
	const currentMonitorDevice = ref({}) //当前的监测设备

	const sensorRouteMax = ref(1) //传感器最大值默认1

	// 默认要校验的
	const formRules = {
		name: [required('请输入点位名称')],
		monitorTargetId: [required('请选择监测对象')],
		monitorDeviceId: [required('请选择监测设备')],
		sensorType: [required('请选择传感器类型')],
		sensorRoute: [required('请输入传感器路数')],
		alarmUsers: [required('请选择报警接收人')],
		temperatureUp: [{ validator: validateTemperature, trigger: ['change', 'blur'] }],
		temperatureDown: [{ validator: validateTemperature, trigger: ['change', 'blur'] }],
		humidityUp: [{ validator: validateHumidity, trigger: ['change', 'blur'] }],
		humidityDown: [{ validator: validateHumidity, trigger: ['change', 'blur'] }],
		co2Up: [{ validator: validateCo2, trigger: ['change', 'blur'] }],
		co2Down: [{ validator: validateCo2, trigger: ['change', 'blur'] }]
	}

	// 温度上下限校验
	function validateTemperature(rule, value, callback) {
		if (rule.field == 'temperatureDown') {
			if (formData.value.temperatureUp !== null && value >= formData.value.temperatureUp) {
				callback(new Error('温度下限不能大于或等于温度上限：' + formData.value.temperatureUp))
			} else {
				callback()
			}
		} else if (rule.field == 'temperatureUp') {
			if (formData.value.temperatureDown !== null && value <= formData.value.temperatureDown) {
				callback(new Error('温度上限不能小于或等于温度下限：' + formData.value.temperatureDown))
			} else {
				callback()
			}
		}
	}

	// 湿度上下限校验
	function validateHumidity(rule, value, callback) {
		if (rule.field == 'humidityDown') {
			if (formData.value.humidityUp !== null && value >= formData.value.humidityUp) {
				callback(new Error('湿度下限不能大于或等于湿度上限：' + formData.value.humidityUp))
			} else {
				callback()
			}
		} else if (rule.field == 'humidityUp') {
			if (formData.value.humidityDown !== null && value <= formData.value.humidityDown) {
				callback(new Error('湿度上限不能小于或等于湿度下限：' + formData.value.humidityDown))
			} else {
				callback()
			}
		}
	}

	// CO2上下限校验
	function validateCo2(rule, value, callback) {
		if (rule.field == 'co2Down') {
			if (formData.value.co2Up !== null && value >= formData.value.co2Up) {
				callback(new Error('CO2下限不能大于或等于CO2上限：' + formData.value.co2Up))
			} else {
				callback()
			}
		} else if (rule.field == 'co2Up') {
			if (formData.value.co2Down !== null && value <= formData.value.co2Down) {
				callback(new Error('CO2上限不能小于或等于CO2下限：' + formData.value.co2Down))
			} else {
				callback()
			}
		}
	}

	// 打开抽屉
	const onOpen = (type, record) => {
		setupListData(type, record)
		memListData()
		visible.value = true
		if (!record) {
			formData.value = ref({ alarmUsers: [], time: [] })
		}
	}

	// 选中的点位标签
	const pointNameChange = (val) => {
		pointName.value = val
		formData.value.name = currentMonitorObj.value.name + '-' + pointName.value
	}

	// 选中的冰箱标签
	const fridgeNameChange = (val) => {
		const data = fridgeRanges.value[val]

		formData.value = {
			...formData.value,

			temperatureUp: data.up, //温度上限
			temperatureDown: data.down //温度下限
		}
	}

	// 获取监测对象
	const setupListData = (type, record) => {
		setupApi
			.setupList({ isAll: false })
			.then((res) => {
				monitorTargetOptions.value = res || []
				currentMonitorObj.value = monitorTargetOptions.value.find((item) => item.id === record.monitorTargetId) //当前的监测对象
				alarmUsersOptions.value = currentMonitorObj.value.alarmUsers || [] //报警接收人
			})
			.finally(() => {
				formData.value = Object.assign({}, record)

				if (type == 'add') {
					formData.value.name = currentMonitorObj.value.name + '-' + pointName.value
				} else {
					formData.value.time = [
						formData.value.ignoreStartTime ? formData.value.ignoreStartTime : null,
						formData.value.ignoreEndTime ? formData.value.ignoreEndTime : null
					]

					if (formData.value.alarmUsers && formData.value.alarmUsers.length > 0) {
						formData.value.alarmUsers = formData.value.alarmUsers.map((item) => item.openId)
					}
					memListData(formData.value.sensorType)
				}
			})
	}

	// 名称输入
	const nameInput = (e) => {
		const val = e.target.value
		if (!val.startsWith(formData.value.name)) {
			formData.value.name = formData.value._name
			message.warning({
				content: '名称必须以 "监测对象名称" + ' + pointName.value + ' 开头',
				key: 'name'
			})
		} else {
			formData.value.name = val
		}
	}

	// 选中传感器类型
	const sensorTypeChange = (value) => {
		if (value) {
			memListData(value)
			monitorDeviceIdChange()
		}
	}

	// 监测设备通过传感器类型来获取， sensorType可为空
	const memListData = (value) => {
		memApi.memList({ isAll: false, sensorType: value }).then((res) => {
			memListOptions.value = res || []
		})
	}

	// 选中监测设备
	const monitorDeviceIdChange = (value) => {
		fridgeName.value = null
		if (value) {
			askRegionByDeviceIdData(value)
			const data = memListOptions.value.find((item) => item.id === value)
			currentMonitorDevice.value = data //选中的监测设备
			formData.value = {
				...formData.value,
				sensorCode: data.deviceCode, //传感器编号
				modelName: data.modelName, //监测设备型号
				deviceCode: data.deviceCode, //冷链编号
				temperatureUp: data.temperatureUp, //温度上限
				temperatureDown: data.temperatureDown, //温度下限
				humidityUp: data.humidityUp, //湿度上限
				humidityDown: data.humidityDown, //湿度下限
				co2Up: data.co2Up, //CO2上限
				co2Down: data.co2Down //CO2下限
			}

			sensorRouteMax.value = data.sensorCount //传感器路数的最大值
			isFridgeDisabled()
		} else {
			// 清理掉监测设备的一些信息
			currentMonitorDevice.value = {}
			sensorRouteMax.value = 1
			formData.value = {
				...formData.value,
				monitorDeviceId: null, //监测设备
				sensorRoute: null, //传感器路数
				sensorCode: null, //传感器编号
				modelName: null, //监测设备型号
				deviceCode: null, //冷链编号
				temperatureUp: null, //温度上限
				temperatureDown: null, //温度下限
				humidityUp: null, //湿度上限
				humidityDown: null, //湿度下限
				co2Up: null, //CO2上限
				co2Down: null //CO2下限
			}
		}
	}

	const fridgeName = ref() //选择的冰箱型号
	const fridgeRanges = ref({
		'-80': { up: -70, down: -80 },
		'-40': { up: -30, down: -40 },
		4: { up: 14, down: 4 },
		'-196': { up: -186, down: -196 }
	})
	const filteredFridges = ref([])
	// 判断 当前的监测设备 的温度范围是否在该冰箱的温度范围内
	const isFridgeDisabled = () => {
		console.log(currentMonitorDevice.value.temperatureUp, currentMonitorDevice.value.temperatureDown)
		filteredFridges.value = fridgeOptions.map((fridge) => {
			const { up, down } = fridgeRanges.value[fridge.value]
			const isDisabled =
				up < currentMonitorDevice.value.temperatureDown || down > currentMonitorDevice.value.temperatureUp

			return {
				...fridge,
				disabled: isDisabled
			}
		})
	}

	const useSensorRoute = ref([]) //已使用的传感器路数
	// 根据检测设备id获取已使用的路数
	const askRegionByDeviceIdData = (value) => {
		if (value) {
			memApi.getRegionByDeviceIdData({ deviceId: value }).then((res) => {
				useSensorRoute.value = res
			})
		}
	}

	// 检查该路是否已被禁用
	const isRouteDisabled = (route) => {
		// 通过遍历useSensorRoute中的数据，判断该路是否已被占用
		return useSensorRoute.value.some((item) => item.sensorRoute === route)
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				const parameter = {
					...formData.value,
					alarmUsers: alarmUsersOptions.value.filter((user) => formData.value.alarmUsers.includes(user.openId)),
					ignoreStartTime: formData.value.time && formData.value.time.length ? formData.value.time[0] : null,
					ignoreEndTime: formData.value.time && formData.value.time.length ? formData.value.time[1] : null
				}
				delete parameter.time
				locationApi.submitForm(parameter, formData.value.id).then(() => {
					onClose()
					emit('successful')
				})
			})
			.catch((error) => {
				console.log(error)
			})
	}

	// 关闭抽屉
	const onClose = () => {
		memListOptions.value = []
		currentMonitorObj.value = {}
		pointName.value = '上层'
		fridgeName.value = null

		formRef.value.resetFields()
		visible.value = false
	}

	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>

<style lang="less" scoped>
	.dict {
		width: 100%;
		padding: 0 10px 0px 45px;
		:deep(.ant-radio-button-wrapper) {
			margin: 5px 5px 10px 0px;
		}
		:deep(.ant-radio-button-wrapper-checked) {
			color: #2b61ff;
			background-color: #e6f3ff;
		}
	}
	:deep(.ant-form-item) {
		width: 100%;
		margin-bottom: 10px;
	}

	.form_item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
	}
</style>
