<template>
	<xn-form-container title="监测点配置" :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">
				<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="请选择监控对象"
						/>
					</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 v-model:value="formData.name" placeholder="请输入点位名称" allow-clear />
					</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="请选择监控设备"
							@change="monitorDeviceIdChange"
						/>
					</a-form-item>
				</a-col>

				<a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
					<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">
					<a-form-item label="传感器路数" name="sensorRoute">
						<a-input-number
							v-model:value="formData.sensorRoute"
							style="width: 100%"
							:min="1"
							:max="sensorRouteMax"
							placeholder="请输入传感器路数"
						/>
					</a-form-item>
				</a-col>

				<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="temperatureMax.downMax"
								:max="temperatureMax.upMax"
								style="width: 100%"
								:disabled="temperatureMax.upMax == null || temperatureMax.upMax == undefined"
							/>
						</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="temperatureMax.downMax"
								:max="temperatureMax.upMax"
								style="width: 100%"
								:disabled="!temperatureMax.downMax == null || temperatureMax.downMax == undefined"
							/>
						</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="humidityMax.downMax"
								:max="humidityMax.upMax"
								style="width: 100%"
								:disabled="!humidityMax.upMax"
							/>
						</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="humidityMax.downMax"
								:max="humidityMax.upMax"
								style="width: 100%"
								:disabled="!humidityMax.downMax"
							/>
						</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="co2Max.upMax"
								style="width: 100%"
							/>
						</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="co2Max.downMax"
								style="width: 100%"
							/>
						</a-form-item>
					</a-col>
				</div>
			</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 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() // 表单数据
	const sensorOptions = tool.dictList('SENSORTYPE') // 传感器类型
	const monitorTargetOptions = ref([]) // 监控对象
	const memListOptions = ref([]) // 监控设备数据

	const temperatureMax = ref({ upMax: Infinity, downMax: Infinity }) // 温度最大值
	const humidityMax = ref({ upMax: Infinity, downMax: Infinity }) // 湿度最大值
	const co2Max = ref({ upMax: Infinity, downMax: Infinity }) // CO2最大值

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

	// 默认要校验的
	const formRules = {
		name: [required('请输入区域名称')],
		monitorTargetId: [required('请选择监控对象')],
		monitorDeviceId: [required('请选择监控设备')],
		sensorType: [required('请选择传感器类型')],
		sensorRoute: [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('温度下限不能大于或等于温度上限'))
			} else {
				callback()
			}
		} else if (rule.field == 'temperatureUp') {
			if (formData.value.temperatureDown !== null && value <= formData.value.temperatureDown) {
				callback(new Error('温度上限不能小于或等于温度下限'))
			} else {
				callback()
			}
		}
	}

	// 湿度上下限校验
	function validateHumidity(rule, value, callback) {
		if (rule.field == 'humidityDown') {
			if (formData.value.humidityUp !== null && value >= formData.value.humidityUp) {
				callback(new Error('湿度下限不能大于或等于湿度上限'))
			} else {
				callback()
			}
		} else if (rule.field == 'humidityUp') {
			if (formData.value.humidityDown !== null && value <= formData.value.humidityDown) {
				callback(new Error('湿度上限不能小于或等于湿度下限'))
			} 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上限'))
			} else {
				callback()
			}
		} else if (rule.field == 'co2Up') {
			if (formData.value.co2Down !== null && value <= formData.value.co2Down) {
				callback(new Error('CO2上限不能小于或等于CO2下限'))
			} else {
				callback()
			}
		}
	}

	// 打开抽屉
	const onOpen = (record) => {
		setupListData()
		visible.value = true
		if (record) {
			formData.value = Object.assign({}, record)
			sensorType.value = formData.value.sensorType
			memListData(sensorType.value)
		} else {
			formData.value = {}
			memListData()
		}
	}
	// 获取监控对象
	const setupListData = () => {
		setupApi.setupList({ isAll: false }).then((res) => {
			monitorTargetOptions.value = (res || []).map((item) => {
				return {
					...item,
					value: item['id'],
					label: item['name']
				}
			})
		})
	}
	const sensorType = ref() //选中的传感器类型
	// 监控设备通过传感器类型来获取， sensorType可为空
	const memListData = (value) => {
		memApi.memList({ isAll: false, sensorType: value }).then((res) => {
			memListOptions.value = (res || []).map((item) => {
				return {
					...item,
					value: item['id'],
					label: item['deviceName'],
					modelName: item['modelName'],
					deviceCode: item['deviceCode'],
					sensorCount: item['sensorCount']
				}
			})
		})
	}

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

	// 选中监控设备
	const monitorDeviceIdChange = (value) => {
		if (value) {
			const data = memListOptions.value.find((item) => item.value === value)
			modeData.value = data

			formData.value.sensorCode = data.deviceCode //传感器编号
			formData.value.modelName = data.modelName //监控设备型号
			formData.value.deviceCode = data.deviceCode //冷链编号
			formData.value.temperatureUp = data.temperatureUp //温度上限
			formData.value.temperatureDown = data.temperatureDown //温度下限
			formData.value.humidityUp = data.humidityUp //湿度上限
			formData.value.humidityDown = data.humidityDown //湿度下限
			formData.value.co2Up = data.co2Up //CO2上限
			formData.value.co2Down = data.co2Down //CO2下限
			sensorRouteMax.value = data.sensorCount //传感器路数的最大值

			temperatureMax.value = {
				upMax: data.temperatureUp,
				downMax: data.temperatureDown
			}
			humidityMax.value = {
				upMax: data.humidityUp,
				downMax: data.humidityDown
			}
			co2Max.value = {
				upMax: data.co2Up,
				downMax: data.co2Down
			}
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		visible.value = false
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				locationApi.submitForm(formData.value, formData.value.id).then(() => {
					onClose()
					emit('successful')
				})
			})
			.catch((error) => {
				console.log(error)
			})
	}

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

<style lang="less" scoped>
	: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>
