<template>
	<el-dialog v-model="state.dialogVisible" draggable :title="dialogTitle" ref="dialogRef" width="50%" append-to-body destroy-on-close @close="close">
		<el-form label-width="110px" ref="ruleFormRef" :model="state.ruleForm" class="show-info-form">
			<el-row :gutter="35">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="工单编码"> {{ state.ruleForm.order?.no }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="工单编码"> {{ state.ruleForm.order?.no }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="省本地编码"> {{ state.ruleForm.order?.provinceNo }} </el-form-item>
				</el-col>
				<template v-if="isAudit">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请人"> {{ state.ruleForm.creatorName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请部门"> {{ state.ruleForm.creatorOrgName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="退回申请时间"> {{ formatDate(state.ruleForm.creationTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
					</el-col>
				</template>
				<template v-else>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请人"> {{ userInfos.name }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请部门"> {{ userInfos.orgName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="退回申请时间"> {{ formatDate(Date(), 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
					</el-col>
				</template>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="申请原因" prop="reason" :rules="[{ required: true, message: '请填写退回申请原因', trigger: 'blur' }]" class="mb20">
						<el-input
							v-model="state.ruleForm.reason"
							type="textarea"
							:autosize="{ minRows: 6, maxRows: 10 }"
							placeholder="请填写退回申请原因"
							:disabled="isAudit"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="附件" prop="handleResult" :rules="[{ required: false, message: '请选择附件', trigger: 'change' }]">
						<annex-list
							name="退回附件"
							v-model="state.ruleForm.files"
							v-model:format="filesFormat"
							:businessId="state.ruleForm?.id"
							classify="退回附件"
							:readonly="isAudit"
						/>
					</el-form-item>
				</el-col>
				<template v-if="isAudit">
					<el-divider />
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="审批意见" prop="auditOpinion" :rules="[{ required: true, message: '请填退回审批意见', trigger: 'blur' }]">
							<el-input
								v-model="state.ruleForm.auditOpinion"
								type="textarea"
								:autosize="{ minRows: 6, maxRows: 10 }"
								placeholder="请填退回审批意见"
							/>
						</el-form-item>
					</el-col>
				</template>
			</el-row>
		</el-form>
		<template #footer v-if="isAudit">
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onPass(ruleFormRef)" :loading="state.loading">审批通过</el-button>
				<el-button type="primary" @click="onReject(ruleFormRef)" :loading="state.loading">驳回</el-button>
			</span>
		</template>
		<template #footer v-else>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-auth="'business:order:supervise:apply'">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="secondVisitDialog">
import { computed, defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { formatDate } from '@/utils/formatTime';
import { returnAdd, returnDetail, returnAudit } from '@/api/business/return';
import { transformFile } from '@/utils/tools';

// 引入组件
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {
		reason: '', // 退回申请理由
		auditOpinion: '', // 退回审批意见
	},
});
const ruleFormRef = ref<RefType>();
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const isAudit = ref<boolean>(false); // 是否是审核
/**
 * @description 打开弹窗
 * @param {object} val 工单详情
 * @param {boolean} audit 是否是审核
 */
const openDialog = (val: any, audit = false) => {
	state.ruleForm = val;
	if (!state.ruleForm.order) {
		state.ruleForm.order = val;
		state.ruleForm.files = transformFile(state.ruleForm.order.files);
	}
	isAudit.value = audit;
	if (audit) {
		returnDetail(val.id).then((res) => {
			state.ruleForm = res.result;
			state.ruleForm.files = transformFile(state.ruleForm.files);
		});
	}
	state.dialogVisible = true;
};
const dialogTitle = computed(() => {
	return isAudit.value ? '退回审批' : '退回申请';
});
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 提交
const filesFormat = ref<EmptyArrayType>([]); // 附件列表
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let request = {
			orderId: state.ruleForm.id,
			content: state.ruleForm.reason,
			files: filesFormat.value,
		};
		returnAdd(request)
			.then(() => {
				state.loading = false;
				closeDialog();
				emit('updateList');
				ElMessage.success('退回申请成功');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 审批通过
const onPass = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		ElMessageBox.confirm(`您确定要通过退回申请，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				const request = {
					auditOpinion: state.ruleForm.auditOpinion,
					id: state.ruleForm.id,
					state: '1',
				};
				returnAudit(request)
					.then(() => {
						ElMessage.success('操作成功');
						closeDialog();
						emit('updateList');
					})
					.catch((err) => {
						console.log(err);
					});
			})
			.catch(() => {});
	});
};
// 审批驳回 审核结果 0 待审核 1 审核通过 2 审核不通过
const onReject = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		ElMessageBox.confirm(`您确定要驳回退回申请，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				const request = {
					auditOpinion: state.ruleForm.auditOpinion,
					id: state.ruleForm.id,
					state: '2',
				};
				returnAudit(request)
					.then(() => {
						ElMessage.success('操作成功');
						closeDialog();
						emit('updateList');
					})
					.catch((err) => {
						console.log(err);
					});
			})
			.catch(() => {});
	});
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
