<template>
	<div class="business-discern-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="DataScope">
					<el-segmented
						:options="[
							{
								value: 0,
								label: '全部',
							},
							{
								value: 1,
								label: '我发起的',
							},
						]"
						v-model="state.queryParams.DataScope"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="快捷查询" prop="DataScope" v-if="['ZiGong'].includes(themeConfig.appScope)">
					<el-segmented
						:options="[
							{
								value: -1,
								label: '全部',
							},
							{
								value: 0,
								label: '部门办件甄别',
							},
							{
								value: 1,
								label: '中心话务甄别',
							},
						]"
						v-model="state.queryParams.QueryScreenType"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="甄别状态" prop="Status">
					<el-select v-model="state.queryParams.Status" placeholder="请选择甄别状态" @change="handleQuery" clearable>
						<el-option v-for="item in state.screenStatus" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</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"
					: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="businessDiscern"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:params="{ exportMethod: screenListExport, exportParams: requestParams }"
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="order.expiredStatusText" title="状态" width="90" align="center">
						<template #default="{ row }">
							<span :class="'overdue-status-' + row.order?.expiredStatus" :title="row.order?.expiredStatusText"></span>
						</template>
					</vxe-column>
					<vxe-column field="statusText" title="甄别状态" width="100"></vxe-column>
					<vxe-column field="workflow.actualHandleStepName" title="当前审核节点" width="120"></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.hotspotName" title="热点分类" width="150"></vxe-column>
					<vxe-column field="screenTypeText" title="甄别类型" width="120"></vxe-column>
					<vxe-column field="visitDetail.visitOrgName" title="被回访部门" width="140"></vxe-column>
					<vxe-column field="creatorName" title="申请人" width="120"></vxe-column>
					<vxe-column field="creatorOrgName" title="申请部门" width="140"></vxe-column>
					<vxe-column field="typeDicName" 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="timeConsuminText" title="发起甄别耗时(工作日)" width="160"></vxe-column>
					<vxe-column title="操作" fixed="right" width="160" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onDetail(row)" title="查看甄别详情"> 甄别详情 </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>
		<!-- 甄别详情 -->
		<discern-detail ref="discernDetailRef" @updateList="queryList" />
		<!-- 甄别修改 -->
		<discern-edit ref="discernEditRef" @updateList="queryList" />
		<!-- 回访详情 -->
		<visit-detail-com ref="visitDetailRef" @updateList="queryList" />
		<!--	更多查询	-->
		<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="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 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="AcceptType">
					<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" clearable class="w100" @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 class="w100" @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="VisitOrgName">
					<el-input v-model="state.queryParams.VisitOrgName" placeholder="被回访部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="申请部门" prop="CreatorOrgName">
					<el-input v-model="state.queryParams.CreatorOrgName" placeholder="申请部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="申请人" prop="CreatorName">
					<el-input v-model="state.queryParams.CreatorName" placeholder="申请人名称" clearable @keyup.enter="handleQuery" />
				</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-item label="联系电话" prop="Contact">
					<el-input v-model="state.queryParams.Contact" placeholder="联系电话" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="来电号码" prop="FromPhone">
					<el-input v-model="state.queryParams.FromPhone" placeholder="来电号码" clearable @keyup.enter="handleQuery" />
				</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="businessDiscern">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { screenBaseData, screenDetail, screenList, screenListExport } from '@/api/business/discern';
import Other from '@/utils/other';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { exportAssignment } from '@/utils/tools';

// 引入组件
const DiscernDetail = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-detail.vue')); // 甄别详情
const DiscernEdit = defineAsyncComponent(() => import('@/views/business/discern/components/Discern-edit.vue')); //  甄别修改
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const VisitDetailCom = defineAsyncComponent(() => import('@/views/business/visit/components/Visit-detail.vue')); // 回访
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		source: '2', // 甄别列表 2
		Status: null, // 甄别状态
		DataScope: 0, // 快捷查询
		No: null, // 工单编码
		Title: null, // 工单标题
		IsProvince: null, // 省/市工单
		IsHomePage: null, // 是否首页进入
		AcceptType: null, // 受理类型
		HotspotSpliceName: null, // 热点分类
		SourceChannel: null, // 来源渠道
		VisitOrgName: null, // 被回访部门
		CreatorOrgName: null, // 申请部门
		CreatorName: null, // 申请人
		crTime: [], // 申请时间
		CreationTimeStart: null,
		CreationTimeEnd: null,
		SortField: null, // 排序字段
		SortRule: null, // 排序字段
		Contact: null, // 联系电话
		FromPhone: null, // 来电电话
		QueryScreenType: 0, // 甄别类型
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	screenStatus: [], // 甄别状态
	screenType: [], // 甄别类型
	acceptTypeOptions: [], // 受理类型
	sourceChannelOptions: [], // 来源渠道
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 获取查询条件基础信息
const getBaseData = async () => {
	const { result } = await screenBaseData();
	state.screenStatus = result?.screenStatus ?? [];
	state.screenType = result?.screenType ?? [];
	state.acceptTypeOptions = result?.acceptType ?? [];
	state.sourceChannelOptions = result?.sourceChannel ?? [];
};
// 手动查询，将页码设置为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.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;
		screenList(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();
	ruleFormRef.value?.resetFields();
	queryList();
};
// 排序
const sortChange = (val: any) => {
	state.queryParams.SortField = val.order ? val.prop : null;
	// 0 升序 1 降序
	state.queryParams.SortRule = val.order ? (val.order == 'descending' ? 1 : 0) : null;
	queryList();
};
// 查看详情
const discernDetailRef = ref<RefType>(); // 甄别详情ref
const discernEditRef = ref<RefType>(); // 甄别修改ref
const onDetail = async (row: any) => {
	try {
		const { result } = await screenDetail(row.id);
		if (result.handle) {
			// 退回到了开始 需要重新打开编辑页面在发起流程
			discernEditRef.value.openDialog(row);
		} else {
			discernDetailRef.value.openDialog(row);
		}
	} catch (e) {
		console.log(e);
	}
};
// 查看回访明细
const visitDetailRef = ref<RefType>();
const visitDetail = (row: any) => {
	visitDetailRef.value.openDialog(row.visit, '回访明细');
};
// 交办单导出
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(async () => {
	queryList().then(() => {
		getBaseData();
	});
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
