<template>
	<div class="judicial-order-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item label="工单标题" prop="Title">
					<el-input v-model="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="工单编码" prop="No">
					<el-input v-model="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" :loading="state.loading">
						<SvgIcon name="ele-Search" class="mr5" />更多查询</el-button
					>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
				:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
			>
				<template #buttons>
					<el-button type="primary" @click="onAddOrder" v-auth="'judicial:custom:add'" :loading="state.loading">
						<SvgIcon name="ele-Plus" class="mr5" />新建工单
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30,useKey: true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="judicialCustom"
					:custom-config="{ storage: true }"
					:params="{ exportMethod: judicialListExport, exportParams: requestParams }"
					showHeaderOverflow
				>
					<vxe-column field="no" title="工单编码" width="160"></vxe-column>
					<vxe-column field="title" title="工单标题" min-width="200">
						<template #default="{ row }">
							<order-detail :order="row" @updateList="queryList">{{ row.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="enforcementOrdersHandlerText" title="执法部门" min-width="150"></vxe-column>
					<vxe-column field="incidentAddressText" title="事发地址" min-width="150"></vxe-column>
					<vxe-column field="isItCounted" title="状态" width="100">
						<template #default="{ row }">
							<el-switch v-model="row.isItCounted" active-text="启用" inactive-text="禁用" @change="changeIsEnable(row)" inline-prompt size="small" />
						</template>
					</vxe-column>
					<vxe-column field="creationTime" title="生成时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="90" align="center" :show-overflow="false">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row)" title="修改"> 修改 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</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="AcceptTypeCode">
					<el-select v-model="state.queryParams.AcceptTypeCode" placeholder="请选择受理类型" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.acceptTypeOptions" :value="item.value" :key="item.value" :label="item.key" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="HotspotId">
					<el-tree-select
						v-model="state.queryParams.HotspotId"
						:data="state.enforcementHotspot"
						:render-after-expand="false"
						class="w100"
						node-key="id"
						:props="{
							isLeaf: 'hasChild',
							children: 'children',
							label: 'hotSpotFullName',
						}"
						placeholder="请选择热点分类"
						filterable
						expand-on-click-node
						@change="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="执法部门" prop="OrgCode">
					<el-select v-model="state.queryParams.OrgCode" placeholder="请选择执法部门" class="w100" @change="handleQuery">
						<el-option v-for="item in state.orgsOptions" :key="item.id" :label="item.name" :value="item.id" />
					</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 label="生成时间" prop="crTime">
					<el-date-picker
						v-model="state.queryParams.crTime"
						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>
			<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="judicialCustom">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { useRouter } from 'vue-router';
import { formatDate } from '@/utils/formatTime';
import { treeArea } from '@/api/auxiliary/area';
import { listBaseData } from '@/api/judicial';
import { enableJudicial, judicialList, judicialListExport } from '@/api/judicial/order';
import Other from '@/utils/other';
import { ElMessage, ElMessageBox } from 'element-plus';

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/views/judicial/order/components/orderDetail.vue')); // 工单详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		// 查询条件
		No: null, // 工单编码
		Title: null,
		HotspotId: null,
		AcceptTypeCode: null,
		OrgCode: null,
		AreaCode: null,
		crTime: [],
		CreationTimeStart: null,
		CreationTimeEnd: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	acceptTypeOptions: [], //受理类型
	channelOptions: [], // 来源频道
	orgsOptions: [], // 部门
	enforcementHotspot: [], // 热点类型
	areaOptions: [], // 省市区数据
});
const router = useRouter(); // 路由
// 获取查询条件基础信息
const getBaseData = async () => {
	try {
		const res: any = await listBaseData();
		const mappings: any = {
			acceptTypeOptions: 'acceptTypeOptions',
			channelOptions: 'channelOptions',
			orgsOptions: 'orgsOptions',
			enforcementHotspot: 'enforcementHotspot',
		};
		for (const key in mappings) {
			state[key] = res.result?.[mappings[key]] ?? [];
		}
		const area = await treeArea();
		state.areaOptions = area?.result ?? []; //省市区数据
	} catch (error) {
		console.log(error);
	}
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.CreationTimeStart = state.queryParams.crTime === null ? null : state.queryParams.crTime[0]; // 生成时间
	requestParams.value.CreationTimeEnd = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime'); // 删除无用的参数
	state.loading = true;
	judicialList(requestParams.value)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			state.loading = false;
		})
		.catch(() => {
			state.loading = 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();
	queryList();
};
// 修改工单
const onEdit = (row: any) => {
	router.push({
		path: '/judicial/order/add',
		query: {
			id: row.id,
		},
	});
};
//  修改是否启用
const changeIsEnable = (row: any) => {
	row.isItCounted = !row.isItCounted; //保持switch点击前的状态
	ElMessageBox.confirm(`您确定要${row.isItCounted ? '禁用' : '启用'}：【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			enableJudicial(row.id)
				.then(() => {
					ElMessage.success('操作成功');
					queryList();
				})
				.catch(() => {
					queryList();
				});
		})
		.catch(() => {
			// queryList();
		});
};
// 新建工单
const onAddOrder = () => {
	router.push({
		path: '/judicial/order/add',
	});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
