<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">
				<el-tab-pane label="流程业务" name="0" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane label="流程模板" name="1" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent  v-if="state.activeName === '1'">
				<el-form-item label="关键字查询" prop="Keyword">
					<el-input
						v-model="state.queryParams.Keyword"
						placeholder="模板名称/模板编码"
						clearable
						@keyup.enter="handleQuery"
						class="keyword-input"
					/>
				</el-form-item>
				<el-form-item label="模板状态" prop="Status">
					<el-select v-model="state.queryParams.Status" placeholder="请选择模板状态" @change="handleQuery" clearable>
						<el-option v-for="item in state.statusList" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<!--    流程业务      -->
			<template v-if="state.activeName === '0'">
				<vxe-toolbar
					ref="toolbarRef1"
					:loading="state.loading"
					custom
					:refresh="{
						queryMethod: handleQuery,
					}"
				>
				</vxe-toolbar>
				<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
					<vxe-table
						border
						:loading="state.loading"
						:data="state.tableData"
						:column-config="{ resizable: true }"
						:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
						ref="tableRef1"
						height="auto"
						auto-resize
						show-overflow
						:scrollY="{ enabled: true, gt: 100 }"
						id="systemWorkflow1"
						:custom-config="{ storage: true }"
						showHeaderOverflow
					>
						<vxe-column field="name" title="业务模块" min-width="120"></vxe-column>
						<vxe-column field="code" title="编码" min-width="120"></vxe-column>
						<vxe-column field="remark" title="备注" min-width="140"></vxe-column>
						<vxe-column field="definition.name" title="模板名称" width="120"></vxe-column>
						<vxe-column field="definition.code" title="模板编码" width="120"></vxe-column>
						<vxe-column field="definition.version" title="模板版本" width="120"></vxe-column>
						<vxe-column title="操作" fixed="right" width="160" align="center">
							<template #default="{ row }">
								<el-button link type="primary" @click="onConfig(row)" title="配置模板" v-auth="'system:workflow:template:config'">
									配置模板</el-button
								>
								<el-button
									link
									type="danger"
									@click="configClear(row)"
									title="清除配置"
									v-if="row.definition"
									v-auth="'system:workflow:template:clear'"
								>
									清除配置
								</el-button>
							</template>
						</vxe-column>
					</vxe-table>
				</div>
			</template>
			<!--    流程模板      -->
			<template v-else>

				<vxe-toolbar
					ref="toolbarRef2"
					:loading="state.loading"
					custom
					:refresh="{
						queryMethod: handleQuery,
					}"
				>
					<template #buttons>
						<el-button type="primary" @click="onAddTemp" v-auth="'system:workflow:template:add'">
							<SvgIcon name="ele-Plus" class="mr5" />新增模板
						</el-button>
					</template>
				</vxe-toolbar>
				<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
					<vxe-table
						border
						:loading="state.loading"
						:data="state.tableData"
						:column-config="{ resizable: true }"
						:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
						ref="tableRef2"
						height="auto"
						auto-resize
						show-overflow
						:scrollY="{ enabled: true, gt: 100 }"
						id="systemWorkflow2"
						:custom-config="{ storage: true }"
						showHeaderOverflow
					>
						<vxe-column field="name" title="模板名称" min-width="120"></vxe-column>
						<vxe-column field="code" title="模板编码" min-width="120"></vxe-column>
						<vxe-column field="version" title="版本号" width="120"></vxe-column>
						<vxe-column field="statusText" title="状态" width="120"></vxe-column>
						<vxe-column field="creationTime" title="更新时间" width="160">
							<template #default="{ row }">
								{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
							</template>
						</vxe-column>
						<vxe-column title="操作" fixed="right" width="150" align="center">
							<template #default="{ row }">
								<!-- 草稿0 启用1 禁用2 -->
								<el-button link type="primary" @click="onEditTemp(row)" title="修改" v-auth="'system:workflow:template:edit'"> 修改 </el-button>
								<el-button
									link
									type="success"
									v-if="row.status === 0"
									@click="onReleaseTemp(row)"
									title="发布"
									v-auth="'system:workflow:template:publish'"
								>
									发布
								</el-button>
								<!-- 发布之后不能修改 -->
								<el-button
									link
									v-if="row.status === 0"
									type="danger"
									@click="onDeleteTemp(row)"
									title="删除"
									v-auth="'system:workflow:template:delete'"
								>
									删除
								</el-button>
							</template>
						</vxe-column>
					</vxe-table>
				</div>
			</template>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
				v-if="state.activeName === '1'"
			/>
		</div>
		<!--  流程跳转 -->
		<workflow-jump ref="workflowJumpRef" @updateList="queryList" />
		<!--  配置模板  -->
		<Workflow-config ref="workflowConfigRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="systemWorkflow">
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } 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 {
	baseData,
	publishOnList,
	wfmodules,
	wfmodulesMatch,
	workflowDelete,
	workflowList,
	// workflowTerminate,
} from '@/api/system/workflow';

// 引入组件
const WorkflowJump = defineAsyncComponent(() => import('@/views/system/config/workflow/components/Workflow-jump.vue')); // 流程跳转
const WorkflowConfig = defineAsyncComponent(() => import('@/views/system/config/workflow/components/Workflow-config.vue')); // 流程配置
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	activeName: '0', // 0:模板 1:实例 2:历史
	queryParams: {
		// 查询参数
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		Keyword: null, // 关键字
		Status: null,
		ModuleCode: null, // 模块编码
	},
	tableData: [], // 表格数据
	loading: false, // 加载状态
	total: 0, // 总条数
	multipleSelection: [], // 多选
	moduleOptions: [], // 模块下拉
	statusList: [
		// 状态下拉
		{ label: '启用', value: '1' },
		{ label: '草稿', value: '0' },
	],
});

const ruleFormRef = ref<FormInstance>(); // 表单ref
const workflowJumpRef = ref(null as any); // 跳转ref
const workflowConfigRef = ref(null as any); // 配置ref
const router = useRouter(); // 路由
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const queryList = () => {
	state.loading = true;
	let req: any = {
		PageIndex: state.queryParams.PageIndex,
		PageSize: state.queryParams.PageSize,
		Keyword: state.queryParams.Keyword,
		Status: state.queryParams.Status,
		ModuleCode: state.queryParams.ModuleCode,
	};
	switch (state.activeName) {
		case '0':
			wfmodules()
				.then((response: any) => {
					state.tableData = response.result ?? [];
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case '1':
			req = {
				...req,
				Status: state.queryParams.Status,
			};
			workflowList(req)
				.then((response: any) => {
					state.tableData = response.result.items ?? [];
					state.total = response.result.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		default:
			break;
	}
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 切换tab 查询列表
const tableRef1 = ref<RefType>();
const toolbarRef1 = ref<RefType>();
const tableRef2 = ref<RefType>();
const toolbarRef2 = ref<RefType>();
const handleClick = () => {
	state.queryParams.Keyword = null;
	state.queryParams.Status = null;
	state.queryParams.ModuleCode = null;
	queryList();
	nextTick(() => {
		if (tableRef1.value && toolbarRef1.value) {
			tableRef1.value.connect(toolbarRef1.value);
		}
		if (tableRef2.value && toolbarRef2.value) {
			tableRef2.value.connect(toolbarRef2.value);
		}
	});
};
// 新增模板
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) => {
	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 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(() => {});
};*/

// 配置模板
const onConfig = (row: any) => {
	workflowConfigRef.value.openDialog(row);
};
// 清除配置
const configClear = (row: any) => {
	ElMessageBox.confirm(`确认清除${row.name} 的配置?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			wfmodulesMatch({ code: row.code, definitionId: '' })
				.then(() => {
					ElMessage.success('操作成功');
					queryList();
				})
				.catch(() => {});
		})
		.catch(() => {});
};
const params = history.state;
// 获取页面基础信息
const getBaseData = async () => {
	const res: any = await baseData();
	state.moduleOptions = res.result?.moduleOptions ?? [];
};
// 页面加载时
onMounted(async () => {
	await getBaseData();
	if (params.index) {
		state.activeName = params.index as string;
	}
	queryList();
	if (tableRef1.value && toolbarRef1.value) {
		tableRef1.value.connect(toolbarRef1.value);
	}
	if (tableRef2.value && toolbarRef2.value) {
		tableRef2.value.connect(toolbarRef2.value);
	}
});
</script>
