<template>
	<div class="system-workflow-container layout-pd">
		<el-card shadow="never">
			<el-tabs v-model="state.activeName" @tab-change="handleClick" class="h100">
				<el-tab-pane label="流程业务" name="0"></el-tab-pane>
				<el-tab-pane label="流程模板" name="1"></el-tab-pane>
				<el-tab-pane label="流程实例" name="2"></el-tab-pane>
				<div class="flex-column">
					<el-form
						:model="state.queryParams"
						ref="ruleFormRef"
						:inline="true"
						@submit.native.prevent
						class="mt15"
            v-if="['1','2'].includes(state.activeName)"
					>
						<el-form-item label="关键字查询" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" :placeholder="state.activeName ==='1' ? '模板名称/模板编码' : '流程标题/流程ID'" clearable @keyup.enter="queryList" />
						</el-form-item>
            <el-form-item label="模板状态" prop="Status"  v-show="state.activeName === '1'">
              <el-select v-model="state.queryParams.Status" class="w100" placeholder="请选择模板状态" v-show="state.activeName === '1'">
                <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 label="业务模块" prop="ModuleCode"  v-show="state.activeName === '2'">
							<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" :loading="state.loading"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
						</el-form-item>
					</el-form>
					<div class="mb20">
						<el-button type="primary" @click="onAddTemp" v-waves v-if="state.activeName === '1'" v-auth="'system:workflow:template:add'">
							<SvgIcon name="ele-Plus" class="mr5" />新增
						</el-button>
					</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 === '0'">
							<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="remark" label="备注" show-overflow-tooltip></el-table-column>
              <el-table-column prop="definition.name" label="模板名称" show-overflow-tooltip></el-table-column>
              <el-table-column prop="definition.code" label="模板编码" show-overflow-tooltip></el-table-column>
              <el-table-column prop="definition.version" label="模板版本" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button link type="primary" @click="onConfig(row)"  title="配置模板"> 配置模板</el-button>
                  <el-button link type="danger" @click="configClear(row)"  title="清除配置" v-if="row.definition"> 清除配置 </el-button>
                </template>
              </el-table-column>
						</template>
						<!-- 模板 -->
						<template v-if="state.activeName === '1'">
							<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="{ row }">
									<span>{{ formatDate(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="{ row }">
									<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 type="warning" v-if="row.status === 2" @click="tempEnable(row)" title="启用" v-auth="'system:workflow:template:enable'">
                    启用
                  </el-button> -->
									<!--									<el-button-->
									<!--										link-->
									<!--										type="danger"-->
									<!--										v-if="row.status === 1"-->
									<!--										@click="tempDisable(row)"-->
									<!--										title="禁用"-->
									<!--										v-auth="'system:workflow:template:disable'"-->
									<!--									>-->
									<!--										禁用-->
									<!--									</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>
							</el-table-column>
						</template>
						<!-- 实例 -->
						<template v-else-if="state.activeName === '2'">
							<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></el-table-column>
							<el-table-column prop="assignTime" label="创建时间" show-overflow-tooltip width="170">
								<template #default="{ row }">
									<span>{{ formatDate(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="{ row }">
									<span>{{ formatDate(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"
						v-if="state.activeName !== '0'"
					/>
				</div>
			</el-tabs>
		</el-card>
    <!--  流程跳转 -->
		<workflow-jump ref="workflowJumpRef" @updateList="queryList" />

    <!--  配置模板  -->
    <Workflow-config ref="workflowConfigRef" @updateList="queryList"/>
	</div>
</template>

<script lang="ts" setup name="systemWorkflow">
import { ref, reactive, onMounted, defineAsyncComponent,onActivated } from 'vue';
import { useRouter,useRoute } 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,
  baseData,
  wfmodules, wfmodulesMatch,
} from '/@/api/system/workflow';


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

// 定义变量内容
const state = reactive(<any>{
	activeName: '0', // 0:模板 1:实例 2:历史
	queryParams: { // 查询参数
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		Keyword: '',// 关键字
    Status:"",
		ModuleCode: '', // 模块编码
	},
	tableList: [], // 表格数据
	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 route = useRoute();
/** 获取列表 */
const queryList = () => {
	state.loading = true;
  let req:any = {
    PageIndex: state.queryParams.PageIndex,
    PageSize: state.queryParams.PageSize,
    Keyword: state.queryParams.Keyword,
  }
	switch (state.activeName) {
		case '0':
			wfmodules()
				.then((response: any) => {
					state.tableList = response.result ?? [];
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case '1':
      req = {
        ...req,
        Status:state.queryParams.Status
      }
			workflowList(req)
				.then((response: any) => {
					state.tableList = response.result.items ?? [];
					state.total = response.result.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case '2':
      req = {
        ...req,
        ModuleCode:state.queryParams.ModuleCode
      }
			workflowPaged(req)
				.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();
}, 500);
// 切换tab 查询列表
const handleClick = () => {
  state.queryParams.Keyword = '';
  state.queryParams.Status = '';
  state.queryParams.ModuleCode = '';
	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) => {
  console.log(row)
		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(() => {});
};


// 配置模板
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;
onMounted(async () => {
	queryList();
	// 获取页面基础信息
	const res: any = await baseData();
	state.moduleOptions = res.result?.moduleOptions ?? [];
  if(params.index){
    state.activeName = params.index as string;
  }
});
onActivated(() => {
  if(params.index){
    state.activeName = params.index as string;
  }
});
</script>
<style lang="scss" scoped>
.system-workflow-container {
	:deep(.el-tabs__content) {
		height: 100%;
	}
}
</style>
