<template>
	<div class="todo-center-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd15">
			<vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="gridRef" @checkbox-all="selectAllChangeEvent" @checkbox-change="selectChangeEvent">
				<template #form>
					<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent class="mb10" inline :disabled="state.loading">
						<el-form-item label="工单标题" prop="Title">
							<el-input v-model.trim="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</el-form-item>
						<el-form-item label="工单编码" prop="No">
							<el-input v-model.trim="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</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="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
						</el-form-item>
					</el-form>
				</template>
				<template #toolbar_buttons>
					<el-button type="primary" @click="onJbExport" :loading="state.loading" :disabled="isChecked" v-auth="'todo:center:jbdExport'"
						><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</el-button>
					<el-button type="primary" @click="onAssignOrders" :loading="state.loading" v-auth="'todo:center:assignOrders'"
						><SvgIcon name="ele-List" class="mr5" />分配工单
					</el-button>
				</template>
				<template #statusText="{ 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>
				<template #order_detail="{ row }">
					<order-detail :order="row" @updateList="refreshList">{{ row.title }}</order-detail>
				</template>
				<template #action="{ row }">
					<el-button link type="primary" @click="onSign(row)" title="签收工单" v-show="row.canSign" v-auth="'todo:center:sign'"> 签收 </el-button>
					<el-button link type="success" @click="onOrderEdit(row)" title="编辑工单" v-show="row.canEdit" v-auth="'todo:center:edit'"> 修改 </el-button>
					<el-button link type="primary" @click="onMigration(row)" title="平级移动" v-auth="'todo:center:migration'"> 平级移动 </el-button>
				</template>
				<template #pager>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.loading"
					/>
				</template>
			</vxe-grid>
		</div>
		<!-- 工单平移 -->
		<order-migration ref="orderMigrationRef" @updateList="refreshList" />
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px" :disabled="gridOptions.loading">
				<el-form-item label="受理时间" prop="scTime">
					<el-date-picker
						v-model="state.queryParams.scTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item label="当前节点" prop="StepName">
					<el-select v-model="state.queryParams.StepName" placeholder="请选择当前节点" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.stepNamesOptions" :value="item" :key="item" :label="item" />
					</el-select>
				</el-form-item>
				<el-form-item label="派单员" prop="CenterToOrgHandlerName">
					<el-input v-model="state.queryParams.CenterToOrgHandlerName" placeholder="派单员" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="是否紧急" prop="IsUrgent">
					<el-select v-model="state.queryParams.IsUrgent" placeholder="请选择是否紧急" clearable class="w100" @change="handleQuery">
						<el-option :value="true" label="紧急" />
						<el-option :value="false" label="不紧急" />
					</el-select>
				</el-form-item>
				<el-form-item label="接办部门" prop="ActualHandleOrgName">
					<el-input v-model="state.queryParams.ActualHandleOrgName" placeholder="接办部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="工单状态" prop="Status">
					<el-select v-model="state.queryParams.Status" placeholder="请选择工单状态" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.orderStatusOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="受理人" prop="AcceptorName">
					<el-input v-model="state.queryParams.AcceptorName" placeholder="受理人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="超期状态" prop="ExpiredStatus">
					<el-select v-model="state.queryParams.ExpiredStatus" placeholder="请选择超期状态" clearable @change="handleQuery">
						<el-option v-for="item in state.expiredStatusOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="来源渠道" prop="SourceChannelCode">
					<el-select v-model="state.queryParams.SourceChannelCode" placeholder="请选择来源渠道" clearable @change="handleQuery">
						<el-option v-for="item in state.channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<!--				<el-form-item label="工单标签" prop="OrderTagCode" v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)">
					<el-cascader
						:options="state.orderTagOptions"
						filterable
						:props="{ value: 'dicDataValue', label: 'dicDataName', emitPath: false, checkStrictly: true }"
						placeholder="请选择工单标签"
						class="w100"
						v-model="state.queryParams.OrderTagCode"
						@change="handleQuery"
						clearable
					>
					</el-cascader>
				</el-form-item>-->
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
	</div>
</template>
<script setup lang="tsx" name="todoCenter">
import { computed, defineAsyncComponent, onActivated, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import other from '@/utils/other';
import { useRouter } from 'vue-router';
import { centerTodo, centerTodoBase } from '@/api/todo/center';
import { orderAverage, orderSign } from '@/api/todo/order';
import { debounce, exportAssignment } from '@/utils/tools';
import mittBus from '@/utils/mitt';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const OrderMigration = defineAsyncComponent(() => import('@/views/todo/center/Order-migration.vue')); // 工单平移
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		Title: null, // 标题
		No: null, // 工单编号
		scTime: [], // 受理时间
		StCreationTime: null, // 受理开始时间
		EnCreationTime: null, // 受理结束时间
		AcceptorName: null, // 受理人
		ActualHandleOrgName: null, // 接办部门
		Status: null, // 工单状态
		ExpiredStatus: null, // 超期状态
		StepName: null, // 当前节点名称
		IsUrgent: null,
		CenterToOrgHandlerName: null, // 派单员
		SortField: null,
		SortRule: null,
		OrderTagCode: null,
		SourceChannelCode: null, // 来源渠道
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	expiredStatusOptions: [], //超期状态
	orderStatusOptions: [], //工单状态
	stepNamesOptions: [], //步骤名称
	orderTagOptions: [], // 工单标签
});

const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				handleQuery();
			},
		},
		slots: {
			buttons: 'toolbar_buttons',
		},
	},
	customConfig: {
		storage: true,
	},
	id: 'todoCenter',
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true },
	height: 'auto',
	columns: [
		{ type: 'checkbox', width: 50, align: 'center' },
		{
			field: 'expiredStatusText',
			title: '状态',
			width: 60,
			align: 'center',
			slots: {
				default: ({ row }) => {
					return <span class={'overdue-status-' + row.expiredStatus} title={row.expiredStatusText}></span>;
				},
			},
		},
		{ field: 'acceptorName', title: '受理人', width: 120 },
		{ field: 'no', title: '工单编码', width: 140 },
		{ field: 'isProvinceText', title: '省/市工单', width: 90 },
		{
			field: 'isUrgentText',
			title: '是否紧急',
			width: 90,
			slots: {
				default: ({ row }) => {
					return <span class="color-danger font-bold">{row.isUrgentText}</span>;
				},
			},
		},
		{ field: 'currentStepName', title: '当前节点', width: 120 },
		{
			field: 'statusText',
			title: '工单状态',
			width: 110,
			slots: {
				default: 'statusText',
			},
		},
		{
			field: 'title',
			title: '工单标题',
			minWidth: 200,
			slots: { default: 'order_detail' },
		},
		{ field: 'centerToOrgHandlerName', title: '派单员', width: 120 },
		{
			field: 'creationTime',
			title: '受理时间',
			width: 160,
			sortable: true,
			formatter: 'formatDate',
		},
		{
			field: 'expiredTime',
			title: '期满时间',
			width: 160,
			sortable: true,
			formatter: 'formatDate',
		},
		{
			field: 'filedTime',
			title: '办结时间',
			width: 160,
			sortable: true,
			formatter: 'formatDate',
		},
		{ field: 'orgLevelOneName', title: '一级部门', width: 140 },
		{ field: 'actualHandleOrgName', title: '接办部门', width: 140 },
		{ field: 'acceptType', title: '受理类型', width: 110 },
		{ field: 'counterSignTypeText', title: '是否会签', width: 110 },
		{ field: 'sourceChannel', title: '来源渠道', width: 110 },
		{ field: 'hotspotName', title: '热点分类', width: 150 },
		{ field: 'sensitive', title: '敏感词', width: 150 },
		{ field: 'reTransactNum', title: '重办次数', width: 130 },
		{ title: '操作', width: 150, fixed: 'right', align: 'center', slots: { default: 'action' } },
	],
	data: [],
	sortConfig: {
		remote: true,
	},
});
const gridEvents = {
	sortChange(val: any) {
		state.queryParams.SortField = val.order ? val.field : null;
		// 0 升序 1 降序
		state.queryParams.SortRule = val.order ? (val.order == 'desc' ? 1 : 0) : null;
		handleQuery();
	},
};
const router = useRouter(); // 路由
// 获取查询条件基础信息
const getBaseData = async () => {
	try {
		const res: any = await centerTodoBase();
		const mappings: any = {
			expiredStatusOptions: 'expiredStatus',
			orderStatusOptions: 'orderStatus',
			stepNamesOptions: 'stepNames',
			orderTagOptions: 'orderTag',
			channelOptions: 'channelOptions',
		};
		for (const key in mappings) {
			state[key] = res.result?.[mappings[key]] ?? [];
		}
	} catch (error) {
		console.log(error);
	}
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 刷新列表  停留当前页 重新查询数据和总数
const refreshList = () => {
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	return new Promise((resolve, reject) => {
		requestParams.value = other.deepClone(state.queryParams);
		requestParams.value.StCreationTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[0]; // 受理时间
		requestParams.value.EndCreationTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[1];
		Reflect.deleteProperty(requestParams.value, 'scTime');
		state.loading = true;
		gridOptions.loading = true;
		centerTodo(requestParams.value)
			.then((response: any) => {
				state.tableData = response?.result.items ?? [];
				state.total = response?.result.total;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				gridOptions.data = state.tableData;
				state.loading = false;
				gridOptions.loading = false;
				resolve(response);
			})
			.catch(() => {
				state.loading = false;
				gridOptions.loading = false;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				reject();
			});
	});
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	queryList();
};
// 签收工单
const onSign = (row: any) => {
	ElMessageBox.confirm(`您确定要要签收【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			orderSign(row.id).then(() => {
				ElMessage.success('签收成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 编辑工单
const onOrderEdit = (row: any) => {
	router.push({
		name: 'orderAccept',
		query: {
			id: row.id,
			tagsViewName: `编辑工单-${row.title}`,
		},
	});
};
// 交办单导出
const onJbExport = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	exportAssignment(ids);
};
// 平移功能
const orderMigrationRef = ref<RefType>();
const onMigration = (row: any) => {
	orderMigrationRef.value.openDialog('centerTodo', row);
};
// 分配工单
const onAssignOrders = () => {
	ElMessageBox.confirm(`您确定分配工单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			orderAverage()
				.then(() => {
					state.loading = false;
					ElMessage.success('分配成功');
					handleQuery();
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const gridRef = ref<RefType>();
const selectAllChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
onMounted(() => {
	queryList().then(() => {
		getBaseData();
	});
});
const handleEvent = debounce(() => {
	handleQuery();
}, 1000);
onActivated(() => {
	mittBus.on('clearCachePage', () => {
		//清除缓存
		handleEvent();
	});
});
onBeforeUnmount(() => {
	mittBus.off('clearCachePage');
});
</script>
