<template>
	<div>
		<el-dialog
			v-model="state.isShowDialog"
			draggable
			:title="state.title + '流程'"
			ref="dialogRef"
			@mouseup="mouseup"
			:style="'transform: ' + state.trasform + ';'"
			append-to-body
		>
			<el-form :model="state.ruleForm" label-width="90px" 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>
					<!-- 撤回 -->
					<template v-if="state.processType === 'recall'">
						<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="selectHandersRecall"
									value-key="key"
									clearable
								>
									<el-option v-for="item in state.handlerClassifies" :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">
							<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.handerMainOptions" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</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="处理人" prop="nextHandlers" :rules="[{ required: false, message: '请选择处理人', trigger: 'change' }]">
								<el-select
									v-model="state.ruleForm.nextHandlers"
									multiple
									filterable
									placeholder="请选择处理人"
									class="w100"
									@change="selectHanders"
									value-key="key"
									clearable
								>
									<el-option v-for="item in state.handerOptions" :key="item.key" :label="item.value" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<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.handerMainOptions" :key="item.key" :label="item.value" :value="item.key" />
								</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>
					</template>
					<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' }]"
						>
							<el-input
								v-model="state.ruleForm.opinion"
								type="textarea"
								:autosize="{ minRows: 10, maxRows: 10 }"
								placeholder="请填写常用意见"
								clearable
								max-length="2000"
							>
							</el-input>
							<span class="bttons">
								<el-button @click="showComents" class="default-button" :loading="state.loading">常用意见</el-button>
								<el-button type="primary" @click="onAddComments" :loading="state.loading">添加到常用意见</el-button>
							</span>
						</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' }]">
							<el-upload
								v-model:file-list="state.fileList"
								class="upload-demo w100"
								action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
								multiple
								:before-remove="beforeRemove"
								:on-exceed="handleExceed"
								ref="uploadListRef"
							>
								<el-button> <SvgIcon name="ele-Upload" /> 上传附件 </el-button>
								<template #file="{ file }">
									<div class="el-upload-list__item-info">
										<a class="el-upload-list__item-name">
											<SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="16px" />
											<span class="el-upload-list__item-file-name">{{ file.name }}</span>
										</a>
									</div>
									<SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" />
								</template>
							</el-upload>
						</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="onSave" :loading="loading">保 存</el-button> -->
					<el-button type="primary" @click="onSubmit" :loading="state.loading">提 交</el-button>
				</span>
			</template>
			<!-- 常用意见管理 -->
			<Comment ref="CommentRef" @chooseComment="chooseComment" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="KonwledgeProcess">
import { defineAsyncComponent, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus';
import { checkFile, fileType } from '/@/utils/tools';
import { addCommon } from '/@/api/business/commonP';
import {
	KnowledgeAddStartflowParams,
	KnowledgeUpdateStartflowParams,
	KnowledgeDeleteStartflowParams,
	KnowledgeAddStartflow,
	KnowledgeUpdateStartflow,
	KnowledgeDeleteStartflow,
} from '/@/api/knowledge';
import { workflowNextsteps, workflowNext, workflowRecall, workflowJump } from '/@/api/system/workflow';

// 引入组件
const Comment = defineAsyncComponent(() => import('/@/views/business/order/components/Comment.vue'));
// 定义子组件向父组件传值/事件
const emit = defineEmits(['onSubmitProcess']);
// 定义变量内容
const state = reactive<any>({
	isShowDialog: false,
	title: '提交',
	ruleForm: {
		nextStepCode: '',
		nextHandlers: [],
		nextMainHandler: '',
		acceptSms: false,
		opinion: '',
	},
	nextStepOptions: [], // 下一节点
	handerOptions: [], // 处理人
	trasform: 'translate(0px, 0px)',
	fileList: [],
	loading: false,
	isStartFlow: false, //是否开启流程
	processType: 'next',
	workflowId: '', //流程id
	commonEeum: '',
	handlerClassifies: [], //撤回处理人
	handerMainOptions: [], // 主办人
});
const ruleFormRef = ref();
const CommentRef = ref();
const dialogRef = ref();
const uploadListRef = ref();
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
	state.processType = val.processType ?? 'next'; // 流程状态
	state.workflowId = val.id ?? ''; // 流程id
	state.commonEeum = val.commonEeum ?? ''; // 常用意见类型
	state.title = val.title ?? '提交流程'; // 流程标题
	let res: any = {};
	switch (state.processType) {
		case 'addStart':
			res = await KnowledgeAddStartflowParams(); //获取新增开启流程参数
			state.nextStepOptions = res.result;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handerOptions = state.nextStepOptions[0].nextSteps;
			}
			break;
		case 'editStart':
			res = await KnowledgeUpdateStartflowParams(); //获取修改开启流程参数
			state.nextStepOptions = res.result;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handerOptions = state.nextStepOptions[0].nextSteps;
			}
			break;
		case 'deleteStart':
			res = await KnowledgeDeleteStartflowParams(); //获取删除开启流程参数
			state.nextStepOptions = res.result;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handerOptions = state.nextStepOptions[0].nextSteps;
			}
			break;
		case 'recall': // 撤回流程
			res = await workflowRecall(state.workflowId); //撤回参数
			state.nextStepOptions = res.result;
			state.ruleForm.workflowId = state.workflowId;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handlerClassifies = state.nextStepOptions[0].handlerClassifies;
			}
			break;
		case 'return': // 退回流程
			break;
		case 'next': // 默认下一流程
			res = await workflowNextsteps(state.workflowId);
			state.ruleForm.workflowId = state.workflowId;
			state.nextStepOptions = res.result;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handerOptions = state.nextStepOptions[0].nextSteps;
			}
			break;

		default: // 默认下一流程
			res = await workflowNextsteps(state.workflowId);
			state.ruleForm.workflowId = state.workflowId;
			state.nextStepOptions = res.result;
			if (state.nextStepOptions.length === 1) {
				state.ruleForm.nextStepCode = state.nextStepOptions[0].code;
				state.handerOptions = state.nextStepOptions[0].nextSteps;
			}
			break;
	}
	state.isShowDialog = true;
};
// 流程选择下一环节
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextMainHandler');
	let next: any;
	switch (state.processType) {
		case 'addStart' || 'editStart' || 'deleteStart':
			next = state.nextStepOptions.find((item: any) => item.code === val);
			state.handerOptions = 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.handerOptions = next.nextSteps ?? [];
			break;
	}
};
// 选择处理人
const selectHanders = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
};
// 选择处理人撤回
const selectHandersRecall = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
};
// 主办从处理人中选择
state.handerMainOptions = computed(() => {
	return state.ruleForm.nextHandlers;
});
// 设置抽屉
const mouseup = () => {
	state.trasform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 删除确认
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
	return ElMessageBox.confirm(`确定要删除 ${uploadFile.name} ?`).then(
		() => true,
		() => false
	);
};
// 删除文件
const handleRemove = (file: any) => {
	uploadListRef.value.handleRemove(file);
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
	ElMessage.warning(`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length} totally`);
};
// 打开常用意见管理
const showComents = () => {
	CommentRef.value.openDialog(state.commonEeum);
};
// 添加到常用意见
const onAddComments = async () => {
	if (!state.ruleForm.opinion) {
		ElMessage.warning(`请先填写${state.title}意见`);
		return;
	}
	await addCommon({
		typeCode: state.commonEeum,
		content: state.ruleForm.opinion,
	});
	ElMessage.success('操作成功');
	CommentRef.value.closeDialog();
};
// 选择常用意见 填入填写框
const chooseComment = (item: any) => {
	state.ruleForm.opinion += item.content;
	CommentRef.value.closeDialog();
};
// 保存
// const onSave = () => {
// 	ruleFormRef.value.validate((valid: boolean) => {
// 		if (valid) {
// 			loading.value = true;
// 			emit('onSubmit');
// 		} else {
// 			return false;
// 		}
// 	});
// };
// 提交
const onSubmit = () => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			ElMessageBox.confirm(`确认提交?`, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
				cancelButtonClass: 'default-button',
				autofocus: false,
			})
				.then(() => {
					state.loading = true;
					let submitObj = JSON.parse(JSON.stringify(state.ruleForm));
					submitObj.nextHandlers = submitObj.nextHandlers.map((item: any) => {
						return {
							id: item.key,
							name: item.value,
						};
					});
					switch (state.processType) {
						case 'addStart': //开始新增流程
						KnowledgeAddStartflow(state.workflowId, submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;
						case 'editStart': //开始更新流程
						KnowledgeUpdateStartflow(state.workflowId, submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;
						case 'deleteStart': //开始删除流程
						KnowledgeDeleteStartflow(state.workflowId, submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;
						case 'recall': // 撤回流程
							workflowJump(submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;
						case 'return': // 退回流程
							break;
						case 'next': // 默认下一流程
							workflowNext(submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;

						default: // 默认下一流程
							workflowNext(submitObj)
								.then(() => {
									ElMessage.success('操作成功');
									state.loading = false;
									state.isShowDialog = false;
									emit('onSubmitProcess');
								})
								.catch(() => {
									state.loading = false;
									state.isShowDialog = false;
								});
							break;
					}
				})
				.catch(() => {});
		} else {
			return false;
		}
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss" scoped>
.upload-demo {
	:deep(.el-upload-list) {
		display: flex;
		flex-wrap: wrap;
		.el-upload-list__item {
			width: calc(25% - 10px);
			border: var(--el-border);
			margin-right: 10px;
		}
	}
}
.textarea {
	position: relative;
	.bttons {
		position: absolute;
		right: 10px;
		bottom: 10px;
	}
}
</style>
