<template>
	<el-dialog v-model="state.dialogVisible"  width="70%" draggable title="编辑预警设置" @close="close" append-to-body destroy-on-close>
		<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef" :disabled="loading">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<p class="border-title mb10">基本信息</p>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="预警名称" prop="earlyWarningName" :rules="[{ required: true, message: '请填写预警名称', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.earlyWarningName" placeholder="请填写预警名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="预警级别" prop="earlyWarningLevelValue" :rules="[{ required: true, message: '请选择预警级别', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.earlyWarningLevelValue" placeholder="请选择预警级别" @change="selectLevel" clearable>
							<el-option v-for="item in earlyWarningLevel" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="预警类型" prop="earlyWarningTypeValue" :rules="[{ required: true, message: '请选择预警类型', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.earlyWarningTypeValue" placeholder="请选择预警类型" @change="selectType" clearable>
							<el-option v-for="item in earlyWarningType" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="频率" prop="frequency" :rules="[{ required: true, message: '请选择频率', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.frequency" placeholder="请选择频率" clearable>
							<el-option v-for="item in eFrequency" :value="item.key" :key="item.key" :label="item.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="状态" prop="isEnable" :rules="[{ required: false, message: '请选择状态', trigger: 'change' }]">
						<el-switch v-model="state.ruleForm.isEnable" inline-prompt active-text="启用" inactive-text="禁用" />
					</el-form-item>
				</el-col>
				<el-col>
					<p class="border-title mb10">预警规则</p>
				</el-col>
				<el-col>
					<el-form-item prop="earlyWarningRules" :rules="[{ required: false, message: '请选择预警规则', trigger: 'change' }]">
						<template #label>
							<div style="height: 32px; line-height: 32px">
								<el-button type="primary" @click="onPlus" link>新增规则<SvgIcon name="ele-Plus" /></el-button>
							</div>
						</template>
						<el-row v-for="(item, index) in state.ruleForm.earlyWarningRules" :key="index" :gutter="10" class="w100 mb20">
							<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
								<el-form-item
									label="敏感词"
									:prop="`earlyWarningRules.${index}.sensitiveWord`"
									:rules="[{ required: true, message: '请填写敏感词', trigger: 'change' }]"
									label-width="70px"
								>
									<el-select-v2 v-model="item.sensitiveWord" :options="sensitiveWords" placeholder="请选择敏感词" clearable filterable>
									</el-select-v2>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
								<el-form-item
									label="出现次数"
									:prop="`earlyWarningRules.${index}.compareType`"
									:rules="[{ required: true, message: '请选择出现次数', trigger: 'change' }]"
									label-width="80px"
								>
									<el-select v-model="item.compareType" placeholder="请选择出现次数" clearable>
										<el-option v-for="item in eCompareType" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="4" :xl="4">
								<el-form-item
									label=""
									:prop="`earlyWarningRules.${index}.times`"
									:rules="[{ required: true, message: '请填写次数', trigger: 'blur' }]"
									label-width="0px"
								>
									<el-input-number v-model="item.times" :min="1" :max="99" :precision="0">
										<template #suffix>
											<span>次</span>
										</template>
									</el-input-number>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="4" :xl="4">
								<el-form-item
									label="排序"
									:prop="`earlyWarningRules.${index}.sort`"
									:rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]"
									label-width="50px"
								>
									<el-input-number v-model="item.sort" :min="1" :precision="0">
									</el-input-number>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="4" :xl="4">
								<div class="flex">
									<el-form-item
										label=""
										:prop="`earlyWarningRules.${index}.nextWhere`"
										:rules="[{ required: true, message: '请选择', trigger: 'change' }]"
										label-width="0px"
										v-if="index < state.ruleForm.earlyWarningRules.length - 1"
									>
										<el-select v-model="item.nextWhere" style="width: 100px;" clearable>
											<el-option v-for="item in eNextWhere" :value="item.key" :key="item.key" :label="item.value" />
										</el-select>
									</el-form-item>
									<el-button link type="danger" @click="onDelete(index)" v-if="index" class="ml10"><SvgIcon name="ele-Delete" /></el-button>
								</div>
							</el-col>
						</el-row>
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="预警原因" prop="earlyWarningRemark" :rules="[{ required: false, message: '请填写预警原因', trigger: 'blur' }]">
						<el-input
							v-model="state.ruleForm.earlyWarningRemark"
							placeholder="请填写预警原因"
							type="textarea"
							:autosize="{ minRows: 4, maxRows: 8 }"
						></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { editEarlySetting, getEarlySettingBaseData, getEarlySettingDetail } from '@/api/early/setting';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		earlyWarningName: null, // 预警名称
		earlyWarningLevelName: null, // 预警级别
		earlyWarningLevelValue: null, // 预警级别
		earlyWarningTypeName: null, // 预警类型
		earlyWarningTypeValue: null, // 预警类型
		frequency: null, // 频率
		isEnable:true, // 是否启用
		earlyWarningRules: [
			{
				sensitiveWord: null,
				compareType: null,
				times: null,
				nextWhere:null,
				sort:1
			},
		], // 预警规则
		earlyWarningRemark: null, // 预警原因
	},
});
let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async (Id: string) => {
	state.dialogVisible = true;
	loading.value = true;
	try {
		const { result } = await getEarlySettingDetail(Id);
		state.ruleForm = result;
		loading.value = false;
		queryBaseInfo();
	} catch (error) {
		loading.value = false;
		console.log(error);
	}
};
// 获取基础信息
const earlyWarningLevel = ref<EmptyArrayType>([]); // 预警级别
const earlyWarningType = ref<EmptyArrayType>([]); // 预警类型
const eFrequency = ref<EmptyArrayType>([]); // 频率
const eCompareType = ref<EmptyArrayType>([]); // 比较类型
const sensitiveWords = ref<EmptyArrayType>([]); // 敏感词
const eNextWhere = ref<EmptyArrayType>([]); // 下一步
const queryBaseInfo = () => {
	getEarlySettingBaseData().then((res) => {
		earlyWarningLevel.value = res.result.earlyWarningLevel ?? [];
		earlyWarningType.value = res.result.earlyWarningType ?? [];
		eFrequency.value = res.result.eFrequency ?? [];
		eCompareType.value = res.result.eCompareType ?? [];
		eNextWhere.value = res.result.eNextWhere ?? [];
		sensitiveWords.value =
			res.result.sensitiveWords.map((item: any) => {
				return {
					label: item,
					value: item,
				};
			}) ?? [];
	});
};
// 选择级别
const selectLevel = (val: string) => {
	const item = earlyWarningLevel.value.find((item) => item.dicDataValue === val);
	state.ruleForm.earlyWarningLevelName = item?.dicDataName;
};
// 选择类型
const selectType = (val: string) => {
	const item = earlyWarningType.value.find((item) => item.dicDataValue === val);
	state.ruleForm.earlyWarningTypeName = item?.dicDataName;
};
// 添加规则
const onPlus = () => {
	state.ruleForm.earlyWarningRules.push({
		sensitiveWord: null,
		compareType: null,
		times: null,
		sort:state.ruleForm.earlyWarningRules.length+1
	});
};
// 删除规则
const onDelete = (index: number) => {
	state.ruleForm.earlyWarningRules.splice(index, 1);
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.ruleForm.earlyWarningRules = [
		{
			sensitiveWord: null,
			compareType: null,
			times: null,
			sort:1
		},
	];
};
// 新增
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
		const request = {
			...state.ruleForm,
		};
		editEarlySetting(request)
			.then(() => {
				ElMessage({
					message: '修改成功',
					type: 'success',
				});
				loading.value = false;
				closeDialog();
				emit('updateList');
			})
			.catch(() => {
				// 新增失败
				loading.value = false;
				closeDialog();
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
