<template>
	<el-dialog v-model="state.dialogVisible" draggable title="甄别退回" ref="dialogRef" width="50%" append-to-body destroy-on-close @close="close">
		<el-form label-width="110px" :model="state.infoForm" class="show-info-form" v-loading="state.loading">
			<p class="border-title">申请信息</p>
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="工单编号"> {{ state.infoForm?.no }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="工单标题"> {{ state.infoForm?.visit?.order?.title }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="申请人">{{ state.infoForm?.creatorName }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="申请部门">{{ state.infoForm?.creatorOrgName }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="申请时间">{{ formatDate(state.infoForm?.creationTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="申请类型"> {{ state.infoForm?.typeDicName }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="发起甄别耗时"> {{ state.infoForm?.timeConsuminText }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="是否省甄别">{{ state.infoForm?.isProvince ? '是' : '否' }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="申请理由" class="formatted-text">{{ state.infoForm?.content }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="附件"
					><annex-list name="甄别申请附件" v-model="state.infoForm.files" readonly classify="甄别申请附件" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<p class="border-title mt10 mb10">甄别审核明细</p>
		<vxe-table :expand-config="{ trigger: 'row', padding: true }" border :data="tableData" :loading="state.loading" max-height="500px">
			<vxe-column type="seq" width="70"></vxe-column>
			<vxe-column type="expand" width="60">
				<template #content="{ row }">
					<div class="mb5  formatted-text">审核意见：{{ row.opinion }}</div>
					<annex-list name="附件" readonly businessId="" classify="查看附件" v-model="row.files" />
				</template>
			</vxe-column>
			<vxe-column field="name" title="节点"></vxe-column>
			<vxe-column field="handlerName" title="审批人"></vxe-column>
			<vxe-column field="handleTime" title="审批时间" width="160">
				<template #default="{ row }">{{ formatDate(row.handleTime, 'YYYY-mm-dd HH:MM:SS') }}</template>
			</vxe-column>
			<vxe-column field="handleModeText" title="状态"></vxe-column>
		</vxe-table>
		<p class="border-title mt20 mb10">退回意见</p>
		<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" v-loading="state.loading">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="退回意见" prop="opinion" :rules="[{ required: true, message: '请填写退回意见', trigger: 'blur' }]">
						<common-advice
							@chooseAdvice="chooseAdvice"
							v-model="state.ruleForm.opinion"
							placeholder="请填写退回意见"
							:loading="state.loading"
							:commonEnum="commonEnum.Discriminate"
							:maxlength="AppConfigInfo.handleOpinionWordLimit"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="附件" :rules="[{ required: false, message: '请上传附件', trigger: 'change' }]">
						<annex-list name="甄别附件" classify="甄别上传" v-model:format="handleFiles" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="discernDetail">
import { defineAsyncComponent, reactive, ref } from 'vue';
import { formatDate } from '@/utils/formatTime';
import {  screenDetail } from '@/api/business/discern';
import { transformFile } from '@/utils/tools';
import { ElMessage, FormInstance } from 'element-plus';
import { workflowPrevious, workflowTraces } from '@/api/system/workflow';
import { commonEnum } from '@/utils/constants';
import { useAppConfig } from '@/stores/appConfig';
import { storeToRefs } from 'pinia';
import other from '@/utils/other';

const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见

const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const emit = defineEmits(['updateList']); // 定义事件
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	infoForm: {},
	ruleForm: {
		isPass: true,
		nextHandlers: [],
		isSms: false,
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false,
		stepId: null,
		workflowId: null,
	},
	handlerOptions: [],
	nextStepOptions: [],
});

const tableData = ref<EmptyArrayType>([]);
/*
 * @params row 工单详情
 * @description 打开弹窗
 * */
const openDialog = async (row: any) => {
	state.dialogVisible = true;
	state.loading = true;
	try {
		const { result } = await screenDetail(row.id);
		state.infoForm = result ?? {};
		state.infoForm.files = transformFile(state.infoForm.files);
		state.ruleForm.workflowId = row.workflowId;
		await getWorkflow(result.workflowId);
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
const formatTraces = (val: any) => {
	if (!val || !val.length) return [];
	val.forEach((item: any) => {
		item.files = transformFile(item.files);
	});
	return val;
};
// 获取流程
const getWorkflow = async (workflowId: string) => {
	try {
		// 查询审核记录
		const { result } = await workflowTraces(workflowId);
		tableData.value = formatTraces(result?.traces);
	} catch (e) {
		console.log(e);
	}
};
// 选择常用意见 填入填写框 办理
const chooseAdvice = (item: any) => {
	state.ruleForm.opinion += item.content;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.ruleForm.files = [];
};
// 提交
const afterSubmit = (emitType?: 'updateList', showMessage?: boolean, message?: string) => {
	state.loading = false;
	closeDialog();
	const msg = message ?? '甄别退回成功';
	if (showMessage) ElMessage.success(msg);
	if (emitType) emit(emitType);
};
const ruleFormRef = ref<RefType>();
const handleFiles = ref<EmptyArrayType>([]); // 附件
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let submitObj = other.deepClone(state.ruleForm);

		workflowPrevious({ ...submitObj, files: handleFiles.value })
			.then(() => {
				afterSubmit('updateList', true);
			})
			.catch(() => {
				afterSubmit('updateList');
			});
	});
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
