<template>
	<div class="todo-order-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.IsHandled" @tab-change="handleQuery">
				<el-tab-pane name="false" label="工单待办" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="true" label="工单已办" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<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 inline :disabled="state.loading">
							<el-form-item label="快捷查询办理" prop="IsCounterSign" v-auth="'todo:order:fastSearchHandle'">
								<el-segmented :options="fastSearchHandle" v-model="state.queryParams.IsCounterSign" @change="handleQuery" :disabled="state.loading" />
							</el-form-item>
							<el-form-item
								label="快捷查询"
								prop="QueryType"
								v-auth="'todo:order:fastSearch'"
								v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope) && state.queryParams.IsHandled === 'false'"
							>
								<el-segmented
									:options="[
										{
											value: 1,
											label: '中心办理件',
										},
										{
											value: 2,
											label: '转单件',
										},
										{
											value: 3,
											label: '二次派发',
										},
									]"
									v-model="state.queryParams.QueryType"
									@change="handleQuery"
									:disabled="state.loading"
								/>
							</el-form-item>
							<el-form-item label="工单标题" prop="Keyword">
								<el-input
									v-model.trim="state.queryParams.Keyword"
									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 label="">
								<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" :disabled="isChecked" :loading="state.loading" v-auth="'todo:order:jbdExport'"
							><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出<span v-if="checkTable.length">({{ checkTable.length }})</span>
						</el-button>
						<el-button
							type="primary"
							@click="onToEnd"
							:disabled="isChecked"
							:loading="state.loading"
							v-auth-all="['todo:order:fastSearch', 'todo:order:toEnd:multiple']"
							><SvgIcon name="ele-List" class="mr5" />批量归档<span v-if="checkTable.length">({{ checkTable.length }})</span>
						</el-button>
						<el-button type="primary" @click="onAssignOrders" :loading="state.loading" v-auth="'todo:order: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="queryList">{{ row.title }}</order-detail>
					</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>
		</div>
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
				<el-form-item prop="CurrentStepCode" label="当前节点">
					<el-select v-model="state.queryParams.CurrentStepCode" placeholder="请选择当前节点" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in currentStepOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item prop="Status" label="工单状态">
					<el-select v-model="state.queryParams.Status" placeholder="请选择工单状态" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in orderStatusOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<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="IsUrgent">
					<el-select v-model="state.queryParams.IsUrgent" placeholder="请选择是否紧急" clearable @change="handleQuery">
						<el-option :value="true" label="紧急" />
						<el-option :value="false" label="不紧急" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否省工单" prop="IsProvince">
					<el-select v-model="state.queryParams.IsProvince" placeholder="请选择是否省工单" @change="handleQuery">
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item label="超期状态" prop="ExpiredOrAlmostOverdue">
					<el-select v-model="state.queryParams.ExpiredOrAlmostOverdue" placeholder="请选择超期状态" @change="handleQuery" clearable>
						<el-option label="已超期" value="true" />
						<el-option label="即将超期" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item label="事发地址" prop="AreaCode">
					<el-cascader
						:options="state.areaOptions"
						filterable
						:props="{ checkStrictly: true, value: 'id', label: 'areaName', emitPath: false }"
						placeholder="请选择事发地址"
						clearable
						class="w100"
						v-model="state.queryParams.AreaCode"
						@change="handleQuery"
					>
					</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="todoOrder">
import { defineAsyncComponent, onMounted, reactive, ref, onActivated, onBeforeUnmount, computed } from 'vue';
import { ElMessage, ElMessageBox, ElNotification, FormInstance } from 'element-plus';
import { orderAverage, orderBatchArchive, orderListTodo, orderListTodoBase, orderListTodoTotal } from '@/api/todo/order';
import { exportAssignment } from '@/utils/tools';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import mittBus from '@/utils/mitt';
import { treeArea } from '@/api/auxiliary/area';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { auth } from '@/utils/authFunction';
import { LZTableHeader, YBTableHeader, ZGTableHeader } from '@/views/todo/order/tableHeader';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		IsHandled: 'false', // 工单状态
		Keyword: null, // 工单标题
		No: null, // 工单编码
		IsProvince: null, // 是否省工单
		IsCounterSign: '', // 是否会签
		ExpiredOrAlmostOverdue: null, // 超期状态
		scTime: [],
		StartTime: null,
		EndTime: null,
		IsUrgent: null,
		AreaCode: null,
		SortField: null,
		SortRule: null,
		CurrentStepCode: null,
		Status: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	areaOptions: [],
});

const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const requestParams = ref<EmptyObjectType>({});
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: 'todoOrder',
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true },
	height: 'auto',
	columns: [],
	data: [],
	sortConfig: {
		remote: true,
	},
});
if (themeConfig.value.appScope === 'YiBin') {
	gridOptions.columns = YBTableHeader;
} else if (themeConfig.value.appScope === 'ZiGong') {
	gridOptions.columns = ZGTableHeader;
} else if (themeConfig.value.appScope === 'LuZhou') {
	gridOptions.columns = LZTableHeader;
}
// 待办不展示 接办部门 一级部门
gridOptions.columns = gridOptions.columns.filter((item: any) => !['actualHandleOrgName', 'orgLevelOneName'].includes(item.field));
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 fastSearchHandle = ref<EmptyArrayType>([
	{
		value: '',
		label: '全部',
	},
	{
		value: false,
		label: '工单待办',
	},
	{
		value: true,
		label: '会签待办',
	},
]);
// 手动查询，将页码设置为1
const handleQuery = () => {
	if (state.queryParams.IsHandled === 'true') {
		fastSearchHandle.value = [
			{
				value: '',
				label: '全部',
			},
			{
				value: false,
				label: '工单已办',
			},
			{
				value: true,
				label: '会签已办',
			},
		];
		if (themeConfig.value.appScope === 'YiBin') {
			gridOptions.columns = YBTableHeader;
		} else if (themeConfig.value.appScope === 'ZiGong') {
			gridOptions.columns = ZGTableHeader;
		} else if (themeConfig.value.appScope === 'LuZhou') {
			gridOptions.columns = LZTableHeader;
		}
	} else {
		fastSearchHandle.value = [
			{
				value: '',
				label: '全部',
			},
			{
				value: false,
				label: '工单待办',
			},
			{
				value: true,
				label: '会签待办',
			},
		];
		// 待办不展示 接办部门 一级部门
		gridOptions.columns = gridOptions.columns.filter((item: any) => !['actualHandleOrgName', 'orgLevelOneName'].includes(item.field));
	}
	state.queryParams.PageIndex = 1;

	queryList();
	getTotal();
};
/** 获取列表 */
const queryList = async () => {
	return new Promise(async (resolve, reject) => {
		state.loading = true;
		gridOptions.loading = true;
		if (['ZiGong', 'LuZhou'].includes(themeConfig.value.appScope) && auth('todo:order:fastSearch') && state.queryParams.IsHandled === 'false') {
			state.queryParams.QueryType = state.queryParams.QueryType ?? 1;
		} else state.queryParams.QueryType = null;
		try {
			requestParams.value = Other.deepClone(state.queryParams);
			requestParams.value.StartTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[0];
			requestParams.value.EndTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[1];
			Reflect.deleteProperty(requestParams.value, 'scTime');
			const res: any = await orderListTodo(requestParams.value);
			state.tableData = res.result ?? [];
			gridOptions.data = state.tableData;
			state.loading = false;
			gridOptions.loading = false;
			await gridRef.value?.clearCheckboxRow();
			checkTable.value = [];
			resolve(true);
		} catch (e) {
			console.log(e);
			state.loading = false;
			await gridRef.value?.clearCheckboxRow();
			checkTable.value = [];
			reject(e);
			gridOptions.loading = false;
		}
	});
};
// 查询总数
const getTotal = () => {
	orderListTodoTotal(requestParams.value)
		.then((res) => {
			state.total = res.result ?? 0;
		})
		.catch(() => {});
};
/** 重置按钮操作 */
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();
	getTotal();
};
// 交办单导出
const onJbExport = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	exportAssignment(ids);
};
// 获取查询条件基础信息
const currentStepOptions = ref<EmptyArrayType>([]);
const orderStatusOptions = ref<EmptyArrayType>([]);
const getBaseData = async () => {
	try {
		const { result } = await treeArea();
		state.areaOptions = result ?? []; //省市区数据
		const res = await orderListTodoBase();
		currentStepOptions.value = res.result?.currentStepOptions ?? [];
		orderStatusOptions.value = res.result?.orderStatusOptions ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 分配工单
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 onToEnd = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要批量归档选中的工单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			orderBatchArchive({ orderIds: ids })
				.then((res: any) => {
					state.loading = false;
					handleQuery();
					ElNotification({
						title: '提示',
						message: `${res.result}`,
						type: 'info',
					});
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
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();
		getTotal();
	});
});
onActivated(() => {
	mittBus.on('clearCachePage', () => {
		//清除缓存
		handleQuery();
	});
});
onBeforeUnmount(() => {
	mittBus.off('clearCachePage');
});
</script>
