<template>
	<div class="business-countersign-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="fastSearch">
					<el-segmented
						:options="[
							{
								value: 'InitiatedCountersignature',
								label: '发起的会签',
							},
							{
								value: 'HandleCountersignature',
								label: '已办会签',
							},
						]"
						v-model="fastSearch"
						@change="fastSearchChange"
						:disabled="state.loading"
					/>
				</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="OrderNo">
					<el-input v-model.trim="state.queryParams.OrderNo" 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"> <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" v-auth="'business:order:jbdExport'"
						><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
					:print-config="{}"
					:scrollY="{ enabled: true, gt: 100 }"
					id="businessOrder"
					:custom-config="{
						storage: true,
					}"
					:params="{ exportMethod: countersignDataExport, exportParams: requestParams }"
					showHeaderOverflow
				>
					<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="stateText" title="会签状态" width="100"></vxe-column>
					<vxe-column field="order.counterSignTypeText" title="会签类型" width="100"></vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="100"></vxe-column>
					<vxe-column field="order.currentStepName" title="当前节点" width="120"></vxe-column>
					<vxe-column field="order.startTime" title="受理时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.order?.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="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.fromPhone" title="来电号码" width="150"></vxe-column>
					<vxe-column field="order.actualHandleOrgName" title="接办部门" width="150"></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="starterOrgName" title="会签发起部门" width="150"></vxe-column>
					<vxe-column field="starterName" title="会签发起人" width="150"></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 title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button type="primary" link @click="onRecord(row)" class="ml10">流程明细</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>
		<!-- 流转记录 -->
		<audit-record ref="auditRecordRef"></audit-record>
		<!--	更多查询	-->
		<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="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="Channel">
					<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="会签类型" prop="CounterSignType">
					<el-select v-model="state.queryParams.CounterSignType" placeholder="会签类型" class="w100" @change="handleQuery" clearable>
						<el-option v-for="item in state.counterSignTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="Hotspot">
					<el-input v-model="state.queryParams.Hotspot" placeholder="热点分类名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办部门" prop="OrgId">
					<el-cascader
						:options="state.orgsOptions"
						filterable
						:props="{ checkStrictly: true, value: 'id', label: 'name', emitPath: false }"
						placeholder="请选择接办部门"
						clearable
						class="w100"
						v-model="state.queryParams.OrgId"
						ref="cascadeRef"
						@change="handleQuery"
					>
					</el-cascader>
				</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-detail ref="processDetailRef"></process-detail>
	</div>
</template>
<script setup lang="tsx" name="businessCountersign">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { countersignBase, countersignData, countersignDataExport } from '@/api/query/countersign';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { getOrgListByUser } from '@/api/system/organize';
import { exportAssignment } from '@/utils/tools';
import Other from '@/utils/other';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const AuditRecord = defineAsyncComponent(() => import('@/components/AuditRecord/index.vue')); // 流程明细
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const ProcessDetail = defineAsyncComponent(() => import('@/components/ProcessDetail/index.vue')); // 流程明细

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 关键字
		IsOnlyStarter: false, // 是否中心
		HandleCountersignature: null, // 已办会签
		InitiatedCountersignature: true, // 是否发起会签
		Hotspot: null, // 热点分类
		ActualHandleStepName: null, // 办理节点
		Channel: null, // 来源渠道
		AcceptType: null, // 受理类型
		Title: null,
		OrderNo: null,
		OrgId: null, // 接办部门名称
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源渠道
	counterSignTypeOptions: [], // 会签类型
	orgsOptions: [], // 接办部门
});
const fastSearch = ref('InitiatedCountersignature');
const fastSearchChange = (val: any) => {
	fastSearch.value = val;
	state.queryParams.HandleCountersignature = null;
	state.queryParams.InitiatedCountersignature = null;
	switch (val) {
		case 'InitiatedCountersignature':
			state.queryParams.InitiatedCountersignature = true;
			break;
		case 'HandleCountersignature':
			state.queryParams.HandleCountersignature = true;
			break;
	}
	handleQuery();
};
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	return new Promise((resolve, reject) => {
		state.loading = true;
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.IsOnlyStarter = userInfos.value.isCenter;
		countersignData(requestParams.value)
			.then((res) => {
				state.tableData = res.result?.items ?? [];
				state.total = res.result?.total ?? 0;
				state.loading = false;
				tableRef.value.clearCheckboxRow();
				checkTable.value = [];
				resolve(res);
			})
			.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();
	fastSearch.value = 'InitiatedCountersignature';
	state.queryParams.HandleCountersignature = null;
	state.queryParams.InitiatedCountersignature = true;
	ruleFormRef.value?.resetFields();
	queryList();
};
// 流转记录
const auditRecordRef = ref<RefType>(); // 流转记录
const processDetailRef = ref<RefType>();
const onRecord = (row:any) => {
	const params = {
		dialogTitle: '流转记录',
		...row.order,
	};
	auditRecordRef.value.openDialog(params);
	// processDetailRef.value.openDialog(params);
};
// 查询基础信息
const baseInfo = async () => {
	try {
		const [orgRes, baseRes] = await Promise.all([getOrgListByUser(), countersignBase()]);
		state.acceptTypeOptions = baseRes.result.acceptTypeOptions;
		state.channelOptions = baseRes.result.channelOptions;
		state.counterSignTypeOptions = baseRes.result.counterSignType;
		state.orgsOptions = orgRes.result ?? [];
	} catch (e) {
		console.log(e);
	}
};
// 交办单导出
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(() => {
		baseInfo();
	});
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
