<template>
	<div class="todo-seats-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.type" @tab-change="changeTab">
				<el-tab-pane name="0" label="工单待办" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="1" label="交办件" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="2" label="办结件" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<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>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAddOrder" v-auth="'todo:seats:add'" :loading="state.loading">
						<SvgIcon name="ele-Plus" class="mr5" />新建工单
					</el-button>
					<el-button type="primary" @click="onJbExport" :disabled="isChecked" :loading="state.loading" v-auth="'todo:seats:jbdExport'"
					><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出
					</el-button>
				</template>
				<template #tools> </template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:sort-config="{ remote: true }"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30 }"
					ref="tableRef"
					@sort-change="sortChange"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:print-config="{}"
					:scrollY="{ enabled: true, gt: 0 }"
					id="todoSeats"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="expiredStatusText" title="超期状态" width="90" align="center">
						<template #default="{ row }">
							<span :class="'overdue-status-' + row.expiredStatus" :title="row.expiredStatusText"></span>
						</template>
					</vxe-column>
					<vxe-column field="no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="isProvinceText" title="省/市工单" width="90"></vxe-column>
					<vxe-column field="isUrgentText" title="是否紧急" width="90">
						<template #default="{ row }">
							<span class="color-danger font-bold">{{ row.isUrgentText }}</span>
						</template>
					</vxe-column>
					<vxe-column field="currentStepName" title="当前节点" width="120"></vxe-column>
					<vxe-column field="statusText" title="工单状态" width="100"></vxe-column>
					<vxe-column field="title" title="工单标题" width="200">
						<template #default="{ row }">
							<order-detail :order="row" @updateList="queryList">{{ row.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="counterSignTypeText" title="是否会签" width="90"></vxe-column>
					<vxe-column field="creationTime" title="生成时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="startTime" title="受理时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="expiredTime" title="工单期满时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="sourceChannel" title="来源渠道" width="100"></vxe-column>
					<vxe-column field="hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="acceptorName" title="受理人" width="120"></vxe-column>
					<vxe-column field="reTransactNum" title="重办次数" width="90"></vxe-column>
					<vxe-column title="操作" fixed="right" width="80" align="center">
						<template #default="{ row }">
							<el-button link type="success" @click="onOrderEdit(row)" title="编辑工单" v-if="row.canEdit" v-auth="'todo:seats:edit'"> 修改 </el-button>
							<el-button link type="primary" @click="onSign(row)" title="签收工单" v-if="row.canSign" v-auth="'todo:seats:sign'"> 签收 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<div class="flex-end" style="align-items: center">
				<span v-loading="totalLoading" class="mr10">共 {{ totalCount }} 条</span>
				<el-pagination
					layout="prev, pager, next"
					:total="state.total"
					@current-change="handleCurrentChange"
					:page-size="state.queryParams.PageSize"
					:current-page="state.queryParams.PageIndex"
					:disabled="state.loading"
				/>
			</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 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="IsCounterSign">
					<el-select v-model="state.queryParams.IsCounterSign" placeholder="请选择是否会签" @change="handleQuery">
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</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="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-item prop="Status" label="工单状态" v-if="state.queryParams.IsHandled === 'true'">
					<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>
			<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="todoSeats">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { useRouter } from 'vue-router';
import { seatsListTodo, orderSign, orderListTodoCount } from '@/api/todo/order';
import { downloadZip, getNeedArr } from '@/utils/tools';
import { exportJbOrder } from '@/api/business/order';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { treeArea } from '@/api/auxiliary/area';
import { centerTodoBase } from '@/api/todo/center';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		IsHandled: 'false', // 工单状态
		type:'0',
		Keyword: null, // 关键字
		IsProvince: null, // 是否省工单
		IsCounterSign: null, // 是否会签
		scTime: [],
		StartTime: null,
		EndTime: null,
		IsUrgent: null,
		AreaCode: null,
		Status: null,
		TypeCode:null,
		SortField:null,
		SortRule:null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	areaOptions: [],
	orderStatusOptions: [], // 工单状态
});
const router = useRouter(); // 路由
// 排序
const 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 changeTab = (val:string)=>{
	switch (val) {
		case '0':
			state.queryParams.IsHandled = 'false';
			state.queryParams.TypeCode  = null;
			break;
		case '1': // 交办
			state.queryParams.TypeCode  = 1;
			state.queryParams.IsHandled = null;
			break;
		case '2': //直办
			state.queryParams.TypeCode = 2;
			state.queryParams.IsHandled = null;
			break;
	}
	handleQuery();
}
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryIndex.value = 0;
	queryList(true);
};
// 改变页码
const queryIndex = ref(0); // 数据批次
const totalTable = ref([]); // 数据总数
const handleCurrentChange = (val: number) => {
	state.queryParams.PageIndex = val;
	// 判断当前页是否是数据的最后一页
	if (val === Math.ceil(state.total / state.queryParams.PageSize)) {
		queryList();
	} else {
		state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
	}
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const totalCount = ref(0);
const totalLoading = ref(false);
const queryList = async (isQuery: boolean = false) => {
	state.loading = true;
	totalLoading.value = true;
	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];
	requestParams.value.QueryIndex = queryIndex.value; // 数据批次
	seatsListTodo(requestParams.value)
		.then((response: any) => {
			if (isQuery) {
				// 如果是查询
				totalTable.value = []; // 先清空
				totalTable.value = response?.result;
				state.total = totalTable.value.length;
				state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
				queryIndex.value = 1; // 请求完成之后，页码加一避免重复
			} else {
				if (response?.result.length) queryIndex.value++;
				totalTable.value = totalTable.value.concat(response?.result);
				state.total = totalTable.value.length;
				state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
			}
			state.loading = false;
		})
		.then(() => {
			// 查询总数
			orderListTodoCount(requestParams.value)
				.then((count) => {
					totalCount.value = count.result;
					totalLoading.value = false;
				})
				.catch(() => {
					totalLoading.value = false;
				});
		})
		.catch(() => {
			state.loading = false;
			totalLoading.value = false;
		});
};
/** 重置按钮操作 */
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();
	queryIndex.value = 0;
	queryList(true);
};
// 新增工单
const onAddOrder = () => {
	router.push({
		name: 'orderAccept',
		query: {
			timeStamp: new Date().getTime(),
		},
	});
};
// 编辑工单
const onOrderEdit = (row: any) => {
	router.push({
		name: 'orderAccept',
		query: {
			id: row.id,
			tagsViewName: `编辑工单-${row.title}`,
		},
	});
};
// 签收工单
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('签收成功');
				handleQuery();
			});
		})
		.catch(() => {});
};
// 交办单导出
const onJbExport = () => {
	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;
			exportJbOrder(ids)
				.then((res: any) => {
					downloadZip(res);
					state.loading = false;
					ElMessage.success('导出成功');
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 获取查询条件基础信息
const getBaseData = async () => {
	try {
		const { result } = await treeArea();
		state.areaOptions = result ?? []; //省市区数据
		const res: any = await centerTodoBase();
		const mappings: any = {
			orderStatusOptions: 'orderStatus',
		};
		for (const key in mappings) {
			state[key] = res.result?.[mappings[key]] ?? [];
		}
	} catch (error) {
		console.log(error);
	}
};
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 toolbarRef = ref<RefType>();
onMounted(() => {
	getBaseData();
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
<style scoped lang="scss">
.todo-seats-container {
	:deep(.pro-table-main) {
		height: calc(100% - 95px);
	}
}
</style>
