<template>
	<div class="business-return-audit-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.AuditState" @tab-change="handleQuery">
				<el-tab-pane name="1" label="退回待审批" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="2" 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="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="State" v-if="state.queryParams.AuditState === '2'">
					<el-select v-model="state.queryParams.State" placeholder="请选择审批状态" @change="handleQuery">
						<el-option value="1" label="审批通过" />
						<el-option value="2" label="审批拒绝" />
					</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="resetQuery(ruleFormRef)" 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,
				}"
			>
				<template #buttons>
					<el-button
						type="primary"
						@click="onAuditMultiple"
						:disabled="isChecked"
						:loading="state.loading"
						v-auth="'business:return:audit:multiple'"
						v-if="state.queryParams.AuditState === '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"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="businessReturnAudit"
					:custom-config="{
						storage: true,
					}"
					showHeaderOverflow
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
				>
					<vxe-column type="checkbox" field="checkbox" width="50" align="center" :visible="state.queryParams.AuditState === '1'"></vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140"></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.isProvinceText" title="省/市工单" width="100"></vxe-column>
					<vxe-column field="order.sourceChannel" title="来源渠道" width="110"></vxe-column>
					<vxe-column field="order.acceptType" title="受理类型" width="110"></vxe-column>
					<vxe-column field="order.hotspotName" title="热点分类" width="150"></vxe-column>
					<template v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)">
						<vxe-column field="order.centerToOrgHandlerName" title="最近派单员" width="140"></vxe-column>
						<vxe-column field="sendBackStepName" title="退回节点" width="140"></vxe-column>
						<vxe-column field="sendBackTimeDifference" title="退回时差(小时)" width="140"></vxe-column>
					</template>
					<vxe-column field="order.acceptorName" title="受理人" width="120"></vxe-column>
					<vxe-column field="order.orgLevelOneName" title="一级部门" width="140"></vxe-column>
					<vxe-column field="order.content" title="受理内容" min-width="200"></vxe-column>
					<vxe-column field="stateText" title="特提审批状态" width="140"></vxe-column>
					<vxe-column field="creatorName" title="申请人" width="140"></vxe-column>
					<vxe-column field="creatorOrgName" title="申请部门" width="140"></vxe-column>
					<vxe-column field="content" title="申请理由" min-width="150"></vxe-column>
					<template v-if="state.queryParams.AuditState === '2'">
						<vxe-column field="auditUser" title="审批人" width="120"></vxe-column>
						<vxe-column field="auditTime" title="审批时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.auditTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column field="auditContent" title="审批意见" min-width="140"></vxe-column>
					</template>
					<vxe-column title="操作" fixed="right" width="100" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onAudit(row)" title="退回特提" v-auth="'business:return:audit'" v-if="[0].includes(row.state)">
								审批
							</el-button>
							<el-button link type="primary" @click="onAuditDetail(row)" title="查看审批详情" v-if="[1, 2].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>
		<!-- 退回审批 -->
		<return-audit ref="returnAuditRef" @updateList="queryList" />
		<!-- 审批详情 -->
		<return-audit-detail ref="returnAuditDetailRef" />
		<!-- 批量审批 -->
		<return-audit-multiple ref="returnAuditMultipleRef" @updateList="queryList" />
	</div>
</template>
<script setup lang="tsx" name="businessReturnAudit">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { returnAuditList } from '@/api/business/return';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { formatDate } from '@/utils/formatTime';
// 引入组件
const ReturnAudit = defineAsyncComponent(() => import('@/views/business/return/components/Return-audit.vue')); // 审批
const ReturnAuditMultiple = defineAsyncComponent(() => import('@/views/business/return/components/Return-audit-multiple.vue'));
const ReturnAuditDetail = defineAsyncComponent(() => import('@/views/business/return/components/Return-audit-detail.vue')); // 审批详情
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.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, // 关键字
		State: null, // 审批状态
		AuditState: '1', // 是否已处理 1 待审批 2已审批
		crTime: [],
		CreationTimeStart: null,
		CreationTimeEnd: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 手动查询，将页码设置为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.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'); // 删除无用的参数
	requestParams.value.AuditState === '2' ? state.queryParams.State : null;
	returnAuditList(requestParams.value)
		.then((res) => {
			state.tableData = res.result?.items ?? [];
			state.total = res.result?.total ?? 0;
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.catch((err) => {
			console.log(err);
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		});
};

/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 审批
const returnAuditRef = ref<RefType>();
const onAudit = (row: any) => {
	returnAuditRef.value.openDialog(row);
};
// 审批详情
const returnAuditDetailRef = ref<RefType>();
const onAuditDetail = (row: any) => {
	returnAuditDetailRef.value.openDialog(row);
};
// 批量审批
const returnAuditMultipleRef = ref<RefType>();
const onAuditMultiple = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	returnAuditMultipleRef.value.openDialog(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();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
