<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		title="重提终止申请"
		ref="dialogRef"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		append-to-body
		destroy-on-close
		:close-on-click-modal="false"
		@close="close"
	>
		<div v-loading="state.loading">
			<el-form :model="state.terminateForm" label-width="110px" ref="terminateFormRef">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单编码"> {{ state.orderDetail.order?.no }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单标题"> {{ state.orderDetail.order?.title }} </el-form-item>
					</el-col>
					<!-- 非退回流程都需要选择 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="下一环节" prop="nextStepCode" :rules="[{ required: true, message: '请选择下一环节', trigger: 'change' }]">
							<el-select v-model="state.terminateForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
								<el-option v-for="item in state.nextStepOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- 非退回流程都需要选择并且如果选择了结束节点就不需要选择办理对象 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showHandlers">
						<el-form-item label="办理对象" prop="nextHandlers" :rules="[{ required: false, message: '请选择办理对象', trigger: 'change' }]">
							<el-select-v2
								v-model="state.terminateForm.nextHandlers"
								:options="state.handlerOptions"
								placeholder="请选择办理对象"
								class="w100"
								multiple
								clearable
								collapse-tags
								collapse-tags-tooltip
								filterable
								value-key="key"
								@change="selectHandlers"
								:multiple-limit="multipleLimit"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="" prop="isSms">
							<el-checkbox v-model="state.terminateForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="终止理由" prop="content" :rules="[{ required: true, message: '请填写终止申请理由', trigger: 'blur' }]">
							<common-advice
								@chooseAdvice="chooseAdviceTerminate"
								v-model="state.terminateForm.content"
								placeholder="请填写终止申请理由"
								:loading="state.loading"
								:commonEnum="commonEnum.OrderCirculation"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件">
							<annex-list
								name="终止附件"
								ref="terminateAnnexListRef"
								v-model:format="handleFilesTerminate"
								:businessId="state.orderDetail.id"
								classify="终止上传"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(terminateFormRef)" :loading="state.loading">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, reactive, ref, watch } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { commonEnum } from '@/utils/constants';
import { transformFile } from '@/utils/tools';
import { terminateDetail, terminateNextFlow, terminateNextFlowParams } from '@/api/business/terminate';

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


// 定义子组件向父组件传值/事件
const emit = defineEmits(['orderProcessSuccess', 'orderProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	terminateForm: {
		//流程表单
		content: '', // 终止理由
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点办理对象
		nextMainHandler: '', // 主办人
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
		stepId: '',
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 办理对象
	transform: 'translate(0px, 0px)', // 滚动条位置
	loading: false, // 提交按钮loading
	workflowId: null, // 流程id
	orderDetail: {}, // 工单详情
	id: null,
});
// 打开弹窗
const openDialog = async (val: any) => {
	state.dialogVisible = true;
	state.loading = true;
	state.workflowId = val.workflowId;
	state.id = val.id;
	try {
		// 如果有流程ID说明已经开启过流程需要获取办理流程的参数
		const [workflowTerminateResponse] = await Promise.all([terminateNextFlowParams(val.workflowId)]); //终止审批参数
		handleResult(workflowTerminateResponse);

		const { result } = await terminateDetail(val.id);
		state.terminateForm.content = result.content ?? {};
		state.orderDetail = result;
		state.terminateForm.files = transformFile(result.files);
		state.loading = false;
	}catch (e){
		console.log(e,'111');
		state.loading = false;
		state.dialogVisible = false;
	}
};
const canStartCountersign = ref<boolean>(false); // 是否可以发起会签
const isMainHandlerShow = ref<boolean>(false); // 是否展示主办人
const handleResult = (res: any) => {
	state.nextStepOptions = res.result.steps; //办理对象选择内容
	canStartCountersign.value = res.result.canStartCountersign ?? false; // 是否可以发起会签
	isMainHandlerShow.value = res.result.isMainHandlerShow ?? false; // 是否展示主办人
	if (state.nextStepOptions.length === 1) {
		// 下一节点是否只有一个 默认选中第一个
		setTimeout(() => {
			state.terminateForm.nextStepCode = state.nextStepOptions[0].key; // 下一节点code
			state.terminateForm.nextStepName = state.nextStepOptions[0].value; // 下一节点name
			state.terminateForm.backToCountersignEnd = state.nextStepOptions[0].backToCountersignEnd ?? false; // 是否回到会签结束节点
		}, 0);
		selectNextStep(state.nextStepOptions[0].key); // 查询流程下一节点参数
	} else {
		state.terminateForm.nextStepCode = '';
		state.terminateForm.nextStepName = '';
	}
	state.terminateForm.stepId = res.result.stepId;
	state.loading = false;
};
// 流程选择下一环节
const selectNextStep = (val: any) => {
	terminateFormRef.value?.resetFields('nextHandlers');
	const next = state.nextStepOptions.find((item: any) => item.key === val);
	const items = next.items; //获取下一节点
	state.terminateForm.nextStepName = next.value; // 下一节点name
	state.terminateForm.backToCountersignEnd = next.backToCountersignEnd ?? false; // 是否回到会签结束节点
	state.terminateForm.handlerType = next.handlerType;
	state.terminateForm.businessType = next.businessType;
	state.terminateForm.flowDirection = next.flowDirection;
	state.handlerOptions = items ?? [];
	state.handlerOptions = state.handlerOptions.map((item: any) => {
		return {
			value: {
				...item,
			},
			label: item.value,
		};
	});
	if (items.length === 1) {
		// 如果办理对象只有一个默认选中
		state.terminateForm.nextHandlers = [items[0]];
	}
};
// 办理对象是否能够选择多个(可以发起会签可以选择多个，不能发起会签只能选择一个)
const multipleLimit = computed(() => {
	return canStartCountersign.value ? 0 : 1;
});
watch(
	() => state.terminateForm.nextHandlers, // 监听办理对象 多个办理对象自动发起会签
	(val) => {
		state.terminateForm.isStartCountersign = val.length > 1;
	}
);

// 是否展示办理对象 (只有结束节点不展示 next.stepType===2 表示为结束节点)
const showHandlers = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.terminateForm.nextStepCode);
	if (!next) return true;
	return next.stepType !== 2;
});

// 选择办理对象
const selectHandlers = () => {
	if (state.terminateForm.nextHandlers.length <= 1) {
		// 如果只有一个办理对象就不需要发起会签
		state.terminateForm.isStartCountersign = false;
	}
};
// 设置抽屉
const dialogRef = ref<RefType>();
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 重置表单方法
const restForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	formEl.clearValidate();
};
// 选择常用意见 填入填写框 终止
const chooseAdviceTerminate = (item: any) => {
	state.terminateForm.content += item.content;
};
const afterSubmit = (emitType?: 'orderProcessSuccess' | 'orderProcessFailed', showMessage?: boolean, message?: string) => {
	state.loading = false;
	closeDialog();
	const msg = message ?? '操作成功';
	if (showMessage) ElMessage.success(msg);
	if (emitType) emit(emitType);
};
const terminateFormRef = ref<RefType>();
const close = () => {
	restForm(terminateFormRef.value);
};
// 提交
const handleFilesTerminate = ref<EmptyArrayType>([]); // 终止附件
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const requestTerminate = {
			data: {
				no: state.orderDetail.order?.no,
				orderId: state.orderDetail.order?.id,
				content: state.terminateForm.content,
				files: handleFilesTerminate.value,
				workflowId: state.workflowId,
				id: state.id,
			},
			nextWorkflow: {
				nextStepCode: state.terminateForm.nextStepCode,
				nextStepName: state.terminateForm.nextStepName,
				backToCountersignEnd: state.terminateForm.backToCountersignEnd,
				nextHandlers: state.terminateForm.nextHandlers,
				flowDirection: state.terminateForm.flowDirection,
				handlerType: state.terminateForm.handlerType,
				stepType: state.terminateForm.stepType,
				businessType: state.terminateForm.businessType,
				isSms: state.terminateForm.isSms,
				opinion: state.terminateForm.content,
				stepId: state.terminateForm.stepId,
				files: handleFilesTerminate.value,
				workflowId: state.workflowId,
			},
		};

		terminateNextFlow(requestTerminate)
			.then(() => {
				afterSubmit('orderProcessSuccess', true, '重提申请成功');
			})
			.catch(() => {
				afterSubmit('orderProcessFailed');
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
