<template>
	<div class="list_group_container">
		<div v-if="!hideAddInput" class="group_list">
			<div class="group_header flex flex-pack-justify flex-align-center">
				<div class="group_header_title">
					<span>
						<el-input v-model="listGroupName" v-autoFocus placeholder="请输入流程组名称" @blur="addFlowGroup" />
					</span>
				</div>
			</div>
		</div>
		<div v-for="(item, idx) in myArray" :key="item.categoryId" class="group_list">
			<div class="group_header flex flex-pack-justify flex-align-center">
				<div class="group_header_title">
					<span>
						<template v-if="!item.editor">
							{{ item.categoryName }}
						</template>
						<template v-else>
							<el-input v-model="item.categoryName" v-autoFocus placeholder="请输入流程组名称" @blur="editFlowGroup('save', item, idx)" />
						</template>
					</span>
				</div>
				<div class="group_header_nameOperate">
					<el-space>
						<el-icon :size="16" class="edit_icon" @click="editFlowGroup('edit', item, idx)"><EditPen /></el-icon>
					</el-space>
					<el-space style="margin-left: 10px">
						<el-tooltip effect="dark" content="删除" placement="top">
							<el-icon :size="16" @click="deleteFlowGroup(item)"><Delete /></el-icon>
						</el-tooltip>
					</el-space>
				</div>
			</div>
			<div class="group_body">
				<ul class="group_list_ul">
					<draggable :list="item.processList" item-key="id">
						<template #item="{ element }">
							<div>
								<li class="group_item flex flex-align-center">
									<LeIcon class="group_itemIcon" :icon-class="`${flowIconPrefix}${element.processIcon}`" />
									<!--									<div class="group_itemIcon">
                    <img :src="getAssetsFile(element.processIcon + '.svg')" />
									</div>-->
									<div class="group_itemLeft">
										<div class="group_itemNameWrapper flex flex-align-center" style="margin-bottom: 5px">
											<div class="group_itemName">
												<span>{{ element.processName }}</span>
											</div>
										</div>
										<div class="group_itemIntro">{{ element.title }}</div>
									</div>
									<div class="group_itemSeeable">
										<el-tag round>V{{ element.processVersion }}</el-tag>
										<el-tag v-if="element.processState === 0" type="danger" round>已停用</el-tag>
									</div>
									<div class="group_itemSeeable">{{ element.processKey }}</div>
									<div class="group_itemOperations">
										<el-space wrap>
											<el-tooltip effect="dark" content="编辑" placement="top">
												<el-icon :size="16" @click="updateEv(element.processId)"><EditPen /></el-icon>
											</el-tooltip>
										</el-space>
										<el-space wrap style="margin-left: 10px">
											<el-tooltip effect="dark" content="复制" placement="top">
												<el-icon :size="16" @click="copyEv(element.processId)"><CopyDocument /></el-icon>
											</el-tooltip>
										</el-space>
										<el-space wrap style="margin-left: 10px">
											<el-tooltip v-if="element.processState === 1" effect="dark" content="禁用" placement="top">
												<el-icon :size="16" @click="enabledEv(element.processId, 0)"><CircleClose /></el-icon>
											</el-tooltip>
											<el-tooltip v-if="element.processState === 0" effect="dark" content="启用" placement="top">
												<el-icon :size="16" @click="enabledEv(element.processId, 1)"><Check /></el-icon>
											</el-tooltip>
										</el-space>
										<el-space wrap>
											<el-popconfirm title="确定删除?" @confirm="stopEv(element.processId)">
												<template #reference>
													<el-icon :size="16"><Delete /></el-icon>
												</template>
											</el-popconfirm>
										</el-space>
									</div>
								</li>
							</div>
						</template>
					</draggable>
				</ul>
			</div>
		</div>
	</div>
</template>

<script lang="tsx" setup>
import Draggable from 'vuedraggable'
import { Delete, CircleClose, EditPen, CopyDocument } from '@element-plus/icons-vue'
import { ref, onActivated, nextTick, onMounted } from 'vue'
import flowGroup from '@/api/flow/group'
import flowDefinition from '@/api/flow/definition'
import { ElMessage, ElMessageBox } from 'element-plus'
import process from '@/api/flow/process'
import router from '@/router'
import { flowIconPrefix /*, getAssetsFile*/ } from '@/utils/index'
const myArray = ref([])
const hideAddInput = ref(true)
const listGroupName = ref('')

// 显示隐藏添加流程组元素
const showAddInput = () => {
	hideAddInput.value = !hideAddInput.value
}

// 新增流程组
const addFlowGroup = async () => {
	if (!listGroupName.value.trim()) {
		showAddInput()
		return false
	}
	try {
		const param = {
			name: listGroupName.value,
			categorySort: 0
		}
		await flowGroup.flowGroupAddOrEditSaveApi(param)
		showAddInput()
		flowGroupListAll()
	} catch (e) {
		console.log(e)
	}
}

// 流程组列表
const flowGroupListAll = async (item = {}) => {
	try {
		const data = await flowDefinition.flowDefinitionListCategoryApi(item)
		myArray.value = data || []
		console.log(data)
	} catch (e) {
		console.log(e)
	}
}

// 流程组删除
const deleteFlowGroup = (item: any) => {
	try {
		// todo 这里需要判断当前的流程组下是否有实例,有不能删除,没有 直接调用删除接口
		ElMessageBox.confirm('是否删除该分组？', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'error',
			buttonSize: 'default'
		})
			.then(async () => {
				ElMessage({
					message: '删除成功!',
					type: 'success'
				})
				await flowGroup.flowGroupDeleteApi([item.categoryId])
				flowGroupListAll()
			})
			.catch(() => {
				console.log('取消')
			})
	} catch (e) {
		console.log(e)
	}
}

/**
 * 编辑流程组函数
 *
 * @param type 操作类型，'edit'表示编辑，其他表示保存
 * @param item 当前项
 * @param idx 当前项的索引
 * @returns 如果type为'edit'，则返回false；否则返回undefined
 */
const editFlowGroup = async (type, item, idx) => {
	if (type === 'edit') {
		myArray.value[idx].editor = true
		return false
	}
	try {
		myArray.value[idx].editor = false
		const param = {
			id: myArray.value[idx].categoryId,
			name: myArray.value[idx].categoryName,
			sort: myArray.value[idx].categorySort
		}
		await flowGroup.flowGroupAddOrEditSaveApi(param)
		flowGroupListAll()
	} catch (e) {
		console.log(e)
	}
}

// 删除
const stopEv = async (id: any) => {
	await process.progressDeleteApi({ id })
	flowGroupListAll()
}

/**
 * 启用/禁用事件处理函数
 *
 * @param id 要启用/禁用的元素的ID
 * @param state 启用/禁用的状态，1表示启用，0表示禁用
 * @returns 无返回值，执行异步操作
 */
const enabledEv = async (id: any, state: number) => {
	await process.processUpdateStateApi({ id, state: state })
	flowGroupListAll()
}

/**
 * 复制事件处理函数
 *
 * @param id 要复制的元素的ID
 * @returns 无返回值，执行异步操作
 */
const copyEv = async (id: any) => {
	await process.progressCloneApi({ id })
	flowGroupListAll()
}

// 修改
const updateEv = async (id: any) => {
	router.push('/flow_create?id=' + id)
}

// keep-alive缓存树，防止创建完流程过后，回到当前窗口未刷新
onActivated(() => {
	flowGroupListAll()
})

/**
 * 当组件被挂载到 DOM 后，执行回调函数
 */
onMounted(() => {
	nextTick(() => {
		flowGroupListAll()
	})
})

// 父组件使用的话需要导出
defineExpose({
	showAddInput,
	searchProcessEv: flowGroupListAll
})
</script>

<style scoped lang="scss">
.list_group_container {
	// 同sortGroup一样的样式
	.group_list {
		border-radius: 4px;
		margin-bottom: 16px;
		box-shadow: 0px 0px 3px 1px rgb(238, 238, 238);
		background-color: var(--el-bg-color);
		font-family: PingFangSC-Regular;
		.group_header {
			height: 54px;
			padding: 0px 16px 0px 12px;
			font-size: 16px;
			line-height: 24px;
			background-color: rgba(244, 245, 246, 0.5);
			&_title {
				position: relative;
				font-family: PingFangSC-Medium;
				display: flex;
				align-items: center;
				&.disabled {
					color: var(--el-text-color-disabled);
				}
				.edit_line {
					display: inline-block;
					width: 200px;
					border: 1px solid var(--el-text-color-primary);
					visibility: hidden;
					height: 36px;
					position: absolute;
					left: -5px;
				}
				.edit_icon {
					right: -170px;
					visibility: hidden;
				}
				&:hover {
					.edit_line,
					.edit_icon {
						visibility: visible;
					}
				}
			}
			&_nameOperate {
				cursor: pointer;
			}
		}

		.group_body,
		.group_list_ul {
			box-sizing: border-box;
			padding: 0;
			//width: 1000px;
		}
		.group_item {
			justify-content: flex-start;
			padding: 8px 12px;
			&:not(.group_item-disabled):hover {
				background-color: var(--el-fill-color-lighter);
			}
			.group_itemIcon {
				flex-shrink: 0;
				margin-right: 8px;
				height: 42px;
				width: 42px;
				border-radius: 50%;
				overflow: hidden;
				font-size: 42px;
				/*img {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}*/
			}
			.group_itemLeft {
				width: 426px;
				//flex-shrink: 0;
				padding-right: 8px;
			}
			.group_itemSeeable {
				min-width: 175px;
				font-size: 14px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				flex: 1 1;
				.el-tag + .el-tag {
					margin-left: 4px;
				}
			}
			.group_itemOperations {
				max-width: 350px;
				flex-shrink: 0;
				display: flex;
				cursor: pointer;
			}
			.group_itemIntro {
				font-size: 14px;
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
				line-height: 17px;
				font-family: PingFangSC-Regular;
			}
			.group_itemNameWrapper {
				justify-content: flex-start;
			}
			.group_itemName {
				max-width: 418px;
				font-size: 14px;
				text-overflow: ellipsis;
				overflow: hidden;
				white-space: nowrap;
				line-height: 16px;
				font-weight: 500;
				font-family: PingFangSC-Medium;
			}
		}
	}
}
</style>
