<template>
	<el-dialog v-model="state.dialogVisible" draggable :title="dialogTitle" width="50%" append-to-body destroy-on-close @close="close">
		<div class="collapse-container" v-loading="state.loading">
			<el-form ref="ruleFormRef" :model="state.ruleForm">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-row :gutter="10" class="w100">
							<el-col :xs="24" :sm="12" :md="12" :lg="10" :xl="10">
								<el-form-item label="流转目标" prop="nextStepCode" :rules="[{ required: true, message: '请选择流转目标', trigger: 'change' }]">
									<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择流转目标" @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="10" :xl="10">
								<el-form-item prop="timeLimit" :rules="[{ required: true, message: '请填写延期数量', trigger: 'blur' }]">
									<!--									<el-select
										v-model="state.ruleForm.timeLimit"
										placeholder="请选择延期数量"
										:rules="[{ required: true, message: '请选择延期数量', trigger: 'change' }]"
										clearable
									>
										<el-option v-for="item in delayOptions" :value="item.value" :key="item.value" :label="item.label" />
									</el-select>-->
									<el-input-number v-model="state.ruleForm.timeLimit" :min="1" :precision="0" class="w100" :max="10" placeholder="请填写延期数量" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="4" :xl="4">
								<el-form-item prop="timeLimitUnit" :rules="[{ required: true, message: '请选择延期申请单位', trigger: 'change' }]">
									<el-select v-model="state.ruleForm.timeLimitUnit" placeholder="延期申请单位" disabled>
										<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-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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 specialReason" :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, nextTick } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { publishReturnBaseData, publishReturn } 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: 1,
		stepType: null,
	},
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>();
const steps = ref<EmptyArrayType>([]); // 退回节点
const timeType = ref<EmptyArrayType>([]); // 时间单位
const specialReason = ref<EmptyArrayType>([]); // 重办原因
const delayOptions = ref([
	{ value: 1, label: '1' },
	{ value: 3, label: '3' },
	{ value: 5, label: '5' },
]); // 延期
/**
 * @description 打开弹窗
 * @param {object} val 工单详情
 */
const dialogTitle = ref('业务信件重办');
const openDialog = async (val: any, title?: string) => {
	state.orderDetail = val;
	state.workflowId = val.workflowId;
	state.loading = true;
	state.dialogVisible = true;
	try {
		const baseRes = await publishReturnBaseData(val.id);
		timeType.value = baseRes.result?.specialTimeType ?? [];
		steps.value = baseRes.result?.step?.steps ?? [];
		specialReason.value = baseRes.result?.specialReason ?? [];
		if (baseRes.result.defaultStepKey) {
			await nextTick(() => {
				// 如果有默认值需要默认选中
				state.ruleForm.nextStepCode = baseRes.result.defaultStepKey;
				state.ruleForm.nextStepName = steps.value.find(item => item.key === baseRes.result?.defaultStepKey).value;
				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 orgId = ref('');
const orgName = ref('');
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const selectNextCode = (val: any) => {
	const next = steps.value.find((item: any) => item.key === val);
	state.ruleForm.nextStepName = next.value; // 下一节点name
	state.ruleForm.businessType = next.businessType;
	state.ruleForm.flowDirection = next.flowDirection;
	state.ruleForm.handlerType = next.handlerType;
	state.ruleForm.stepType = next.stepType;
	if (['ZiGong','LuZhou'].includes(themeConfig.value.appScope)) {
		orgId.value = next.handler.orgId;
		orgName.value = next.handler.orgName;
	}
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let reTransactError: any;
		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,
			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: 2, // 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>
