<template>
	<div class="system-workflow-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.activeName" @tab-change="handleClick" class="h100">
				<el-tab-pane label="流程模板" name="template"></el-tab-pane>
				<el-tab-pane label="流程实例" name="example"></el-tab-pane>
				<div class="flex-column">
					<el-form
						:model="state.queryParams"
						ref="ruleFormRef"
						:inline="true"
						@submit.native.prevent
						class="mt15"
						v-show="state.activeName === 'example'"
					>
						<el-form-item label="关键字查询" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" placeholder="流程标题/流程ID" style="width: 300px" clearable @keyup.enter="queryList" />
						</el-form-item>
						<el-form-item label="业务模块" prop="ModuleCode">
							<el-select v-model="state.queryParams.ModuleCode" class="w100" placeholder="请选择业务模块">
								<el-option v-for="item in state.moduleOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="queryList" :loading="state.loading" v-waves>
								<SvgIcon name="ele-Search" class="mr5" />查询
							</el-button>
							<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
						</el-form-item>
					</el-form>
					<div class="flex-center-between mb20">
						<p class="table-title">信息列表</p>
						<div>
							<el-button type="primary" @click="onAddTemp" v-waves v-if="state.activeName === 'template'" v-auth="'system:workflow:template:add'">
								<SvgIcon name="ele-Plus" class="mr5" />新增
							</el-button>
						</div>
					</div>
					<!-- 表格 -->
					<el-table :data="state.tableList" v-loading="state.loading" row-key="id">
						<el-table-column type="index" width="60" label="序号" />
						<!-- 模板 -->
						<template v-if="state.activeName === 'template'">
							<el-table-column prop="moduleName" label="业务模块" show-overflow-tooltip></el-table-column>
							<el-table-column prop="name" label="模板名称" show-overflow-tooltip></el-table-column>
							<el-table-column prop="code" label="模板编码" show-overflow-tooltip></el-table-column>
							<el-table-column prop="version" label="版本号" show-overflow-tooltip></el-table-column>
							<el-table-column prop="creationTime" label="更新时间" show-overflow-tooltip>
								<template #default="scope">
									<span>{{ formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="statusText" label="状态" show-overflow-tooltip></el-table-column>
							<el-table-column label="操作" width="150" fixed="right" align="center">
								<!-- 草稿0 启用1 禁用2 -->
								<template #default="scope">
									<el-button link type="primary" @click="onEditTemp(scope.row)" title="修改" v-auth="'system:workflow:template:edit'">
										修改
									</el-button>
									<el-button
										link
										type="success"
										v-if="scope.row.status === 0"
										@click="onReleaseTemp(scope.row)"
										title="发布"
										v-auth="'system:workflow:template:release'"
									>
										发布
									</el-button>
									<!-- <el-button link type="warning" v-if="scope.row.status === 2" @click="tempEnable(scope.row)" title="启用" v-auth="'system:workflow:template:enable'">
										启用
									</el-button> -->
									<el-button
										link
										type="danger"
										v-if="scope.row.status === 1"
										@click="tempDisable(scope.row)"
										title="禁用"
										v-auth="'system:workflow:template:disable'"
									>
										禁用
									</el-button>
									<!-- 发布之后不能修改 -->
									<el-button
										link
										v-if="scope.row.status === 0"
										type="danger"
										@click="onDeleteTemp(scope.row)"
										title="删除"
										v-auth="'system:workflow:template:delete'"
									>
										删除
									</el-button>
								</template>
							</el-table-column>
						</template>
						<!-- 实例 -->
						<template v-else-if="state.activeName === 'example'">
							<el-table-column prop="title" label="流程标题" show-overflow-tooltip width="300"></el-table-column>
							<el-table-column prop="statusText" label="流程状态" show-overflow-tooltip width="100"></el-table-column>
							<el-table-column prop="id" label="流程ID" show-overflow-tooltip width="300"></el-table-column>
							<el-table-column prop="moduleName" label="业务模块" show-overflow-tooltip width="170"></el-table-column>
							<el-table-column prop="moduleCode" label="流程模板" show-overflow-tooltip width="170"></el-table-column>
							<el-table-column prop="assignTime" label="创建时间" show-overflow-tooltip width="170">
								<template #default="scope">
									<span>{{ formatDate(scope.row.assignTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="completeTime" label="当前环节到达" show-overflow-tooltip width="170">
								<template #default="scope">
									<span>{{ formatDate(scope.row.completeTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="currentStepName" label="当前环节" show-overflow-tooltip width="170"></el-table-column>
							<el-table-column label="操作" width="140" fixed="right" align="center">
								<template #default="{ row }">
									<el-button
										link
										type="primary"
										@click="onLink(row)"
										title="跳转"
										v-if="![20, 30].includes(row.status)"
										v-auth="'system:workflow:jump'"
									>
										跳转
									</el-button>
									<el-button
										link
										type="danger"
										@click="onStopProcess(row)"
										title="终止流程"
										v-if="![20, 30].includes(row.status)"
										v-auth="'system:workflow:stop'"
									>
										终止流程
									</el-button>
								</template>
							</el-table-column>
						</template>
						<template #empty>
							<Empty />
						</template>
					</el-table>
					<!-- 分页 -->
					<pagination
						:total="state.total"
						v-model:page="state.queryParams.PageIndex"
						v-model:limit="state.queryParams.PageSize"
						@pagination="queryList"
					/>
				</div>
			</el-tabs>
		</div>
		<workflow-jump ref="workflowJumpRef" @updateList="queryList" />
	</div>
</template>

<script lang="ts" setup name="systemWorkflow">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
// 引入节流
import { throttle } from '/@/utils/tools';
import {
	workflowList,
	workflowPaged,
	workflowDelete,
	publishOnList,
	workflowEnable,
	workflowDisable,
	workflowTerminate,
	WorkflowHasDefine,
	baseData,
} from '/@/api/system/workflow';

// 引入组件
const WorkflowJump = defineAsyncComponent(() => import('/@/views/system/config/workflow/component/Workflow-jump.vue'));

// 定义接口来定义对象的类型
interface QueryState {
	activeName: string;
	queryParams: {
		PageIndex: number;
		PageSize: number;
		Keyword: string;
		ModuleCode: string;
	};
	tableList: Array<any>;
	loading: boolean;
	total: number;
	multipleSelection: Array<any>;
	moduleOptions: Array<any>;
}

// 定义变量内容
const state = reactive(<QueryState>{
	activeName: 'template',
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
		ModuleCode: '',
	},
	tableList: [],
	loading: false,
	total: 0,
	multipleSelection: [],
	moduleOptions: [],
});
const ruleFormRef = ref<FormInstance>();
const workflowJumpRef = ref(null as any);
const router = useRouter();
/** 获取列表 */
const queryList = () => {
	switch (state.activeName) {
		case 'template':
			state.loading = true;
			workflowList(state.queryParams)
				.then((response: any) => {
					state.tableList = response.result.items ?? [];
					state.total = response.result.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case 'example':
			state.loading = true;
			workflowPaged(state.queryParams)
				.then((response: any) => {
					state.tableList = response.result?.items ?? [];
					state.total = response.result?.total ?? 0;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		default:
			break;
	}
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 1000);
// 切换tab 查询列表
const handleClick = () => {
	queryList();
};
// 新增模板
const onAddTemp = () => {
	router.push({
		name: 'workflowAddEdit',
		params: {
			tagsViewName: '新增流程模板',
		},
	});
};
// 修改模板
const onEditTemp = (row: any) => {
	router.push({
		name: 'workflowAddEdit',
		params: {
			tagsViewName: '编辑流程-' + row.name,
			id: row.id,
		},
	});
};
// 删除模板
const onDeleteTemp = (row: any) => {
	ElMessageBox.confirm(`此操作将删除模板：“${row.name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			workflowDelete(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 发布模板
const onReleaseTemp = async (row: any) => {
	const response: any = await WorkflowHasDefine(row.moduleCode);
	if (response.result) {
		//若已存在有效模板
		ElMessageBox.confirm(`业务模块【${row.moduleName}】已有流程模板，确认覆盖当前版本？`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				publishOnList(row.id).then(() => {
					ElMessage.success('发布成功');
					queryList();
				});
			})
			.catch(() => {});
	} else {
		ElMessageBox.confirm(`此操作将发布模板：“${row.name}”，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				publishOnList(row.id).then(() => {
					ElMessage.success('发布成功');
					queryList();
				});
			})
			.catch(() => {});
	}
};
// 启用模板
const tempEnable = (row: any) => {
	ElMessageBox.confirm(`此操作将启用模板：“${row.name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			workflowEnable(row.id).then(() => {
				ElMessage.success('启用成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 禁用模板
const tempDisable = (row: any) => {
	ElMessageBox.confirm(`此操作将禁用模板：“${row.name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			workflowDisable(row.id).then(() => {
				ElMessage.success('禁用成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 跳转流程
const onLink = (row: any) => {
	workflowJumpRef.value.openDialog(row);
};
// 终止流程
const onStopProcess = (row: any) => {
	ElMessageBox.prompt('终止原因', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputPlaceholder: '请输入终止原因，不超过50字符',
		draggable: true,
		inputErrorMessage: '请输入终止原因',
		inputType: 'textarea',
		inputValidator: (value) => {
			if (value) return true;
			else return '请输入终止原因';
		},
	})
		.then(({ value }) => {
			let req = {
				workflowId: row.id,
				opinion: value,
			};
			ElMessageBox.confirm(`终止后，当前处理人将无法处理该流程，确定终止？`, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
				cancelButtonClass: 'default-button',
				autofocus: false,
			})
				.then(() => {
					workflowTerminate(req)
						.then(() => {
							ElMessage.success('操作成功');
							queryList();
						})
						.catch(() => {});
				})
				.catch(() => {});
		})
		.catch(() => {});
};
//
onMounted(async () => {
	queryList();
	// 获取页面基础信息
	const res: any = await baseData();
	state.moduleOptions = res.result?.moduleOptions ?? [];
});
</script>
<style lang="scss" scoped>
.system-workflow-container {
	:deep(.el-tabs__content) {
		height: 100%;
	}
	.flex-column {
		display: flex;
		flex-direction: column;
		height: calc(100% - 55px);
		.el-table {
			flex: 1;
		}
	}
}
</style>
