<template>
	<div class="business-end-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline :disabled="state.loading">
				<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="工单标题" prop="Title">
					<el-input v-model.trim="state.queryParams.Title" 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>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="oncancelEnd" v-auth="'business:order:end'" :disabled="isChecked">
						<SvgIcon name="ele-Stopwatch" class="mr5" />取消终结件<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</el-button>
					<el-button type="primary" @click="onJbExport" :disabled="isChecked" :loading="state.loading"
						><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</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"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="businessEnd"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column type="checkbox" width="60" align="center"></vxe-column>
					<vxe-column field="order.expiredStatusText" title="状态" width="60" align="center">
						<template #default="{ row }">
							<span :class="'overdue-status-' + row.order?.expiredStatus" :title="row.order?.expiredStatusText"></span>
						</template>
					</vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="order.statusText" title="工单状态" width="100">
						<template #default="{ row }">
							<el-text type="danger" tag="b" v-if="[1, 2, 3, 9, 101, 102, 103, 104, 105, 200].includes(row.order.status)">{{
								row.order.statusText
							}}</el-text>
							<span v-else>{{ row.order.statusText }}</span>
						</template>
					</vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
					<vxe-column field="order.currentStepName" title="当前节点" width="110"></vxe-column>
					<vxe-column field="order.title" title="工单标题" min-width="200">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="refreshList">{{ row.order?.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="order.creationTime" title="受理时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="creatorName" title="设置人" width="120"></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 field="order.expiredTime" title="期满时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="order.acceptType" title="受理类型" width="110"></vxe-column>
					<vxe-column field="order.hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="order.actualHandleOrgName" title="接办部门" width="140"></vxe-column>
					<vxe-column field="order.actualHandleTime" title="接办时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.actualHandleTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="order.filedTime" title="办结时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.filedTime, 'YYYY-mm-dd HH:MM:SS') }}
						</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" :disabled="state.loading">
				<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 prop="Channel" label="来源渠道">
					<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<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.value" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="受理时间" prop="slTime">
					<el-date-picker
						v-model="state.queryParams.slTime"
						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="CreatorName">
					<el-input v-model.trim="state.queryParams.CreatorName" placeholder="设置人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="设置时间" prop="szTime">
					<el-date-picker
						v-model="state.queryParams.szTime"
						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="qmTime">
					<el-date-picker
						v-model="state.queryParams.qmTime"
						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 prop="AcceptTypeCode" label="受理类型">
					<el-select v-model="state.queryParams.AcceptTypeCode" placeholder="请选择受理类型" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="Hotspot">
					<el-input v-model.trim="state.queryParams.Hotspot" placeholder="热点分类" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办部门" prop="CurrentHandleOrgName">
					<el-input v-model.trim="state.queryParams.CurrentHandleOrgName" placeholder="接办部门" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办时间" prop="jbTime">
					<el-date-picker
						v-model="state.queryParams.jbTime"
						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="bjTime">
					<el-date-picker
						v-model="state.queryParams.bjTime"
						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="businessEnd">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { deleteEnd, endList } from '@/api/query/end';
import { exportAssignment } from '@/utils/tools';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { orderBaseData } from '@/api/business/order';
import Other from '@/utils/other';
// 引入组件
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,
		No: null, // 工单编码
		Title: null, // 工单编码
		Status:null, // 工单状态
		Channel:null, // 来源渠道
		CurrentStepCode:null, // 当前节点
		slTime:[], // 受理时间
		CreationTimeStart:null, // 受理时间 开始
		CreationTimeEnd:null, // 受理时间 结束
		CreatorName:null, // 设置人
		szTime:[], // 设置时间
		SetCreationTimeStart:null, // 设置时间 开始
		SetCreationTimeEnd:null, // 设置时间 结束
		qmTime:[], // 期满时间
		ExpiredTimeStart:null, // 期满时间 开始
		ExpiredTimeEnd:null, // 期满时间 结束
		AcceptTypeCode:null, // 受理类型
		Hotspot:null, // 热点分类
		CurrentHandleOrgName:null, // 接办部门
		jbTime:[], // 接办时间
		CurrentHandleTimeStart:null, // 接办时间 开始
		CurrentHandleTimeEnd:null, // 接办时间 结束
		bjTime:[], // 办结时间
		FiledTimeStart:null, // 办结时间 开始
		FiledTimeEnd:null, // 办结时间 结束
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 刷新列表
const refreshList = () => {
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.CreationTimeStart  = state.queryParams.slTime === null ? null : state.queryParams.slTime[0]; // 受理时间
	requestParams.value.CreationTimeEnd = state.queryParams.slTime === null ? null : state.queryParams.slTime[1];
	Reflect.deleteProperty(requestParams.value, 'slTime'); // 删除无用的参数
	requestParams.value.SetCreationTimeStart  = state.queryParams.szTime === null ? null : state.queryParams.szTime[0]; // 设置时间
	requestParams.value.SetCreationTimeEnd = state.queryParams.szTime === null ? null : state.queryParams.szTime[1];
	Reflect.deleteProperty(requestParams.value, 'szTime'); // 删除无用的参数
	requestParams.value.ExpiredTimeStart  = state.queryParams.qmTime === null ? null : state.queryParams.qmTime[0]; // 期满时间
	requestParams.value.ExpiredTimeEnd = state.queryParams.qmTime === null ? null : state.queryParams.qmTime[1];
	Reflect.deleteProperty(requestParams.value, 'qmTime'); // 删除无用的参数
	requestParams.value.CurrentHandleTimeStart  = state.queryParams.jbTime === null ? null : state.queryParams.jbTime[0]; // 接办时间
	requestParams.value.CurrentHandleTimeEnd = state.queryParams.jbTime === null ? null : state.queryParams.jbTime[1];
	Reflect.deleteProperty(requestParams.value, 'jbTime'); // 删除无用的参数
	requestParams.value.FiledTimeStart  = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[0]; // 办结时间
	requestParams.value.FiledTimeEnd = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[1];
	Reflect.deleteProperty(requestParams.value, 'bjTime'); // 删除无用的参数
	endList(requestParams.value)
		.then((res) => {
			state.tableData = res?.result.items ?? [];
			state.total = res?.result.total;
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.finally(() => {
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		});
};

/** 重置按钮操作 */
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 oncancelEnd = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定选中的工单取消终结件吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			deleteEnd({ ids }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 交办单导出
const onJbExport = () => {
	const ids = checkTable.value.map((item: any) => item.order.id);
	exportAssignment(ids);
};
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 channelOptions = ref<EmptyArrayType>([]); // 来源渠道
const orderStatusOptions = ref<EmptyArrayType>([]); // 工单状态
const acceptTypeOptions = ref<EmptyArrayType>([]); // 受理类型
const currentStepOptions = ref<EmptyArrayType>([]); // 当前节点
const getBaseData = async () => {
	try {
		const { result } = await orderBaseData();
		channelOptions.value = result.channelOptions ?? [];
		orderStatusOptions.value = result.orderStatusOptions ?? [];
		acceptTypeOptions.value = result.acceptTypeOptions ?? [];
		currentStepOptions.value = result.currentStepOptions ?? [];
	} catch (e) {
		console.log(e);
	}
};
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
