<template>
	<el-dialog v-model="state.dialogVisible" draggable :title="dialogTitle" width="50%" append-to-body destroy-on-close @close="close">
		<div class="collapse-container">
			<el-form ref="ruleFormRef" :model="state.ruleForm">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="退回节点" prop="nextStepCode" :rules="[{ required: true, message: '请选择退回节点', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择退回节点" class="w100" @change="selectNextCode">
								<el-option v-for="item in steps" :value="item.key" :key="item.key" :label="item.value"> </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.ruleForm.nextStepCode">
						<el-form-item label="办理对象" prop="nextHandlers" :rules="[{ required: true, message: '请选择办理对象', trigger: 'change' }]">
							<el-select-v2
								v-model="state.ruleForm.nextHandlers"
								:options="handlerOptions"
								placeholder="请选择办理对象"
								class="w100"
								multiple
								clearable
								collapse-tags
								collapse-tags-tooltip
								filterable
								value-key="key"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="isDepartment">
						<el-form-item
							label="延期"
							label-width="76px"
							prop="timeLimit"
							:rules="[{ required: false, message: '请填写延期申请数量', trigger: 'blur' }]"
						>
							<el-row :gutter="10">
								<el-col :xs="24" :sm="12" :md="12" :lg="16" :xl="16">
									<el-select
										v-model="state.ruleForm.timeLimit"
										placeholder="请选择延期数量"
										:rules="[{ required: true, message: '请选择延期数量', trigger: 'change' }]"
										clearable
										style="width: 220px"
									>
										<el-option v-for="item in delayOptions" :value="item.value" :key="item.value" :label="item.label" />
									</el-select>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
									<el-form-item label="" prop="timeLimitUnit" :rules="[{ required: true, message: '请选择延期申请单位', trigger: 'change' }]">
										<el-select v-model="state.ruleForm.timeLimitUnit" placeholder="延期申请单位" disabled style="width: 140px">
											<el-option v-for="item in timeType" :value="item.key" :key="item.key" :label="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="['YiBin'].includes(themeConfig.appScope)">
						<el-form-item label="错件类别" :rules="[{ required: true, message: '请选择错件类别', trigger: 'change' }]" prop="error">
							<el-checkbox v-model="state.ruleForm.error" @change="selectError" style="display: none"></el-checkbox>
							<el-row class="w100">
								<el-col :span="24" v-for="(item, index) in state.ruleForm.orgs" :key="item.id" class="mb18">
									<el-form-item :prop="`orgs.${index}.reason`" :rules="[{ required: item.choose, message: '请选择错件类别', trigger: 'change' }]">
										<template #label>
											<el-checkbox v-model="item.choose" @change="selectError"> {{ item.value }}</el-checkbox>
										</template>
										<el-select
											v-model="item.reason"
											placeholder="请选择错件类别"
											value-key="dicDataValue"
											clearable
											@change="selectError"
											style="min-width: 240px"
										>
											<el-option v-for="items in reTransactErrorType" :key="items.dicDataValue" :label="items.dicDataName" :value="items" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)">
						<el-form-item label="错件类别" :rules="[{ required: true, message: '请选择错件类别', trigger: 'change' }]" prop="error">
							<el-select v-model="state.ruleForm.error" placeholder="请选择错件类别" value-key="dicDataValue" clearable style="min-width: 240px">
								<el-option v-for="items in reTransactErrorType" :key="items.dicDataValue" :label="items.dicDataName" :value="items" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="退回意见" prop="reason" :rules="[{ required: true, message: '请填写退回意见', trigger: 'blur' }]">
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.ruleForm.reason"
								placeholder="请填写退回意见"
								:commonEnum="commonEnum.Return"
							/>
						</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(ruleFormRef)" :loading="state.loading">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="SpecialDialog">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { publishReturn, publishReturnBaseDataNew } from '@/api/business/publish';
import { commonEnum } from '@/utils/constants';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {
		nextStepCode: null, // 退回节点
		reason: '', // 退回理由
		timeLimitUnit: 2,
		timeLimit: null,
		orgs: [],
		nextHandlers: [],
		stepType: null,
	},
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>();
const steps = ref<EmptyArrayType>([]); // 退回节点
const timeType = ref([]); // 时间单位
const reTransactErrorType = ref<EmptyArrayType>([]); // 错件类别
const handlerOptions = ref<EmptyArrayType>([]); // 办理对象
const delayOptions = ref([
	{ value: 1, label: '1' },
	{ value: 3, label: '3' },
	{ value: 5, label: '5' },
]); // 延期
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
/**
 * @description 打开弹窗
 * @param {object} val 工单详情
 */
const dialogTitle = ref('业务信件退回');
const defaultHandlerKey = ref();
const openDialog = async (val: any, title?: string) => {
	defaultHandlerKey.value = null;
	state.orderDetail = val;
	state.workflowId = val.workflowId;
	state.loading = true;
	state.dialogVisible = true;
	try {
		const baseRes = await publishReturnBaseDataNew(val.id);
		timeType.value = baseRes.result?.specialTimeType ?? [];
		steps.value = baseRes.result?.step?.steps ?? [];
		reTransactErrorType.value = baseRes.result?.reTransactErrorType ?? [];
		state.ruleForm.orgs = baseRes.result?.orgs ?? [];

		// 默认选中退回节点
		if (baseRes.result.defaultHandlerKey) {
			state.ruleForm.nextStepCode = baseRes.result?.defaultStepKey;
			state.ruleForm.nextStepName = steps.value.find((item) => item.key === baseRes.result?.defaultStepKey).value;
			defaultHandlerKey.value = baseRes.result?.defaultHandlerKey;
			selectNextCode(baseRes.result.defaultStepKey);
		}
		if (title) dialogTitle.value = title;
	} catch (e) {
		console.log(e);
	} finally {
		state.loading = false;
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
	steps.value = [];
};
// 选择退回节点
const isDepartment = ref<Boolean>(false); // 选择的退回节点是否是部门
const orgId = ref('');
const orgName = ref('');
const selectNextCode = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	const next = steps.value.find((item: any) => item.key === val);
	isDepartment.value = next.businessType === 2; // 如果是部门才可以选择延期
	const items = next.items; //获取下一节点
	state.ruleForm.nextStepName = next.value; // 下一节点name
	handlerOptions.value = items ?? [];
	state.ruleForm.businessType = next.businessType;
	state.ruleForm.flowDirection = next.flowDirection;
	state.ruleForm.handlerType = next.handlerType;
	state.ruleForm.stepType = next.stepType;
	handlerOptions.value = handlerOptions.value.map((item: any) => {
		return {
			value: {
				...item,
			},
			label: item.value,
		};
	});
	if (['ZiGong', 'LuZhou'].includes(themeConfig.value.appScope)) {
		orgId.value = next.handler.orgId;
		orgName.value = next.handler.orgName;
	}
	if (defaultHandlerKey.value) {
		const handler = handlerOptions.value.find((item: any) => item.value.key === defaultHandlerKey.value);
		if (handler) {
			state.ruleForm.nextHandlers = [handler.value];
		} else {
			state.ruleForm.nextHandlers = [];
		}
	}
	if (items.length === 1) {
		// 如果办理对象只有一个默认选中
		state.ruleForm.nextHandlers = [items[0]];
	}
};
// 选择错件类别
const selectError = () => {
	state.ruleForm.error = state.ruleForm.orgs.find((item: any) => item.choose) ? true : null;
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let reTransactError: any;
		if (['YiBin'].includes(themeConfig.value.appScope)) {
			reTransactError = state.ruleForm.orgs
				.filter((item: any) => item.choose)
				.map((item: any) => {
					return {
						orgId: item.key,
						orgName: item.value,
						errorId: item.reason.id,
						errorName: item.reason.dicDataName,
					};
				});
		} else if (['ZiGong', 'LuZhou'].includes(themeConfig.value.appScope)) {
			reTransactError = [
				{
					orgId: orgId.value,
					orgName: orgName.value,
					errorId: state.ruleForm.error.dicDataValue,
					errorName: state.ruleForm.error.dicDataName,
				},
			];
		}
		const request = {
			workflowId: state.orderDetail.workflowId,
			orderId: state.orderDetail.id,
			nextStepCode: state.ruleForm.nextStepCode,
			nextStepName: state.ruleForm.nextStepName,
			nextHandlers: state.ruleForm.nextHandlers,
			reason: state.ruleForm.reason,
			timeLimit: state.ruleForm.timeLimit,
			timeLimitUnit: state.ruleForm.timeLimitUnit,
			alterTime: !!state.ruleForm.timeLimit,
			businessType: state.ruleForm.businessType,
			flowDirection: state.ruleForm.flowDirection,
			handlerType: state.ruleForm.handlerType,
			stepType: state.ruleForm.stepType,
			reTransactError,
			specialType: 3, // 1特提 2重办 3退回
		};
		publishReturn(request)
			.then(() => {
				state.loading = false;
				closeDialog();
				emit('updateList');
				ElMessage.success('操作成功');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 选中常用意见
const chooseAdvice = (item: any) => {
	state.ruleForm.reason += item.content;
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
