<template>
	<div class="business-second-handle-audit-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.Status" @tab-change="handleQuery">
				<el-tab-pane :name="1" label="待审批" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane :name="4" label="已审批" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item label="关键词" prop="Keyword">
					<el-input v-model.trim="state.queryParams.Keyword" placeholder="工单编码/标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<!--        <el-form-item label="申请状态" prop="Status">
									<el-select v-model="state.queryParams.Status" placeholder="请选择申请状态" clearable @change="handleQuery">
										<el-option v-for="item in state.statusOptions" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</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>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" 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="onAuditMultiple"
						v-auth="'business:secondHandle:audit:multiple'"
						:disabled="isChecked"
						v-if="state.queryParams.Status === 1"
						>批量审批<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="businessSecondHandleAudit"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:params="{ exportMethod: secondHandleAuditExport, exportParams: requestParams }"
				>
					<vxe-column type="checkbox" width="60" align="center" :visible="state.queryParams.Status === 1"></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="order.no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="stateText" title="办理状态" width="100"></vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
					<vxe-column field="sendBack" title="重提办理" width="90"></vxe-column>
					<vxe-column field="order.title" title="工单标题" min-width="200">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="queryList">{{ row.order?.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="creatorName" title="申请人" width="120"></vxe-column>
					<vxe-column field="creatorOrgName" title="申请部门" width="140"></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.acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="order.hotspotName" title="热点分类" width="140"></vxe-column>
					<vxe-column title="操作" fixed="right" width="120" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onView(row)" title="查看办理明细" v-if="![1].includes(row.state)"> 办理明细 </el-button>
							<el-button
								link
								type="primary"
								@click="onReturn(row)"
								title="退回"
								v-auth="'business:secondHandle:return'"
								v-if="[1].includes(row.state)"
							>
								退回
							</el-button>
							<el-button link type="primary" @click="onAudit(row)" title="审批" v-auth="'business:secondHandle:audit'" v-if="[1].includes(row.state)">
								审批
							</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>
		<second-handle-return ref="secondHandleReturnRef" @updateList="queryList" />
		<second-handle-audit ref="secondHandleAuditRef" @updateList="queryList" />
		<second-handle-audit-multiple ref="secondHandleAuditMultipleRef" @updateList="queryList" />
		<!--  办理明细  -->
		<second-handle-detail ref="secondHandleDetailRef" @updateList="queryList" />
	</div>
</template>
<script setup lang="tsx" name="businessSecondHandleAudit">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { secondHandleAuditExport, secondHandleAuditList, secondHandleBase } from '@/api/business/secondHandle';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import other from '@/utils/other';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const SecondHandleReturn = defineAsyncComponent(() => import('@/views/business/secondHandle/components/Second-handle-return.vue')); // 二次办理退回
const SecondHandleAudit = defineAsyncComponent(() => import('@/views/business/secondHandle/components/Second-handle-audit.vue')); // 二次办理审批
const SecondHandleAuditMultiple = defineAsyncComponent(() => import('@/views/business/secondHandle/components/Second-handle-audit-multiple.vue')); // 二次办理审批批量
const SecondHandleDetail = defineAsyncComponent(() => import('@/views/business/secondHandle/components/Second-handle-detail.vue')); // 办理明细
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 关键字
		Status: 1, // 状态
		crTime: [],
		CreationTimeStart: null,
		CreationTimeEnd: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	statusOptions: [],
});
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	requestParams.value = other.deepClone(state.queryParams);
	requestParams.value.StCreationTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	requestParams.value.EndCreationTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime');
	secondHandleAuditList(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 resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 批量审批
const secondHandleAuditMultipleRef = ref<RefType>();
const onAuditMultiple = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	secondHandleAuditMultipleRef.value.openDialog(ids);
};
// 查看详情
const secondHandleDetailRef = ref<RefType>();
const onView = (row: any) => {
	secondHandleDetailRef.value.openDialog(row.id);
};
// 退回
const secondHandleReturnRef = ref<RefType>();
const onReturn = (row: any) => {
	secondHandleReturnRef.value.openDialog(row);
};
// 审批
const secondHandleAuditRef = ref<RefType>();
const onAudit = (row: any) => {
	secondHandleAuditRef.value.openDialog(row);
};
// 获取基础数据
const getBaseData = async () => {
	try {
		const { result } = await secondHandleBase();
		state.statusOptions = result?.status ?? [];
	} catch (e) {
		console.log(e);
	}
};
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();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
