<template>
	<div class="system-timeLimit-edit-container">
		<el-dialog v-model="state.dialogVisible" width="60%" draggable title="新增时限">
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="100px" scroll-to-error>
				<el-row :gutter="5">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="配置名称" prop="timeLimitName" :rules="[{ required: true, message: '请输入配置名称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.timeLimitName" placeholder="请输入配置名称" clearable max-length="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="业务名称" prop="workflowObj" :rules="[{ required: true, message: '请选择业务名称', trigger: 'change' }]">
							<el-select
								v-model="state.ruleForm.workflowObj"
								placeholder="请选择业务名称"
								style="width: calc(100% - 60px)"
								value-key="key"
								@change="
									(val) => {
										state.ruleForm.workflowCode = val.key;
										state.ruleForm.workflowName = val.value;
									}
								"
							>
								<el-option v-for="item in state.moduleOptions" :key="item.key" :label="item.value" :value="item" />
							</el-select>
							<el-tooltip placement="top-start" v-if="state.ruleForm.workflowCode === 'Order'">
								<SvgIcon name="ele-InfoFilled" size="24px" color="var(--el-color-primary)" class="ml15" />
								<template #content>
									说明：时限计算优先级依次为指定优先级、组合、时限最短。<br />
									若已配置指定参数优先级的，则先按指定的优先级计算办理期限；
									<br />无指定优先级的，默认按组合最短时限计算办理期限；<br />
									无组合配置的，则默认按已配置的参数最短时限计算办理期限；未配置时限的参数，默认为无时限要求。
								</template>
							</el-tooltip>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-collapse
				v-model="state.collapseArr"
				class="collapse-box mt20"
				style="border-top: none"
				v-loading="state.loading"
				v-if="state.ruleForm.workflowCode === 'Order'"
			>
				<p class="border-title mb10">参数信息</p>
				<!-- 参数多选 -->
				<div class="pl20 pr20">
					<el-checkbox-group v-model="state.parameterList" class="pd20">
						<el-row>
							<el-col v-for="(item, index) in state.baseData" :key="index" :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
								<el-checkbox :label="item" @change="(val) => parameterChange(val, item)">{{ item.name }}</el-checkbox>
							</el-col>
						</el-row>
					</el-checkbox-group>
					<el-collapse-item name="1">
						<template #title>
							<p class="pl10">
								<b class="font14">已选参数</b>
							</p>
						</template>
						<div class="parameter pl20 pr20">
							<!-- 已选列表 -->
							<div class="mt20 parameter-choose">
								<el-row>
									<el-col v-for="(item, index) in state.paramArr" :key="index" :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
										<div class="parameter-choose-one text-no-wrap" :class="{ active: item.active }" @click="chooseParameter(item)">
											{{ item.name }}<span v-if="item.paramValue.length">({{ item.paramValue.length }})</span>
										</div>
									</el-col>
								</el-row>
							</div>
							<!-- 参数表格 -->
							<el-table :data="state.currentParam.paramValue" class="mt20" v-if="state.currentParam">
								<el-table-column label="序号" type="index" width="70"></el-table-column>
								<el-table-column :label="state.currentParam.name" prop="paramTypeValue">
									<template #default="{ row }">
										<template v-if="state.currentParam.typeCode === 'HotPots'">
											<el-tree-select
												class="w100"
												v-model="row.paramTypeValue"
												filterable
												placeholder="请选择热点分类"
												:props="HotspotProps"
												lazy
												:load="load"
												node-key="id"
												check-strictly
												:render-after-expand="false"
												@node-click="
													(val, e) => {
														state.hotspotExternal = [];
														state.external = [];
														row.paramTypeName = val.hotSpotFullName;
														state.hotspotExternal = getParentId(e, state.external);
														row.hotParamParent = getParentId(e, state.external).join(',');
													}
												"
												:default-expanded-keys="state.hotspotExternal"
											/>
										</template>
										<template v-else>
											<el-select
												v-model="row.paramTypeObj"
												:placeholder="'请选择' + state.currentParam.name"
												value-key="key"
												class="w100"
												@change="
													(val) => {
														row.paramTypeValue = val.key;
														row.paramTypeName = val.value;
														getSelectedParams();
														getEnableAcceptType();
													}
												"
											>
												<el-option v-for="item in state.selectArray" :key="item.key" :label="item.value" :value="item" :disabled="item.disabled" />
											</el-select>
										</template>
									</template>
								</el-table-column>
								<el-table-column label="时限" prop="name">
									<template #default="{ row }">
										<el-input-number
											v-model="row.timeLimitValue"
											:min="1"
											@change="
												(val) => {
													getSelectedParams();
													getEnableAcceptType();
													if (row.timeLimitType !== 1) row.hour = val * 24;
													else row.hour = val;
												}
											"
											placeholder="请填写时限"
											class="w100"
										></el-input-number>
									</template>
								</el-table-column>
								<el-table-column label="单位" prop="name">
									<template #default="{ row }">
										<el-select
											v-model="row.hourObj"
											placeholder="请选择单位"
											class="w100"
											value-key="key"
											@change="
												(val) => {
													row.timeLimitType = val.key;
													if (val.key !== 1) row.hour = row.timeLimitValue * 24;
													else row.hour = row.timeLimitValue;
													row.timeLimitTypeName = val.value;
													getSelectedParams();
													getEnableAcceptType();
												}
											"
										>
											<el-option v-for="item in state.timeType" :key="item.key" :label="item.value" :value="item" />
										</el-select>
									</template>
								</el-table-column>
								<el-table-column align="center" width="100">
									<template #header>
										<el-button type="primary" @click="handleAdd"> 新增 </el-button>
									</template>
									<template #default="scope">
										<el-button @click="handleDelete(scope.row, scope.$index)" type="danger" text>删除</el-button>
									</template>
								</el-table-column>
							</el-table>
							<div class="mt20"></div>
						</div>
					</el-collapse-item>
					<el-collapse-item name="2">
						<template #title>
							<p class="pl10">
								<b class="font14">已配置参数</b>
							</p>
						</template>
						<div class="parameter-stop pd20">
							<el-row>
								<el-col v-for="(item, index) in state.paramSelect" :key="index" :xs="24" :sm="8" :md="8" :lg="6" :xl="4" :title="item.name">
									<div class="parameter-stop-one mb10 text-no-wrap" :class="{ active: item.active }" @click="selectParameter(item)">
										{{ item.name }}
									</div>
								</el-col>
							</el-row>
						</div>
					</el-collapse-item>
					<el-collapse-item name="3">
						<template #title>
							<p class="flex-center-align pl10">
								<b class="font14">指定优先级</b>
								<el-tooltip placement="top-start" content="选中已配置参数，可自定义优先级，参数越靠前优先级越高。" trigger="hover">
									<SvgIcon name="ele-QuestionFilled" size="16px" color="var(--el-color-info)" class="ml5"></SvgIcon>
								</el-tooltip>
							</p>
						</template>
						<div class="pd20">
							<draggable-list :list="state.priority" :force-fallback="true" animation="300" @end="onEnd" itemKey="id" class="parameter-sort">
								<template #item="item">
									<div class="parameter-sort-one" :title="item.element.timeLimitValue">
										<el-tag class="mr20"> {{ item.index + 1 }}. {{ item.element.name }} </el-tag>
									</div>
								</template>
							</draggable-list>
						</div>
					</el-collapse-item>
				</div>
			</el-collapse>
			<p class="border-title mb10 mt20" v-if="state.ruleForm.workflowCode === 'Order'">参数组合</p>
			<!-- 组合参数表格 -->
			<div class="pd20" v-if="state.ruleForm.workflowCode === 'Order'">
				<el-table :data="state.combination">
					<el-table-column label="序号" type="index" width="70"></el-table-column>
					<el-table-column label="组合名称" prop="combinationName">
						<template #default="{ row }">
							<el-input v-model="row.combinationName" placeholder="请填写组合名称" class="w100" max-length="30"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="参数" prop="combinationDisplayParam">
						<template #default="{ row }">
							<div class="flex-center-align">
								<span class="omit text-no-wrap" :title="row.combinationDisplayParam">{{ row.combinationDisplayParam }}</span>
								<el-button class="ml3" text title="配置参数" type="primary" @click="chooseCombination(row)">
									<SvgIcon name="ele-Edit" size="16px" />
								</el-button>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="时限" prop="timeLimitValue">
						<template #default="{ row }">
							<el-input-number
								v-model="row.timeLimitValue"
								:min="1"
								placeholder="请填写时限"
								class="w100"
								@change="
									(val) => {
										if (row.timeLimit !== 1) row.hour = val * 24;
										else row.hour = val;
									}
								"
							></el-input-number>
						</template>
					</el-table-column>
					<el-table-column label="单位" prop="hourObj">
						<template #default="{ row }">
							<el-select
								v-model="row.hourObj"
								value-key="key"
								placeholder="请选择单位"
								class="w100"
								@change="
									(val) => {
										row.timeLimit = val.key;
										if (val.key !== 1) row.hour = row.timeLimitValue * 24;
										else row.hour = row.timeLimitValue;
										row.timeLimitTypeName = val.value;
									}
								"
							>
								<el-option v-for="item in state.timeType" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column align="center" width="100">
						<template #header>
							<el-button type="primary" @click="combinationAdd"> 新增 </el-button>
						</template>
						<template #default="scope">
							<el-button @click="combinationDelete(scope.row, scope.$index)" type="danger" text>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onSubmit(ruleFormRef)" class="default-button">暂 存</el-button>
					<el-button type="primary" @click="onConfirm(ruleFormRef)">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="state.paramDialog" width="700" draggable title="参数选择">
			<el-form :model="state.paramForm" ref="paramFormRef" label-width="100px">
				<el-row :gutter="5">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="受理类型" prop="acceptType" :rules="[{ required: false, message: '请选择受理类型', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.acceptType"
								placeholder="请选择受理类型"
								class="w100"
								value-key="key"
								clearable
								@clear="clearCombinationParam('AcceptType')"
							>
								<el-option v-for="item in state.result.acceptType" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="热点分类" prop="hotspot" :rules="[{ required: false, message: '请选择热点分类', trigger: 'change' }]">
							<el-tree-select
								class="w100"
								v-model="state.paramForm.hotspot"
								filterable
								placeholder="请选择热点分类"
								:props="HotspotProps"
								lazy
								:load="load"
								node-key="id"
								check-strictly
								:render-after-expand="false"
								@node-click="getComHotspot"
								ref="hotspotComRef"
								:default-expanded-keys="state.hotspotExternalCom"
								clearable
								@clear="clearCombinationParam('HotPots')"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="来源渠道" prop="sourceChannel" :rules="[{ required: false, message: '请选择来源渠道', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.sourceChannel"
								placeholder="请选择来源渠道"
								class="w100"
								value-key="key"
								filterable
								clearable
								@clear="clearCombinationParam('SourceChannel')"
							>
								<el-option v-for="item in state.result.sourceChannel" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="来电人身份" prop="identityType" :rules="[{ required: false, message: '请选择来电人身份', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.identityType"
								placeholder="请选择来电人身份"
								class="w100"
								value-key="key"
								filterable
								clearable
								@clear="clearCombinationParam('IdentityType')"
							>
								<el-option v-for="item in state.result.identityType" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="工单类型" prop="orderType" :rules="[{ required: false, message: '请选择工单类型', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.orderType"
								placeholder="请选择工单类型"
								class="w100"
								value-key="key"
								filterable
								clearable
								@clear="clearCombinationParam('OrderType')"
							>
								<el-option v-for="item in state.result.orderType" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="证件类型" prop="certType" :rules="[{ required: false, message: '请选择证件类型类', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.certType"
								placeholder="请选择证件类型"
								class="w100"
								value-key="dicDataValue"
								filterable
								clearable
								@clear="clearCombinationParam('LicenceType')"
							>
								<el-option v-for="item in state.result.certType" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="紧急程度" prop="emergencyLevel" :rules="[{ required: false, message: '请选择紧急程度', trigger: 'change' }]">
							<el-select
								v-model="state.paramForm.emergencyLevel"
								placeholder="请选择紧急程度"
								class="w100"
								value-key="key"
								filterable
								clearable
								@clear="clearCombinationParam('EmergencyLevel')"
							>
								<el-option v-for="item in state.result.emergencyLevel" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="默认参数" prop="emergencyLevel" :rules="[{ required: false, message: '请选择默认参数', trigger: 'change' }]">
							<el-select v-model="state.paramForm.emergencyLevel" placeholder="请选择默认参数" class="w100" value-key="key" filterable>
								<el-option v-for="item in state.result.emergencyLevel" :key="item.key" :label="item.value" :value="item"  />
							</el-select>
						</el-form-item>
					</el-col> -->
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button class="default-button" @click="state.paramDialog = false">取 消</el-button>
					<el-button type="primary" @click="onConfirmCom">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="EditTimeLimit">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { guid } from '/@/utils/tools';
import { removeDuplicate } from '/@/utils/arrayOperation';
import DraggableList from 'vuedraggable';
import { hotSpotType } from '/@/api/business/order';
import { timeLimitDetail, timeLimitUpdate } from '/@/api/system/timeLimit';
import other from '/@/utils/other';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList', 'openDialog', 'closeDialog']);
const paramTypeNameType: any = {
	AcceptType: '受理类型',
	HotPots: '热点分类',
	SourceChannel: '来源渠道',
	IdentityType: '来电人身份',
	OrderType: '工单类型',
	LicenceType: '证件类型',
	EmergencyLevel: '紧急程度',
	DefaultTime: '默认参数',
};
// 定义变量内容
const ruleFormRef = ref<RefType>();
const state = reactive<any>({
	ruleForm: {},
	paramForm: {},
	paramDialog: false,
	dialogVisible: false,
	baseData: [], // 基础数据
	parameterList: [], //选择基础数据
	paramArr: [], //参数列表信息
	currentParam: null as any, // 当前参数
	collapseArr: ['1', '2', '3', '4'], //展开列表
	result: {}, //所有基础数据
	timeType: [], // 单位
	moduleOptions: [], // 业务名称
	selectArray: [], // 可选数据
	paramSelect: [], // 已配置的数据 （可选择）
	priority: [], // 排序参数
	combination: [], // 组合
	hotspotExternal: [], // 热点分类展开
	external: [],
	hotspotExternalCom: [], // 组合热点分类展开
	externalCom: [],
	loading: false,
	timeLimitId: null as any,
});

// 热点分类远程搜索
const HotspotProps = {
	label: 'hotSpotFullName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类懒加载
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	const res: any = await hotSpotType({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
const resetState = () => {
	state.parameterList = [];
	state.paramArr = [];
	state.currentParam = null;
	state.selectArray = [];
	state.paramSelect = [];
	state.priority = [];
	state.combination = [];
	state.hotspotExternal = [];
	state.external = [];
	state.hotspotExternalCom = [];
	state.externalCom = [];
};
// 打开弹窗
const openDialog = (val: any, baseData: any) => {
	state.dialogVisible = true;
	state.loading = true;
	resetState();
	ruleFormRef.value?.resetFields();
	const { baseData: stateBaseData = [], timeType = [], moduleOptions = [] } = baseData;
	state.result = baseData;
	state.baseData = stateBaseData; //基础数据
	state.timeType = timeType; //单位
	state.moduleOptions = moduleOptions; //业务名称
	state.timeLimitId = val.id;
	timeLimitDetail(val.id)
		.then((res: any) => {
			// 表单数据
			const { timeLimitName, workflowCode, workflowName } = res.result;
			state.ruleForm.timeLimitName = timeLimitName;
			state.ruleForm.workflowObj = {
				key: workflowCode,
				value: workflowName,
			};
			state.ruleForm.workflowCode = workflowCode;
			state.ruleForm.workflowName = workflowName;
			// 参数
			for (const i of res.result.paramArr) {
				for (const j of state.baseData) {
					if (i.paramType === j.typeCode) {
						state.parameterList.push({
							...j,
						});
						state.parameterList = removeDuplicate(state.parameterList, 'typeCode');
						parameterChange(true, j);
					}
				}
				for (const k of state.paramArr) {
					if (i.paramType === k.paramType) {
						k.paramValue.push({
							paramTypeObj: {
								key: i.paramTypeValue,
								value: i.paramTypeName,
							},
							hourObj: {
								key: i.timeLimitType,
							},
							...i,
						});
						if (i.hotParamParent) state.hotspotExternal = i.hotParamParent.split(',');
					}
				}
			}
			// 配置参数
			getSelectedParams();
			for (let i of state.paramSelect) {
				for (let j of res.result.priority) {
					if (i.id === j.code) {
						i.active = true;
					}
				}
			}
			state.priority = res.result.priority;
			state.priority = state.priority.map((v: any) => {
				return {
					...v,
					name: paramTypeNameType[v.paramType] + '-' + v.paramTypeName,
				};
			});

			// 组合
			state.combination = res.result.combination;
			state.combination = state.combination.map((v: any) => {
				return {
					...v,
					hourObj: {
						key: v.timeLimit,
					},
				};
			});

			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
			state.dialogVisible = false;
		});
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
	emit('closeDialog');
};
// 选择参数
const parameterChange = (value: string | number | boolean, item: any) => {
	let arr: any = other.deepClone(state.parameterList);
	state.paramArr = arr.map((v: any) => {
		let j = state.paramArr.find((j: any) => j.paramType === v.typeCode);
		if (j) {
			v.paramValue = j.paramValue;
		}
		return {
			...v,
			paramType: v.typeCode,
			paramValue: v.paramValue ?? [],
		};
	});
	if (value) {
		//新增选中新增的
		chooseParameter(item);
	} else {
		// 取消选中最后一个
		chooseParameter(state.paramArr[state.paramArr.length - 1]);
	}
};
// 选择参数 切换当前
const chooseParameter = (item: any) => {
	switch (item?.typeCode) {
		case 'AcceptType':
			state.selectArray = state.result.acceptType;
			break;
		case 'HotPots': // 热点
			state.selectArray = [];
			break;
		case 'SourceChannel':
			state.selectArray = state.result.sourceChannel;
			break;
		case 'IdentityType':
			state.selectArray = state.result.identityType;
			break;
		case 'OrderType':
			state.selectArray = state.result.orderType;
			break;
		case 'LicenceType': //证件类型
			state.selectArray = state.result.certType.map((item: any) => {
				return {
					key: item.dicDataValue,
					value: item.dicDataName,
				};
			});
			break;
		case 'EmergencyLevel':
			state.selectArray = state.result.emergencyLevel;
			break;
		case 'DefaultTime': //默认参数
			state.selectArray = [];
			break;
		default:
			break;
	}
	// state.selectArray = state.result[state.currentParam.typeCode];
	state.paramArr.forEach((v: any) => {
		if (item.typeCode === v.paramType) {
			v.active = true;
			state.currentParam = v;
		} else {
			v.active = false;
		}
	});
	getEnableAcceptType();
	getSelectedParams();
};
// 新增
const handleAdd = () => {
	state.currentParam.paramValue.push({
		id: guid(),
		paramType: state.currentParam.paramType,
		paramTypeName: '',
		paramTypeValue: '',
		timeLimitValue: 1,
		hour: '',
	});
	getEnableAcceptType();
	getSelectedParams();
};
// 删除
const handleDelete = (row: any, index: number) => {
	ElMessageBox.confirm(`确定要删除?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			state.currentParam.paramValue.splice(index, 1);
			getEnableAcceptType();
			getSelectedParams();
		})
		.catch(() => {});
};
// 获取可用的数组
const getEnableAcceptType = () => {
	if (state.currentParam?.paramValue.length) {
		const array = state.currentParam.paramValue.map((v: any) => v.paramTypeValue);
		state.selectArray.forEach((v: any) => {
			v.disabled = array.includes(v.key);
		});
	}
};
// 获取已经配置的列表
const getSelectedParams = () => {
	const arr = state.paramArr.flatMap((i: any) => i.paramValue).filter((j: any) => j.paramTypeName && j.id && j.timeLimitType);
	state.paramSelect = arr.map((v: any) => {
		const { id, active } = v;
		const selected = state.paramSelect.find((j: any) => j.id === id);
		return {
			...v,
			active: selected?.active ?? false,
			name: paramTypeNameType[v.paramType] + '-' + v.paramTypeName,
		};
	});
};
// 选择已配置的
const selectParameter = (item: any) => {
	state.paramSelect.forEach((v: any) => {
		if (item.id === v.id) {
			v.active = !v.active;
		}
	});
	// 排序数组
	state.priority = state.paramSelect.filter((v: any) => {
		return v.active;
	});
	state.priority = state.priority.map((item: any, index: number) => {
		return {
			...item,
			sort: index,
			code: item.id,
		};
	});
};
//结束拖拽事件
const onEnd = () => {
	state.priority = state.priority.map((item: any, index: number) => {
		return {
			...item,
			sort: index,
			code: item.id,
		};
	});
};
// 新增组合
const combinationAdd = () => {
	state.combination.push({
		id: guid(),
		combinationName: '',
		combinationDisplayParam: '',
		combinationParam: [],
		timeLimitValue: 1,
		hour: '',
	});
};
// 删除组合
const combinationDelete = (row: any, index: number) => {
	ElMessageBox.confirm(`确定要删除?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			state.combination.splice(index, 1);
			getEnableAcceptType();
			getSelectedParams();
		})
		.catch(() => {});
};
// 选择组合参数
const chooseCombination = (row: any) => {
	state.paramForm = row;
	for (let i of state.combination) {
		for (let j of i.combinationParam) {
			switch (j.paramType) {
				case 'AcceptType':
					state.paramForm.acceptType = {
						key: j.paramValue,
						value: j.paramName,
					};
					break;
				case 'HotPots':
					state.paramForm.hotspot = j.paramValue;
					state.paramForm.hotspotSpliceName = j.paramName;
					if (j.hotParamParent) state.hotspotExternalCom = j.hotParamParent.split(',');
					break;
				case 'SourceChannel':
					state.paramForm.sourceChannel = {
						key: j.paramValue,
						value: j.paramName,
					};
					break;
				case 'IdentityType':
					state.paramForm.identityType = {
						key: j.paramValue,
						value: j.paramName,
					};
					break;
				case 'OrderType':
					state.paramForm.orderType = {
						key: j.paramValue,
						value: j.paramName,
					};
					break;
				case 'LicenceType':
					state.paramForm.certType = {
						dicDataValue: j.paramValue,
						dicDataName: j.paramName,
					};
					break;
				case 'EmergencyLevel':
					state.paramForm.emergencyLevel = {
						key: j.paramValue,
						value: j.paramName,
					};
					break;
				default:
					break;
			}
		}
	}
	state.paramDialog = true;
};
// 选择组合热点
const getComHotspot = (val: any, e: any) => {
	state.hotspotExternalCom = [];
	state.externalCom = [];
	state.hotspotExternalCom = getParentId(e, state.externalCom);
	state.paramForm.hotspotSpliceName = val.hotSpotFullName;
};
// 删除组合参数
const clearCombinationParam = (val: any) => {
	let item = state.combination.find((item: any) => item.id === state.paramForm.id);
	item.combinationParam = item.combinationParam.filter((v: any) => v.paramType !== val);
};
// 参数组合确定
const onConfirmCom = () => {
	let comName: string[] = [];
	let item = state.combination.find((item: any) => item.id === state.paramForm.id);
	if (item) {
		if (item.acceptType?.value) {
			item.combinationParam.push({
				paramName: item.acceptType.value,
				paramValue: item.acceptType.key,
				hotParamParent: '',
				paramType: 'AcceptType',
			});
			comName.push(`受理类型-${item.acceptType.value}`);
		}
		if (item?.hotspot) {
			item.combinationParam.push({
				paramName: item.hotspotSpliceName,
				paramValue: item.hotspot,
				hotParamParent: state.hotspotExternalCom.join(','),
				paramType: 'HotPots',
			});
			comName.push(`热点分类-${item.hotspotSpliceName}`);
		}
		if (item.identityType?.value) {
			item.combinationParam.push({
				paramName: item.identityType.value,
				paramValue: item.identityType.key,
				hotParamParent: '',
				paramType: 'IdentityType',
			});
			comName.push(`来电人身份-${item.identityType.value}`);
		}
		if (item.sourceChannel?.value) {
			item.combinationParam.push({
				paramName: item.sourceChannel.value,
				paramValue: item.sourceChannel.key,
				hotParamParent: '',
				paramType: 'SourceChannel',
			});
			comName.push(`来源渠道-${item.sourceChannel.value}`);
		}
		if (item.orderType?.value) {
			item.combinationParam.push({
				paramName: item.orderType.value,
				paramValue: item.orderType.key,
				hotParamParent: '',
				paramType: 'OrderType',
			});
			comName.push(`工单类型-${item.orderType.value}`);
		}
		if (item.certType?.dicDataName) {
			item.combinationParam.push({
				paramName: item.certType.dicDataName,
				paramValue: item.certType.dicDataValue,
				hotParamParent: '',
				paramType: 'LicenceType',
			});
			comName.push(`证件类型-${item.certType.dicDataName}`);
		}
		if (item.emergencyLevel?.value) {
			item.combinationParam.push({
				paramName: item.emergencyLevel.value,
				paramValue: item.emergencyLevel.key,
				hotParamParent: '',
				paramType: 'EmergencyLevel',
			});
			comName.push(`紧急程度-${item.emergencyLevel.value}`);
		}
		// if(state.paramForm.emergencyLevel.value){
		// 	state.paramForm.push({
		// 		paramName:state.paramForm.emergencyLevel.value,
		// 		paramValue:state.paramForm.emergencyLevel.key,
		// 		hotParamParent:'',
		// 		paramType:'EmergencyLevel'
		// 	})
		// 	comName+=`默认参数-${state.paramForm.emergencyLevel.value}&`;
		// }
	}
	item.combinationParam = removeDuplicate(item.combinationParam, 'paramType');
	state.paramForm.hotParamParent = state.hotspotExternalCom.join(',');
	if (item.combinationParam.length < 2) {
		ElMessageBox.alert('一个组合中至少包含两个参数', '提示', {
			confirmButtonText: '确定',
		});
		return;
	}
	item.combinationDisplayParam = comName.join('&');
	state.paramDialog = false;
};
// 定义一个函数来检查某个属性是否存在，如果不存在就给出提示信息，并返回false
const checkProperty = (obj: any, property: string, message: string) => {
	if (!obj[property]) {
		ElMessage.warning(message);
		return false;
	}
	return true;
};
// 暂存
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		let arr: any = [];
		for (let i of state.paramArr) {
			if (i.paramValue.length) {
				for (let j of i.paramValue) {
					// 检查paramTypeName是否存在
					if (!checkProperty(j, 'paramTypeName', `请选择${i.name}`)) return;
					// 检查timeLimitValue是否存在
					if (!checkProperty(j, 'timeLimitValue', `请填写${i.name}的时限`)) return;
					// 检查timeLimitType是否存在
					if (!checkProperty(j, 'timeLimitType', `请选择${i.name}的单位`)) return;
					arr.push(j);
				}
			}
		}
		if (!arr.length) {
			ElMessage.warning(`请选择参数`);
			return;
		}
		for (let i of state.combination) {
			// 检查combinationName是否存在
			if (!checkProperty(i, 'combinationName', `请填写组合名称`)) return;
			// 检查combinationDisplayParam是否存在
			if (!checkProperty(i, 'combinationDisplayParam', `请选择组合参数`)) return;
			if (i.combinationParam.length.length < 2) {
				ElMessageBox.alert('一个组合中至少包含两个参数', '提示', {
					confirmButtonText: '确定',
				});
				return;
			}
			// 检查timeLimitValue是否存在
			if (!checkProperty(i, 'timeLimitValue', `请填写时限`)) return;
			// 检查timeLimit是否存在或者为0
			if (!checkProperty(i, 'timeLimit', `请选择组合单位`)) return;
		}
		let req = {
			...state.ruleForm,
			paramArr: arr,
			priority: state.priority,
			combination: state.combination,
			id: state.timeLimitId,
		};
		timeLimitUpdate(req).then(() => {
			ElMessage.success('操作成功');
			emit('updateList');
			state.dialogVisible = false;
		});
	});
};
// 确定
const onConfirm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		let arr: any = [];
		for (let i of state.paramArr) {
			if (i.paramValue.length) {
				for (let j of i.paramValue) {
					// 检查paramTypeName是否存在
					if (!checkProperty(j, 'paramTypeName', `请选择${i.name}`)) return;
					// 检查timeLimitValue是否存在
					if (!checkProperty(j, 'timeLimitValue', `请填写${i.name}的时限`)) return;
					// 检查timeLimitType是否存在
					if (!checkProperty(j, 'timeLimitType', `请选择${i.name}的单位`)) return;
					arr.push(j);
				}
			}
		}
		if (!arr.length) {
			ElMessage.warning(`请选择参数`);
			return;
		}
		for (let i of state.combination) {
			// 检查combinationName是否存在
			if (!checkProperty(i, 'combinationName', `请填写组合名称`)) return;
			// 检查combinationDisplayParam是否存在
			if (!checkProperty(i, 'combinationDisplayParam', `请选择组合参数`)) return;
			if (i.combinationParam.length.length < 2) {
				ElMessageBox.alert('一个组合中至少包含两个参数', '提示', {
					confirmButtonText: '确定',
				});
				return;
			}
			// 检查timeLimitValue是否存在
			if (!checkProperty(i, 'timeLimitValue', `请填写时限`)) return;
			// 检查timeLimit或者timeLimit（这里可能是拼写错误）是否存在或者为0
			if (!checkProperty(i, 'timeLimit', `请选择组合单位`)) return;
		}
		// timeLimitAdd(state.ruleForm).then(() => {
		// 	ElMessage.success('操作成功');
		// 	emit('updateList');
		// 	state.dialogVisible = false;
		// });
	});
};
//暴漏变量和方法
defineExpose({ closeDialog, openDialog });
</script>
<style lang="scss" scoped>
.system-timeLimit-edit-container {
	.collapse-box {
		:deep(.el-collapse-item__header) {
			background-color: var(--hotline-bg-main-color);
			height: 40px;
			border-radius: var(--el-border-radius-base);
		}
		:deep(.el-collapse-item__content) {
			padding-bottom: 0 !important;
			.el-form-item {
				margin-bottom: 5px;
				.el-form-item__content {
					line-height: 24px;
				}
			}
		}
		.collapse-container {
			padding: 10px;
			.plug-container {
				border: var(--el-border);
				border-radius: var(--el-border-radius-base);
				margin-bottom: 15px;
				&:last-child {
					margin-bottom: 0;
				}
				.plug-container-title {
					padding: 10px 15px;
					font-weight: bold;
					border-bottom: var(--el-border);
					font-size: var(--el-font-size-medium);
				}
			}
		}
	}
	:deep(.el-collapse-item__wrap) {
		border-bottom: 0;
	}
	:deep(.el-collapse) {
		border-bottom: 0;
	}
	:deep(.el-tabs__nav-wrap::after) {
		height: 100% !important;
	}
	.parameter-choose {
		&-one {
			cursor: pointer;
			text-align: center;
			height: 34px;
			line-height: 34px;
			color: var(--el-color-primary);
			width: calc(100% - 10px);
			padding: 0 5px;
			border: 1px solid transparent;
		}
		.active {
			border: 1px solid var(--el-color-primary);
			border-radius: var(--el-border-radius-base);
		}
	}
	.parameter-stop {
		&-one {
			cursor: pointer;
			text-align: center;
			height: 34px;
			line-height: 34px;
			width: calc(100% - 10px);
			padding: 0 5px;
		}
		.active {
			border: 1px solid var(--el-color-primary);
			border-radius: var(--el-border-radius-base);
			color: var(--el-color-primary);
		}
	}
	.parameter-sort {
		display: flex;
		flex-wrap: wrap;
		&-one {
			cursor: pointer;
			text-align: center;
			height: 34px;
			line-height: 34px;
		}
	}
	.omit {
		display: inline-block;
	}
}
</style>
