<template>
	<div class="knowledge--process-container">
		<el-dialog
			v-model="state.dialogVisible"
			draggable
			:title="state.title + '流程'"
			ref="dialogRef"
			@mouseup="mouseup"
			:style="'transform: ' + state.transform + ';'"
			append-to-body
			@opened="opened"
		>
			<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef">
				<el-row :gutter="35">
					<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.ruleForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
                <el-option v-for="item in state.nextStepOptions" :key="item.code" :label="item.name" :value="item.code" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="处理人" prop="nextHandlers" :rules="[{ required: false, message: '请选择处理人', trigger: 'change' }]">
							<el-select
								v-model="state.ruleForm.nextHandlers"
								multiple
								filterable
								placeholder="请选择处理人"
								class="w100"
								@change="selectHandlers"
								value-key="id"
								clearable
							>
                <el-option v-for="item in state.handlerOptions" :key="item.id" :label="item.name" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showMainHandler">
						<el-form-item
							label="主办"
							prop="nextMainHandler"
							filterable
							clearable
							:rules="[{ required: false, message: '请选择主办', trigger: 'change' }]"
						>
							<el-select v-model="state.ruleForm.nextMainHandler" placeholder="请选择主办" class="w100">
                <el-option v-for="item in state.handlerMainOptions" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="8" :lg="12" :xl="12">
							<el-form-item label="" prop="acceptSms">
								<el-checkbox v-model="state.ruleForm.acceptSms" label="短信通知" />
							</el-form-item>
						</el-col> -->
					<!--  办理流程展示期满时间  -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="['next'].includes(state.processType)">
						<el-form-item label="期满时间" prop="expiredTime" :rules="[{ required: true, message: '请选择期满时间', trigger: 'change' }]">
							<el-date-picker
								v-model="state.ruleForm.expiredTime"
								type="datetime"
								placeholder="请选择期满时间"
								value-format="YYYY-MM-DD[T]HH:mm:ss"
								class="w100"
							/>
						</el-form-item>
					</el-col>
					<!-- 办理流程和开始流程是否发起会签 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="['next', 'addStart', 'deleteStart'].includes(state.processType)">
						<el-form-item
							label="是否发起会签"
							prop="isStartCountersign"
							:rules="[{ required: false, message: '请选择是否发起会签', trigger: 'change' }]"
						>
							<el-switch v-model="state.ruleForm.isStartCountersign" inline-prompt active-text="是" inactive-text="否" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item
							:label="state.title + '意见'"
							class="textarea"
							prop="opinion"
							:rules="[{ required: true, message: '请填写常用意见', trigger: 'blur' }]"
						>
              <common-advice
                  @chooseAdvice="chooseAdvice"
                  v-model="state.ruleForm.opinion"
                  placeholder="请填写常用意见"
                  :loading="state.loading"
                  :commonEnum="state.commonEnum"
              />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" prop="additions" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
							<annex-list state.ruleForm />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">提 交</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="knowledgeProcessComponent">
import { defineAsyncComponent, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { KnowledgeAddStartFlowParams, KnowledgeDeleteStartFlowParams, KnowledgeAddStartFlow, KnowledgeDeleteStartFlow } from '/@/api/knowledge';
import { workflowNextSteps, workflowNext, workflowRecall, workflowRecallParams, workflowStepOptions } from '/@/api/system/workflow';
import other from '/@/utils/other';
// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue'));  // 附件列表

// 定义子组件向父组件传值/事件
const emit = defineEmits(['knowledgeProcessSuccess', 'knowledgeProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	title: '提交',
	ruleForm: {
		nextStepCode: '', // 下一个节点
		nextHandlers: [], // 下一个节点处理人
		nextMainHandler: '', // 下一个节点主办人
		acceptSms: false, // 是否接收短信
		opinion: '', // 意见
		additions: [], // 附件
		expiredTime: '', // 期满时间
		isStartCountersign: false, // 是否发起会签
	},
	nextStepOptions: [], // 下一个节点
	handlerOptions: [], // 处理人
	transform: 'translate(0px, 0px)', // 附件弹窗位置
	fileList: [], // 附件列表
	loading: false, // 提交按钮loading
	isStartFlow: false, //是否开启流程
	processType: 'next',  // 流程状态
	workflowId: '', //流程id
	commonEnum: '', // 常用意见类型
	handlerClassifies: [], //撤回处理人
	handlerMainOptions: [], // 主办人
	handleId: '', // 流程处理ID
});
const ruleFormRef = ref<RefType>(); // 表单ref
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	state.processType = val.processType ?? 'next'; // 流程状态
	state.workflowId = val.id ?? ''; // 流程id
	state.commonEnum = val.commonEnum ?? ''; // 常用意见类型
	state.title = val.title ?? '提交流程'; // 流程标题
	let res: any = {};
	switch (state.processType) {
		case 'addStart':
			res = await KnowledgeAddStartFlowParams(); //获取新增开启流程参数
			state.nextStepOptions = res.result.steps;
			state.handleId = res.result.id;
			if (state.nextStepOptions.length === 1) {
        state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
        getNextStepOption(res.result.id, state.nextStepOptions[0].code);
			}
			break;
		case 'deleteStart':
			res = await KnowledgeDeleteStartFlowParams(); //获取删除开启流程参数
			state.nextStepOptions = res.result.steps;
			state.handleId = res.result.id;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].key;
				await getNextStepOption(res.result.id, state.nextStepOptions[0].key);
			}
			break;
		case 'recall': // 撤回流程
			res = await workflowRecallParams(state.workflowId); //撤回参数
			state.nextStepOptions = res.result.steps;
			state.ruleForm.workflowId = state.workflowId;
			state.handleId = res.result.id;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].key;
				await getNextStepOption(res.result.id, state.nextStepOptions[0].key);
			}
			break;
		case 'return': // 退回流程
			break;
		case 'next': // 默认下一流程
			res = await workflowNextSteps(state.workflowId);
			state.ruleForm.workflowId = state.workflowId;
			state.ruleForm.expiredTime = res.result?.expiredTime ?? '';
			state.nextStepOptions = res.result.steps;
			state.handleId = res.result.id;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].key;
				await getNextStepOption(res.result.id, state.nextStepOptions[0].key);
			}
			break;
		default: // 默认下一流程
			res = await workflowNextSteps(state.workflowId);
			state.ruleForm.workflowId = state.workflowId;
			state.ruleForm.expiredTime = res.result?.expiredTime ?? '';
			state.nextStepOptions = res.result.steps;
			state.handleId = res.result.id;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].key;
				await getNextStepOption(res.result.id, state.nextStepOptions[0].key);
			}
			break;
	}
	state.dialogVisible = true;
};
// 打开弹窗清空表单
const opened = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 流程选择下一个环节
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextMainHandler');
	let next: any;
	next = state.nextStepOptions.find((item: any) => item.key === val);
	getNextStepOption(state.handleId, next.key);
	// switch (state.processType) {
	// 	case 'addStart' || 'editStart' || 'deleteStart':
	// 		next = state.nextStepOptions.find((item: any) => item.code === val);
	// 		state.handlerOptions = next.nextSteps ?? [];
	// 		break;
	// 	case 'recall': // 撤回
	// 		next = state.nextStepOptions.find((item: any) => item.code === val);
	// 		console.log(next, state.nextStepOptions);
	// 		state.handlerClassifies = next.handlerClassifies ?? [];
	// 		break;
	// 	default:
	// 		next = state.nextStepOptions.find((item: any) => item.code === val);
	// 		state.handlerOptions = next.nextSteps ?? [];
	// 		break;
	// }
};
// 查询流程下一节点参数
const getNextStepOption = async (DefineId: string, Code: string) => {
	try {
		const res: any = await workflowStepOptions({ DefineId, Code });
    state.handlerOptions = res.result.handlers ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 选择处理人
const selectHandlers = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
};
const showMainHandler = computed(() => {
	return state.ruleForm.nextHandlers.length > 1;
});
// 主办从处理人中选择
state.handlerMainOptions = computed(() => {
	return state.ruleForm.nextHandlers;
});
// 设置抽屉
const dialogRef = ref<RefType>(); // 弹窗ref
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 选择常用意见 填入填写框
const chooseAdvice = (item: any) => {
	state.ruleForm.opinion += item.content;
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		ElMessageBox.confirm(`确认提交?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				state.loading = true;
				let submitObj = other.deepClone(state.ruleForm);
				if (submitObj.nextHandlers && submitObj.nextHandlers.length) {
					submitObj.nextHandlers = submitObj.nextHandlers.map((item: any) => {
						return {
							id: item.key,
							name: item.value,
						};
					});
					if (submitObj.nextHandlers.length === 1) {
						submitObj.nextMainHandler = submitObj.nextHandlers[0].id;
					}
				}
				switch (state.processType) {
					case 'addStart': //开始新增流程
						KnowledgeAddStartFlow(state.workflowId, submitObj)
							.then(() => {
								ElMessage.success('操作成功');
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessSuccess');
							})
							.catch(() => {
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessFailed');
							});
						break;
					case 'deleteStart': //开始删除流程
						KnowledgeDeleteStartFlow(state.workflowId, submitObj)
							.then(() => {
								ElMessage.success('操作成功');
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessSuccess');
							})
							.catch(() => {
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessFailed');
							});
						break;
					case 'recall': // 撤回流程
						workflowRecall(submitObj)
							.then(() => {
								ElMessage.success('操作成功');
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessSuccess');
							})
							.catch(() => {
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessFailed');
							});
						break;
					case 'return': // 退回流程
						break;
					case 'next': // 默认下一流程
						workflowNext(submitObj)
							.then(() => {
								ElMessage.success('操作成功');
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessSuccess');
							})
							.catch(() => {
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessFailed');
							});
						break;

					default: // 默认下一流程
						workflowNext(submitObj)
							.then(() => {
								ElMessage.success('操作成功');
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessSuccess');
							})
							.catch(() => {
								state.loading = false;
								state.dialogVisible = false;
								emit('knowledgeProcessFailed');
							});
						break;
				}
			})
			.catch(() => {});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
