<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 :disabled="state.loading">
				<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="qmTime">
					<el-date-picker
						v-model="state.queryParams.qmTime"
						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="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,
				}"
			>
				<template #buttons>
					<el-button
						type="primary"
						@click="onAuditMultiple"
						:disabled="isChecked"
						:loading="state.loading"
						v-auth="'business:return:audit:multiple'"
						v-show="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="refreshList">{{ 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.expiredTime" title="期满时间" width="150">
						<template #default="{ row }">
							{{ formatDate(row.order.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<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-show="[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="refreshList" />
		<!-- 审批详情 -->
		<return-audit-detail ref="returnAuditDetailRef" />
		<!-- 批量审批 -->
		<return-audit-multiple ref="returnAuditMultipleRef" @updateList="refreshList" />
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px" :disabled="state.loading">
				<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 label="是否省工单" prop="IsProvince">
					<el-select v-model="state.queryParams.IsProvince" placeholder="请选择是否省工单" @change="handleQuery">
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item prop="Channel" label="来源渠道">
					<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item prop="AcceptTypeCode" label="受理类型">
					<el-select v-model="state.queryParams.AcceptTypeCode" placeholder="请选择受理类型" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="Hotspot">
					<el-input v-model.trim="state.queryParams.Hotspot" placeholder="热点分类" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="最近派单员" prop="CenterToOrgHandlerName">
					<el-input v-model.trim="state.queryParams.CenterToOrgHandlerName" placeholder="最近派单员" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="退回节点" prop="SendBackStepName">
					<el-input v-model.trim="state.queryParams.SendBackStepName" placeholder="退回节点" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="退回时差" prop="SendBackTimeDifference">
					<el-input v-model.trim="state.queryParams.SendBackTimeDifference" placeholder="退回时差" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="受理人" prop="NameOrNo">
					<el-input v-model.trim="state.queryParams.NameOrNo" placeholder="受理人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="一级部门" prop="OrgLevelOneName">
					<el-input v-model.trim="state.queryParams.OrgLevelOneName" placeholder="一级部门" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="受理内容" prop="Content">
					<el-input v-model.trim="state.queryParams.Content" placeholder="一级部门" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="申请人" prop="ApplyName">
					<el-input v-model.trim="state.queryParams.ApplyName" placeholder="申请人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="申请部门" prop="ApplyOrgName">
					<el-input v-model.trim="state.queryParams.ApplyOrgName" placeholder="申请部门" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="申请理由" prop="Opinion">
					<el-input v-model.trim="state.queryParams.Opinion" 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="businessReturnAudit">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { returnAuditList, returnBase } 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';
import { orderBaseData } from '@/api/business/order';
// 引入组件
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 state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 关键字
		State: null, // 审批状态
		AuditState: '1', // 是否已处理 1 待审批 2已审批
		crTime: [],
		CreationTimeStart: null,
		CreationTimeEnd: null,
		qmTime: [],
		ExpiredTimeStart: null,
		ExpiredTimeEnd: null,
		IsProvince:null, // 是否省工单
		Channel:null, // 来源渠道
		AcceptTypeCode:null, // 受理类型
		Hotspot:null, // 热点分类
		CenterToOrgHandlerName:null, // 最近派单员
		SendBackStepName:null, // 退回节点
		SendBackTimeDifference:null, // 退回时差
		NameOrNo:null, // 受理人
		OrgLevelOneName:null, //一级部门
		Content:null, // 受理内容
		ApplyName:null, // 申请人
		ApplyOrgName:null, // 申请部门
		Opinion:null, // 申请理由
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 刷新列表
const refreshList = () => {
	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.ExpiredTimeStart = state.queryParams.qmTime === null ? null : state.queryParams.qmTime[0]; // 期满时间
	requestParams.value.ExpiredTimeEnd = state.queryParams.qmTime === null ? null : state.queryParams.qmTime[1];
	Reflect.deleteProperty(requestParams.value, 'qmTime'); // 删除无用的参数
	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 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 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 !checkTable.value.length;
});
// 获取基础数据
const channelOptions = ref<EmptyArrayType>([]); // 来源渠道
const orderStatusOptions = ref<EmptyArrayType>([]); // 工单状态
const acceptTypeOptions = ref<EmptyArrayType>([]); // 受理类型
const getBaseData = async ()=>{
	try {
		const { result } = await orderBaseData();
		channelOptions.value = result.channelOptions ?? [];
		orderStatusOptions.value = result.orderStatusOptions ?? [];
		acceptTypeOptions.value = result.acceptTypeOptions ?? [];
	} catch (e) {
		console.log(e);
	}
}
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
