<template>
	<div class="todo-seats-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.TypeCode" @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>
			<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="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>
								<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="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" />交办单导出<span v-if="checkTable.length">({{ checkTable.length }})</span>
						</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 #action="{ 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>
					<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 label="受理人" prop="AcceptorName">
					<el-input v-model.trim="state.queryParams.AcceptorName" placeholder="受理人" clearable @keyup.enter="handleQuery" />
				</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="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="工单状态">
					<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 prop="IndustryId" label="行业类型" v-if="['ZiGong'].includes(themeConfig.appScope)">
					<el-select v-model="state.queryParams.IndustryId" placeholder="请选择行业类型" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.industryOptions" :value="item.id" :key="item.id" :label="item.name" />
					</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 { useRouter } from 'vue-router';
import { seatsListTodo, orderSign, orderListTodoCount } from '@/api/todo/order';
import { exportAssignment } from '@/utils/tools';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { treeArea } from '@/api/auxiliary/area';
import { centerTodoBase } from '@/api/todo/center';
import { LZTableHeader, YBTableHeader, ZGTableHeader } from '@/views/todo/seats/tableHeader';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.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, // 每页条数
		Keyword: null, // 关键字
		IsProvince: null, // 是否省工单
		IsCounterSign: null, // 是否会签
		scTime: [],
		StartTime: null,
		EndTime: null,
		IsUrgent: null,
		AreaCode: null,
		Status: null,
		TypeCode: '0',
		SortField: null,
		SortRule: null,
		AcceptorName: null, // 受理人
		IndustryId: null, // 行业ID
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	areaOptions: [],
	orderStatusOptions: [], // 工单状态
	industryOptions: [], // 行业类型
});

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: 'todoSeats',
	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;
}
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 changeTab = () => {
	handleQuery();
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
	getTotal();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const totalCount = ref(0);
const queryList = async () => {
	return new Promise((resolve, reject) => {
		state.loading = true;
		gridOptions.loading = 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];
		seatsListTodo(requestParams.value)
			.then((response: any) => {
				gridOptions.data = response?.result ?? [];
				state.loading = false;
				gridOptions.loading = false;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				resolve(totalCount.value);
			})
			.catch(() => {
				state.loading = false;
				gridOptions.loading = false;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				reject();
			});
	});
};
// 查询总数
const getTotal = () => {
	orderListTodoCount(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 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);
	exportAssignment(ids);
};
// 获取查询条件基础信息
const getBaseData = async () => {
	try {
		const [res, res1] = await Promise.all([treeArea(), centerTodoBase()]);
		const mappings: any = {
			orderStatusOptions: 'orderStatus',
			industryOptions: 'industry',
		};
		for (const key in mappings) {
			state[key] = res1.result?.[mappings[key]] ?? [];
		}
		state.areaOptions = res.result ?? []; //省市区数据
	} catch (error) {
		console.log(error);
	}
};
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();
	});
});
</script>
