<template>
	<el-dialog v-model="state.dialogVisible" width="50%" draggable :title="dialogTitle" @close="close" append-to-body destroy-on-close>
		<el-form :model="state.ruleForm" label-width="80px" ref="ruleFormRef">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请填写标题', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.title" placeholder="请填写标题" clearable show-word-limit maxlength="200"></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="关键词" prop="keyWords" :rules="[{ required: false, message: '请填写关键词', trigger: 'change' }]">
						<el-tag
							v-for="tag in dynamicTags"
							:key="tag"
							class="mr10 mb10"
							size="large"
							closable
							:disable-transitions="false"
							@close="handleClose(tag)"
						>
							{{ tag }}
						</el-tag>
						<el-input
							v-if="inputVisible"
							ref="InputRef"
							v-model="inputValue"
							@keyup.enter="handleInputConfirm"
							@blur="handleInputConfirm"
							style="max-width: 200px"
							class="mb10"
						/>
						<el-button v-else @click="showInput" class="mb10"> 添加关键词 </el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-divider content-position="left">
			<el-text tag="b" size="large"> 重复事件工单 </el-text>
		</el-divider>
		<vxe-toolbar
			ref="toolbarRef"
			:loading="state.loading"
		>
			<template #buttons>
				<el-button type="primary" @click="onAddRepeatTable"><SvgIcon name="ele-Plus" class="mr5"/> 添加</el-button>
				<el-button type="danger" @click="onRemoveRepeatTable" :disabled="isChecked"><SvgIcon name="ele-Delete" class="mr5"/>移除 </el-button>
			</template>
		</vxe-toolbar>
		<vxe-table
				border
				:loading="state.loading"
				:data="state.repeatTable"
				:column-config="{ resizable: true }"
				:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
				ref="tableRef"
				@checkbox-all="selectAllChangeEvent"
				@checkbox-change="selectChangeEvent"
				max-height="500"
				show-overflow
				:scrollY="{ enabled: true, gt: 100 }"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column field="no" title="工单编码" width="140"></vxe-column>
				<vxe-column field="isProvinceText" title="省/市工单" width="90"></vxe-column>
				<vxe-column field="currentStepName" title="当前节点" width="100"></vxe-column>
				<vxe-column field="statusText" title="工单状态" width="100">
					<template #default="{ row }">
						<el-text type="danger" tag="b" v-if="[1, 2, 3, 9, 101, 102, 103, 104, 105, 200].includes(row.status)">{{ row.statusText }}</el-text>
						<span v-else>{{ row.statusText }}</span>
					</template>
				</vxe-column>
				<vxe-column field="title" title="工单标题" width="200">
					<template #default="{ row }">
						<order-detail :order="row">{{ row.title }}</order-detail>
					</template>
				</vxe-column>
				<vxe-column field="startTime" title="受理时间" width="160">
					<template #default="{ row }">
						{{ formatDate(row.startTime, 'YYYY-mm-dd HH:MM:SS') }}
					</template>
				</vxe-column>
				<vxe-column field="expiredTime" title="工单期满时间" width="160">
					<template #default="{ row }">
						{{ formatDate(row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
					</template>
				</vxe-column>
				<vxe-column field="actualHandleOrgName" title="接办部门" width="140"></vxe-column>
				<vxe-column field="acceptType" title="受理类型" width="100"></vxe-column>
				<vxe-column field="counterSignTypeText" title="是否会签" width="90"></vxe-column>
				<vxe-column field="sourceChannel" title="来源渠道" width="100"></vxe-column>
				<vxe-column field="hotspotName" title="热点分类" width="150"></vxe-column>
			</vxe-table>

		<!--   从所有工单重选择重复   -->
		<el-dialog v-model="state.dialogVisibleAllTable" width="50%" draggable title="选择重复事件工单" append-to-body destroy-on-close>
			<el-form :model="state.queryParamsAll" ref="queryParamsAllRef" inline @submit.native.prevent>
				<el-form-item label="关键词" prop="Keyword">
					<el-input v-model="state.queryParamsAll.Keyword" placeholder="工单标题/工单编码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQueryAll(queryParamsAllRef)" :loading="state.loading" class="default-button">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<vxe-table
				border
				:loading="state.loading"
				:data="state.allTable"
				:column-config="{ resizable: true }"
				:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
				ref="tableRefAll"
				@checkbox-all="selectAllChangeEventAll"
				@checkbox-change="selectChangeEventAll"
				max-height="500"
				show-overflow
				:scrollY="{ enabled: true, gt: 100 }"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column field="no" title="工单编码" width="140"></vxe-column>
				<vxe-column field="isProvinceText" title="省/市工单" width="90"></vxe-column>
				<vxe-column field="currentStepName" title="当前节点" width="100"></vxe-column>
				<vxe-column field="statusText" title="工单状态" width="100">
					<template #default="{ row }">
						<el-text type="danger" tag="b" v-if="[1, 2, 3, 9, 101, 102, 103, 104, 105, 200].includes(row.status)">{{ row.statusText }}</el-text>
						<span v-else>{{ row.statusText }}</span>
					</template>
				</vxe-column>
				<vxe-column field="title" title="工单标题" width="200">
					<template #default="{ row }">
						<order-detail :order="row">{{ row.title }}</order-detail>
					</template>
				</vxe-column>
				<vxe-column field="startTime" title="受理时间" width="160">
					<template #default="{ row }">
						{{ formatDate(row.startTime, 'YYYY-mm-dd HH:MM:SS') }}
					</template>
				</vxe-column>
				<vxe-column field="expiredTime" title="工单期满时间" width="160">
					<template #default="{ row }">
						{{ formatDate(row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
					</template>
				</vxe-column>
				<vxe-column field="actualHandleOrgName" title="接办部门" width="140"></vxe-column>
				<vxe-column field="acceptType" title="受理类型" width="100"></vxe-column>
				<vxe-column field="counterSignTypeText" title="是否会签" width="90"></vxe-column>
				<vxe-column field="sourceChannel" title="来源渠道" width="100"></vxe-column>
				<vxe-column field="hotspotName" title="热点分类" width="150"></vxe-column>
			</vxe-table>
			<pagination
				@pagination="queryListAll"
				:total="state.totalAll"
				v-model:current-page="state.queryParamsAll.PageIndex"
				v-model:page-size="state.queryParamsAll.PageSize"
				:disabled="state.loading"
			/>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogVisibleAllTable = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmitAll" :loading="state.loading" :disabled="isCheckedAll">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.dialogVisible = false" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="tsx" name="repeatEventEdit">
import { nextTick, reactive, ref, defineAsyncComponent, computed } from 'vue';
import { formatDate } from '@/utils/formatTime';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { removeDuplicate } from '@/utils/arrayOperation';
import { orderList, orderListCount } from '@/api/business/order';
import { repeatEventAdd, repeatEventDetail, repeatEventUpdate } from '@/api/business/repeatEvent';
import { throttle } from '@/utils/tools';

const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const emit = defineEmits(['updateList']);
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 10,
		Keyword: null, // 关键字
		CreationTimeStart: dayjs().startOf('day').format('YYYY-MM-DD[T]HH:mm:ss'), // 创建时间 开始
		CreationTimeEnd: dayjs().endOf('day').format('YYYY-MM-DD[T]HH:mm:ss'), // 创建时间 结束
		exTime: [dayjs().startOf('day').format('YYYY-MM-DD[T]HH:mm:ss'), dayjs().endOf('day').format('YYYY-MM-DD[T]HH:mm:ss')], // 创建时间
	},
	tableData: [], //表格
	loading: false, // 加载
	total: 0, // 总数
	dialogVisible: false, // 弹窗
	ruleForm: {},
	repeatTable: [], // 重复事件工单
	dialogVisibleAllTable: false, // 全部工单 重复事件工单弹窗
	allTable: [], // 全部工单
	totalAll: 0,
	queryParamsAll: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '', // 关键字
	},
});

const columns = ref<any[]>([
	{ type: 'selection', fixed: 'left', width: 55 },
	{ prop: 'no', label: '工单编码', width: 150 },
	{ prop: 'isProvinceText', label: '省/市工单', width: 100 },
	{ prop: 'currentStepName', label: '当前节点', width: 120 },
	{ prop: 'statusText', label: '工单状态', width: 100 },
	{ prop: 'title', label: '标题', width: 300 },
	{
		prop: 'startTime',
		label: '受理时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.startTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'expiredTime',
		label: '工单期满时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.expiredTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'actualHandleOrgName', label: '接办部门', width: 170 },
	{ prop: 'acceptType', label: '受理类型', width: 150 },
	{ prop: 'sourceChannel', label: '来源渠道' },
	{ prop: 'acceptorName', label: '受理人', width: 120 },
]);

const inputValue = ref('');
const dynamicTags = ref<EmptyArrayType>([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<any>>();
// 删除同义词
const handleClose = (tag: string) => {
	dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};
// 展示填写框
const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value!.input!.focus();
	});
};
// 确定添加
const handleInputConfirm = () => {
	if (inputValue.value) {
		dynamicTags.value.push(inputValue.value);
	}
	inputVisible.value = false;
	inputValue.value = '';
};
// 创建重复事件
const dialogTitle = ref<String>('创建重复性事件');
const openDialog = (row?: any) => {
	state.dialogVisible = true;
	state.loading = true;
	if (row) {
		dialogTitle.value = '编辑重复性事件';
		getDetail(row);
	} else {
		dialogTitle.value = '创建重复性事件';
		state.loading = false;
	}
};
// 查询详情
const getDetail = async (row: any) => {
	try {
		const { result } = await repeatEventDetail({ id: row.id, Keyword: null });
		state.ruleForm = result;
		if (result.keyWords) dynamicTags.value = result.keyWords?.split(',') ?? [];
		state.repeatTable = result.details.map((item: any) => {
			return {
				...item,
				...item?.order,
			};
		});
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 打开所有工单列表选择重复工单
const onAddRepeatTable = () => {
	state.dialogVisibleAllTable = true;
	queryListAll();
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParamsAll.PageIndex = 1;
	queryListAll();
};
// 查询总数
const getTotal = () => {
	orderListCount(state.queryParamsAll)
		.then((res) => {
			state.totalAll = res.result ?? 0;
		})
		.catch(() => {
		});
};
// 获取所有工单列表
const queryListAll = async () => {
	state.loading = true;
	try {
		const res = await orderList(state.queryParamsAll);
		state.allTable = res.result ?? [];
		console.log('allTable', state.allTable)
		getTotal();
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 重置所有工单列表
const queryParamsAllRef = ref<RefType>();
const resetQueryAll = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryListAll();
};

const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});

const tableRefAll = ref<RefType>();
const checkTableAll = ref<EmptyArrayType>([]);
const selectAllChangeEventAll = ({ checked }) => {
	if (tableRefAll.value) {
		const records = tableRefAll.value.getCheckboxRecords();
		checkTableAll.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEventAll = ({ checked }) => {
	if (tableRefAll.value) {
		const records = tableRefAll.value.getCheckboxRecords();
		checkTableAll.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isCheckedAll = computed(() => {
	return !Boolean(checkTableAll.value.length);
});

const onSubmitAll = () => {
	state.dialogVisibleAllTable = false;
	state.repeatTable = removeDuplicate([...state.repeatTable, ...checkTableAll.value], 'id'); // 添加时去重
};
// 删除重复工单
const onRemoveRepeatTable = () => {
	ElMessageBox.confirm(`您确定要删除选中的工单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			checkTable.value.forEach((item1: any) => {
				state.repeatTable.forEach((item: any, index: number) => {
					if (item.id === item1.id) {
						tableRef.value.setCheckboxRow(item, false);
						checkTable.value.splice(checkTable.value.indexOf(item1), 1);
						state.repeatTable.splice(index, 1);
					}
				});
			});
		})
		.catch(() => {});
};
const ruleFormRef = ref<RefType>();
const close = () => {
	ruleFormRef.value.clearValidate();
	ruleFormRef.value.resetFields();
};

const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const details = state.repeatTable.map((item: any) => {
			return {
				orderNo: item.no,
				orderId: item.id,
			};
		});
		const request = {
			...state.ruleForm,
			keyWords: dynamicTags.value.join(','),
			details,
		};
		if (dialogTitle.value === '创建重复性事件') {
			repeatEventAdd(request)
				.then(() => {
					ElMessage({
						message: '操作成功',
						type: 'success',
					});
					emit('updateList');
					state.dialogVisible = false;
				})
				.catch(() => {})
				.finally(() => {
					state.loading = false;
					state.dialogVisible = false;
				});
		} else {
			repeatEventUpdate(request)
				.then(() => {
					ElMessage({
						message: '操作成功',
						type: 'success',
					});
					emit('updateList');
					state.dialogVisible = false;
				})
				.catch(() => {})
				.finally(() => {
					state.loading = false;
					state.dialogVisible = false;
				});
		}
	});
}, 300);
defineExpose({
	openDialog,
});
</script>
