<template>
	<div class="business-discern-apply-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.ScreenType" @tab-change="handleQuery">
				<el-tab-pane :name="0" label="部门办件甄别" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane :name="1" label="中心话务甄别" v-if="userInfos.isCenter" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item label="甄别退回" prop="ScreenSendBack">
					<el-select v-model="state.queryParams.ScreenSendBack" placeholder="请选择甄别退回" @change="handleQuery">
						<el-option :value="0" label="全部" />
						<el-option :value="1" label="是" />
						<el-option :value="2" label="否" />
					</el-select>
				</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="工单标题" 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,
				}"
				:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
			>
				<template #buttons>
					<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"
					:sort-config="{ remote: true }"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
					ref="tableRef"
					@sort-change="sortChange"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="businessDiscernZGApply"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:params="{ exportMethod: screenApplyListExport, exportParams: requestParams }"
				>
					<vxe-column type="checkbox" width="50" 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="screenByEndTime" title="截止申请日期" width="160" sortable>
						<template #default="{ row }">
							{{ formatDate(row.screenByEndTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="screenSendBackText" title="甄别退回" width="90"></vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="order.isProvinceText" title="省/市工单" width="90"></vxe-column>
					<vxe-column field="order.title" title="工单标题" width="200">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="queryList">{{ row.order?.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="order.acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
					<vxe-column field="order.orgLevelOneName" title="一级部门" width="140"></vxe-column>
					<vxe-column field="order.actualHandleOrgName" title="接办部门" width="140"></vxe-column>
					<vxe-column field="visitOrgName" title="被回访部门" width="140"></vxe-column>
					<vxe-column field="order.acceptorName" title="受理人" width="120" v-if="state.queryParams.ScreenType === 1"></vxe-column>
					<vxe-column field="order.startTime" title="受理时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="order.actualHandleTime" title="接办时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template> </vxe-column
					><vxe-column field="order.filedTime" title="办结时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.filedTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="orderVisit.visitTime" title="回访时间" sortable width="160">
						<template #default="{ row }">
							{{ formatDate(row.orderVisit?.visitTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="340" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="submitDiscern(row)" title="发起甄别申请" v-auth="'business:discern:apply:submit'">
								发起甄别
							</el-button>
							<el-button link type="primary" @click="onEditApplyTime(row)" title="修改甄别提起时限" v-auth="'business:discern:apply:editApplyTime'">
								修改提起时限
							</el-button>
							<el-button link type="primary" @click="onDetail(row)" title="查看甄别详情" v-if="row.screenSendBack"> 甄别详情 </el-button>
							<el-button link type="primary" @click="visitDetail(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="IsProvince">
					<el-select v-model="state.queryParams.IsProvince" clearable placeholder="请选择省/市工单" @change="handleQuery">
						<el-option :value="false" label="市工单" />
						<el-option :value="true" label="省工单" />
					</el-select>
				</el-form-item>
				<el-form-item label="受理人" prop="NameOrNo" v-if="state.queryParams.ScreenType === 1">
					<el-input v-model="state.queryParams.NameOrNo" placeholder="受理人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="受理类型" prop="AcceptType">
					<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" clearable @change="handleQuery">
						<el-option v-for="item in state.acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="HotspotSpliceName">
					<el-input v-model="state.queryParams.HotspotSpliceName" placeholder="热点分类名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="来源渠道" prop="SourceChannel">
					<el-select v-model="state.queryParams.SourceChannel" placeholder="请选择来源渠道" clearable @change="handleQuery">
						<el-option v-for="item in state.sourceChannelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="一级部门" prop="OrgLevelOneName">
					<el-input v-model="state.queryParams.OrgLevelOneName" placeholder="一级部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办部门" prop="ActualHandleOrgName">
					<el-input v-model="state.queryParams.ActualHandleOrgName" placeholder="接办部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="被回访部门" prop="VisitOrgName">
					<el-input v-model="state.queryParams.VisitOrgName" placeholder="被回访部门名称" clearable @keyup.enter="handleQuery" />
				</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="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-item label="回访时间" prop="hfTime">
					<el-date-picker
						v-model="state.queryParams.hfTime"
						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>
		<!-- 流程审批 -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="queryList" />
		<!-- 回访详情 -->
		<visit-detail-com ref="visitDetailRef" @updateList="queryList" />
		<!-- 甄别详情 -->
		<discern-detail ref="discernDetailRef" @updateList="queryList" />
		<!-- 甄别修改 -->
		<discern-edit ref="discernEditRef" @orderProcessSuccess="queryList" />
		<!--	甄别申请	-->
		<discern-apply ref="discernApplyRef" @orderProcessSuccess="queryList" />
		<!-- 修改甄别提起时限 -->
		<discern-edit-apply-time ref="discernEditApplyTimeRef" @updateList="queryList" />
	</div>
</template>
<script setup lang="tsx" name="businessDiscernZGApply">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { screenApplyList, screenApplyListExport, screenBaseData } from '@/api/business/discern';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { useUserInfo } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import {  exportAssignment } from '@/utils/tools';
// 引入组件
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const VisitDetailCom = defineAsyncComponent(() => import('@/views/business/visit/components/Visit-detail.vue')); // 回访
const DiscernDetail = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-detail.vue')); // 甄别详情
const DiscernEdit = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-edit.vue')); // 甄别修改
const DiscernEditApplyTime = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-edit-apply-time.vue')); // 修改甄别提起时限
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const DiscernApply = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-apply.vue')); // 甄别申请
// 定义变量内容
const stores = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(stores); // 用户信息
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		ScreenSendBack: 0, // 甄别退回
		No: null, // 工单编码
		Title: null, // 工单标题
		IsProvince: null, // 省/市工单
		IsHomePage: null, // 是否首页进入
		AcceptType: null, // 受理类型
		HotspotSpliceName: null, // 热点分类
		SourceChannel: null, // 来源渠道
		OrgLevelOneName: null, // 一级部门
		ActualHandleOrgName: null, // 接办部门名称
		VisitOrgName: null, // 被回访部门
		slTime: [], // 受理时间
		CreationTime: null,
		EndCreationTime: null,
		jbTime: [], // 接办时间
		CurrentHandleTime: null,
		EndCurrentHandleTime: null,
		bjTime: [], // 办结时间
		FiledTime: null,
		EndFiledTime: null,
		hfTime: [], // 回访时间
		VisitTime: null,
		EndVisitTime: null,
		SortField: null,
		SortRule: null,
		ScreenType: 0, // 部门还是中心 默认部门
		NameOrNo: null, // 受理人
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	screenStatus: [], // 甄别状态
	screenType: [], // 甄别类型
	counterSignTypeOptions: [], // 会签类型
	acceptTypeOptions: [], // 受理类型
	sourceChannelOptions: [], // 来源渠道
});
// 获取查询条件基础信息
const getBaseData = async () => {
	try {
		const { result } = await screenBaseData();
		state.screenStatus = result?.screenStatus ?? [];
		state.screenType = result?.screenType ?? [];
		state.counterSignTypeOptions = result?.counterSignType ?? [];
		state.acceptTypeOptions = result?.acceptType ?? [];
		state.sourceChannelOptions = result?.sourceChannel ?? [];
		state.visitSatisfaction = result?.visitSatisfaction ?? [];
		state.dissatisfiedReason = result?.dissatisfiedReason ?? [];
	} catch (e) {
		console.log(e);
	}
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	return new Promise((resolve, reject) => {
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.CreationTime = state.queryParams.slTime === null ? null : state.queryParams.slTime[0]; // 受理时间
		requestParams.value.EndCreationTime = state.queryParams.slTime === null ? null : state.queryParams.slTime[1];
		Reflect.deleteProperty(requestParams.value, 'slTime'); // 删除无用的参数
		requestParams.value.CurrentHandleTime = state.queryParams.jbTime === null ? null : state.queryParams.jbTime[0]; // 接办时间
		requestParams.value.EndCurrentHandleTime = state.queryParams.jbTime === null ? null : state.queryParams.jbTime[1];
		Reflect.deleteProperty(requestParams.value, 'jbTime'); // 删除无用的参数
		requestParams.value.FiledTime = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[0]; // 办结时间
		requestParams.value.EndFiledTime = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[1];
		Reflect.deleteProperty(requestParams.value, 'bjTime'); // 删除无用的参数
		requestParams.value.VisitTime = state.queryParams.hfTime === null ? null : state.queryParams.hfTime[0]; // 回访时间
		requestParams.value.EndVisitTime = state.queryParams.hfTime === null ? null : state.queryParams.hfTime[1];
		Reflect.deleteProperty(requestParams.value, 'hfTime'); // 删除无用的参数
		state.loading = true;
		screenApplyList(requestParams.value)
			.then((response: any) => {
				state.tableData = response?.result.items ?? [];
				state.total = response?.result.total;
				state.loading = false;
				tableRef.value.clearCheckboxRow();
				checkTable.value = [];
				resolve(response);
			})
			.catch(() => {
				state.loading = false;
				tableRef.value.clearCheckboxRow();
				checkTable.value = [];
				reject();
			});
	});
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.IsHomePage = null;
	ruleFormRef.value?.resetFields();
	queryList();
};
// 排序
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;
	queryList();
};
// 甄别审批
const processAuditRef = ref<RefType>(); // 流程审批ref
const discernEditRef = ref<RefType>(); // 甄别修改ref
const discernApplyRef = ref<RefType>(); // 申请甄别
//  ScreenType 中心1 部门0
const submitDiscern = (row: any) => {
	if (row.screenSendBack) {
		if (row.orderScreens.length) {
			const editRow = { ...row.orderScreens[0], screenType: state.queryParams.ScreenType };
			// 修改甄别
			// 退回到了开始 需要重新打开编辑页面在发起流程
			discernEditRef.value.openDialog(editRow);
		}
	} else {
		const orderDetail = {
			visitId: row.visitId,
			visitDetailId: row.id,
			...row.order,
		};
		const params = {
			id: row.id,
			orderDetail,
			extra: {
				screenType: state.queryParams.ScreenType,
			},
		};
		discernApplyRef.value.openDialog(params);
	}
};
// 查看甄别详情
const discernDetailRef = ref<RefType>();
const onDetail = (row: any) => {
	if (row && row.orderScreens && row.orderScreens.length) {
		const params = {
			id: row.orderScreens[0].id,
		};
		discernDetailRef.value.openDialog(params);
	}
};
// 查看回访明细
const visitDetailRef = ref<RefType>();
const visitDetail = (row: any) => {
	visitDetailRef.value.openDialog(row.orderVisit, '回访明细');
};
// 修改甄别提起时限
const discernEditApplyTimeRef = ref<RefType>();
const onEditApplyTime = (row: any) => {
	discernEditApplyTimeRef.value.openDialog(row);
};
// 交办单导出
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 toolbarRef = ref<RefType>();
onMounted(() => {
	queryList().then(() => {
		getBaseData();
	});
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
