<template>
	<div class="system-workflow-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="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="queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent class="mt15" v-show="activeName === 'example'">
						<el-form-item label="关键字查询" prop="Keyword">
							<el-input
								v-model="queryParams.Keyword"
								placeholder="流程标题/业务模块/流程ID"
								style="width: 300px"
								clearable
								@keyup.enter="getList(activeName)"
							/>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="getList(activeName)" :loading="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="activeName === 'template'">
								<SvgIcon name="ele-Plus" class="mr5" />新增
							</el-button>
						</div>
					</div>
					<!-- 表格 -->
					<el-table :data="tableList" v-loading="loading" row-key="id">
						<el-table-column type="index" width="60" label="序号" />
						<!-- 模板 -->
						<template v-if="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="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 text type="primary" @click="onEditTemp(scope.row)" title="修改">
										修改
										<!-- <SvgIcon name="ele-VideoPlay" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
									<el-button text type="success" v-if="scope.row.status === 0" @click="onReleaseTemp(scope.row)" title="发布">
										发布
										<!-- <SvgIcon name="ele-Download" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
									<el-button text type="warning" v-if="scope.row.status === 2" @click="tempEnable(scope.row)" title="启用">
										启用
										<!-- <SvgIcon name="ele-Connection" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
									<el-button text type="danger" v-if="scope.row.status === 1" @click="tempDisable(scope.row)" title="禁用">
										禁用
										<!-- <SvgIcon name="ele-Connection" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
									<!-- 发布之后不能修改 -->
									<el-button text v-if="scope.row.status === 0" type="danger" @click="onDeleteTemp(scope.row)" title="删除">
										删除
										<!-- <SvgIcon name="ele-Delete" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
								</template>
							</el-table-column>
						</template>
						<!-- 实例 -->
						<template v-else-if="activeName === 'example'">
							<el-table-column prop="title" label="流程标题" show-overflow-tooltip width="300"></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 prop="person" label="当前处理人" show-overflow-tooltip  width="170"></el-table-column>
							<el-table-column label="操作" width="120" fixed="right" align="center">
								<template #default="scope">
									<el-button text type="primary" @click="onLink(scope.row)" title="跳转">
										跳转
										<!-- <SvgIcon name="ele-VideoPlay" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
									<el-button text type="danger" @click="onStopProcess(scope.row)" title="终止流程">
										终止流程
										<!-- <SvgIcon name="ele-Download" size="var(--hotline-table-icon-font-size)" /> -->
									</el-button>
								</template>
							</el-table-column>
						</template>
						<template #empty>
							<Empty />
						</template>
					</el-table>
					<!-- 分页 -->
					<pagination :total="total" v-model:page="queryParams.PageIndex" v-model:limit="queryParams.PageSize" @pagination="getList(activeName)" />
				</div>
			</el-tabs>
		</div>
		<Jump ref="jumpRef" @updateList="getList(state.activeName)" />
	</div>
</template>

<script lang="ts" setup name="systemWorkflow">
import { ref, reactive, toRefs, onMounted, defineAsyncComponent,onActivated } 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,
	workflowRerminate,
	WorkflowHasdefine,
} from '/@/api/system/workflow';

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

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

// 定义变量内容
const state = reactive(<QueryState>{
	activeName: 'template',
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
	},
	tableList: [],
	loading: false,
	total: 0,
	multipleSelection: [],
});
const { queryParams, tableList, loading, total, activeName } = toRefs(state);
const ruleFormRef = ref<FormInstance>();
const jumpRef = ref(null as any);
const router = useRouter();
/** 获取列表 */
const getList = (val: string) => {
	queryParams.value.PageIndex = 1;
	state.loading = true;
	switch (val) {
		case 'template':
			workflowList(queryParams.value)
				.then((response: any) => {
					state.tableList = response?.result.items ?? [];
					state.total = response?.result.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case 'example':
			workflowPaged(queryParams.value)
				.then((response: any) => {
					state.tableList = response.result?.items ?? [];
					state.total = response.result?.total ?? 0;
					state.total = 1;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		default:
			break;
	}
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getList(state.activeName);
}, 1000);
// 切换tab 查询列表
const handleClick = (val: string) => {
	getList(val);
};
// 新增模板
const onAddTemp = () => {
	router.push({
		path: '/system/config/workflow/detail',
		query: {
			tagsViewName: '新增流程模板',
		},
	});
};
// 修改模板
const onEditTemp = (row: any) => {
	router.push({
		name:'workflowEdit',
		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('删除成功');
				getList(state.activeName);
			});
		})
		.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('发布成功');
					getList(state.activeName);
				});
			})
			.catch(() => {});
	} else {
		ElMessageBox.confirm(`此操作将发布模板：“${row.name}”，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				publishOnList(row.id).then(() => {
					ElMessage.success('发布成功');
					getList(state.activeName);
				});
			})
			.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('启用成功');
				getList(state.activeName);
			});
		})
		.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('禁用成功');
				getList(state.activeName);
			});
		})
		.catch(() => {});
};
// 跳转流程
const onLink = (row: any) => {
	jumpRef.value.openDialog(row);
};
// 终止流程
const onStopProcess = (row: any) => {
	ElMessageBox.confirm(`终止后，当前处理人将无法处理该流程，确定终止？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			workflowRerminate(row.id).then(() => {
				ElMessage.success('操作成功');
				getList(state.activeName);
			});
		})
		.catch(() => {});
};
//
onMounted(() => {
	getList(state.activeName);
});
onActivated(()=>{
	getList(state.activeName);
})
</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>
