// 流程设计列表 - 左侧 流程分类树
<template>
	<!-- 新增流程分类（父级） -->
	<div :class="style['process-category-add-wrapper']">
		<div :class="style['wrapper-caption']">流程分类</div>

		<!-- v-if="
				getButtonPermission(
					CommonConstant.permissionKeys.processCategorySave.value
				)
			" -->
		<a-button
			type="primary"
			:size="'small'"
			style="margin-right: 1em"
			@click="onAddClick"
		>
			<template #icon>
				<plus-outlined />
			</template>
		</a-button>
	</div>

	<div style="padding: 0 1em; width: 100%">
		<!-- 展示全部组织 -->
		<a-input-search
			v-model:value="searchValue"
			style="margin-bottom: 8px"
			:placeholder="
				getI18n('common', 'Common_Please_Enter', [
					getI18n('common', 'Common_KeyWords'),
				])
			"
		/>
		<!-- <template v-if="isShowAllDeptList"> -->
		<!-- @check="onCheck"
			v-if="treeDataList.length"
			:tree-data="treeDataList"
			v-model:expandedKeys="expandedKeysValue"
			v-model:selectedKeys="selectedKeysTemp"
			v-model:checkedKeys="checkedKeysIdArr"
			@select="onSelect" -->
		<a-tree
			class="design-category-custom-dropdown-wrapper"
			:expandedKeys="expandedKeys"
			:auto-expand-parent="autoExpandParent"
			:tree-data="gData"
			@expand="onExpand"
			@select="onSelect"
		>
			<template #title="{ key: treeKey, title, isShowIcon }">
				<div
					@mouseenter="onTreeTitleMouseEnter(treeKey)"
					@mouseleave="onTreeTitleMouseEnter(treeKey)"
				>
					<!-- 文字 -->

					<!-- <span :style=" searchValue&&title.indexOf(searchValue) > -1 ? 'color: #f5222d' : '' " :class="isShowIcon?'tree-title':''" :title="title">
						{{ title }}
					</span> -->

					<span
						v-if="title.indexOf(searchValue) > -1"
						:class="isShowIcon ? 'tree-title' : ''"
						:title="title"
					>
						{{ title.substr(0, title.indexOf(searchValue)) }}
						<span style="color: #f5222d">{{ searchValue }}</span>
						{{
							title.substr(
								title.indexOf(searchValue) + searchValue.length
							)
						}}
					</span>
					<span
						v-else
						:class="isShowIcon ? 'tree-title' : ''"
						:title="title"
					>
						{{ title }}
					</span>

					<!-- 按钮 -->
					<span v-if="isShowIcon" class="operation-icon-wrapper">
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.processCategorySave.value
								)
							" -->
						<PlusOutlined
							class="operation-icon"
							@click="
								e => (
									e.stopPropagation(), onIconAddClick(treeKey)
								)
							"
						/>
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.processCategoryUpdate.value
								)
							" -->
						<FormOutlined
							class="operation-icon"
							@click="
								e => (
									e.stopPropagation(),
									onIconEditClick(treeKey)
								)
							"
						/>
						<!-- v-if="
								getButtonPermission(
									CommonConstant.permissionKeys
										.processCategoryDelete.value
								)
							" -->
						<DeleteOutlined
							class="operation-icon"
							@click="
								e => (
									e.stopPropagation(),
									onIconDeleteClick(treeKey)
								)
							"
						/>
					</span>
				</div>
			</template>
		</a-tree>
		<!-- </template> -->
		<!-- 懒加载组织 -->
		<!-- <template v-else>
			<a-tree
				v-if="treeDataList.length"
				:load-data="onLoadData"
				:tree-data="treeDataList"
				:expandKeys="expandedKeysValue"
				:checkable="isCheckable"
				v-model:expandedKeys="expandedKeysValue"
				v-model:selectedKeys="selectedKeysTemp"
				v-model:checkedKeys="checkedKeysIdArr"
				@select="onSelect"
				@check="onCheck"
			/>
		</template> -->
	</div>

	<!-- 确认删除 -->
	<base-operational-qualification
		:confirm-modal-visible="deleteProcessCategoryVisible"
		@confirm-modal-ok="onDeleteOkClick"
		@confirm-modal-cancel="onDeleteCancelClick"
	/>

	<!-- 新增/编辑弹窗 -->
	<process-category-edit-modal
		:confirm-modal-visible="editProcessCategoryVisible"
		:process-category-id="editProcessCategoryId"
		:parent-process-category-id="addProcessCategoryParentId"
		:sel-node-parent-name="currentTreeNodeParentName"
		@confirm-add-modal-refresh="onTreeModalRefreshClick"
		@confirm-add-modal-cancel="onTreeModalCancelClick"
	/>
</template>
<script lang="ts">
import { message } from 'ant-design-vue'
import style from './index.module.less'
import { ProcessCategoryEditModal } from './components'
import {
	PlusOutlined,
	FormOutlined,
	DeleteOutlined,
} from '@ant-design/icons-vue'
import { getI18n } from '@/utils/i18n'
import { RequestResult } from '@/utils/request/model'
import { defineComponent, PropType, ref, watch, onMounted } from 'vue'
import { ProcessCategoryTreeModel } from '@/types/process'
import { ProcessConstant, CommonConstant } from '@/utils/constant'
import { DeleteProcessCategoryParamsModel } from '@/api/process-category/model'
import {
	getProcessCategoryRoleTreeApi,
	deleteProcessCategoryApi,
	// getProcessCategoryListApi,
} from '@/api/process-category'
import { validatenull } from '@/utils/tool/translateValue'
// import { getButtonPermission } from '@/utils/tool/translateValue'

export default defineComponent({
	components: {
		PlusOutlined,
		FormOutlined,
		DeleteOutlined,
		ProcessCategoryEditModal,
	},
	props: {
		// 选中的数据
		selectedKeys: {
			type: Array as PropType<string[]>,
			required: false,
			default: () => [],
		},
		expandKeys: {
			type: Array as PropType<string[]>,
			required: false,
			default: () => [],
		},
	},
	emits: ['on-tree-select', 'on-select-dept-id'],
	setup(_props, context) {
		// const selectedKeys = ref<string[]>([])
		// 当前选择分类的 父级名称集合
		const currentTreeNodeParentName = ref<string>()

		const processCategoryLoading = ref<boolean>(false)
		const expandedKeys = ref<string[]>([])
		const searchValue = ref<string>('')
		const autoExpandParent = ref<boolean>(true)
		const gData = ref<ProcessCategoryTreeModel[]>([])
		const dataList = ref<
			{
				key: string
				title: string
				isShowIcon?: boolean
			}[]
		>([])

		const onExpand = (keys: string[]) => {
			expandedKeys.value = keys
			autoExpandParent.value = false
		}

		const getParentKey = (
			key: string,
			tree: ProcessCategoryTreeModel[]
		): string | number | undefined => {
			let parentKey
			for (let i = 0; i < tree.length; i++) {
				const node = tree[i]
				if (node.children) {
					if (node.children.some(item => item.key === key)) {
						parentKey = node.key
					} else if (getParentKey(key, node.children)) {
						parentKey = getParentKey(key, node.children)
					}
				}
			}
			return parentKey
		}

		const generateList = (data: ProcessCategoryTreeModel[]) => {
			for (let i = 0; i < data.length; i++) {
				const node = data[i]
				dataList.value.push({
					key: data[i].key || '',
					title: data[i].title || '',
					isShowIcon: data[i].isShowIcon,
				})
				if (node.children) {
					generateList(node.children)
				}
			}
		}

		/**
		 * 显示层级数据
		 * @param tree {Array} 树数据
		 * @param func {Function} 回调函数
		 * @param field {String} 字段名称
		 * @param path {Array} 路径数据
		 * @returns {*[]|[]|*}
		 */
		const treeFindPath = (
			tree: ProcessCategoryTreeModel[],
			func: Function,
			field: string,
			path: string[] = []
		) => {
			if (!tree) return []
			for (const data of tree) {
				field === '' ? '' : path.push(data[field])
				if (func(data)) return path
				if (data.children) {
					const findChildren = treeFindPath(
						data.children,
						func,
						field,
						path
					)
					if (findChildren.length) return findChildren
				}
				path.pop()
			}
			return []
		}

		// 初始化树
		const initTree = async () => {
			// val?: GetOrgsListParamsModel
			processCategoryLoading.value = true
			const res: RequestResult<ProcessCategoryTreeModel[]> =
				await getProcessCategoryRoleTreeApi().finally(() => {
					processCategoryLoading.value = false
				})

			generateList(res.data)
			gData.value = res.data
		}

		watch(searchValue, value => {
			const expanded = dataList.value
				.map((item: ProcessCategoryTreeModel) => {
					if ((item.title as string).indexOf(value) > -1) {
						return getParentKey(item.key as string, gData.value)
					}
					return null
				})
				.filter((item, i, self) => item && self.indexOf(item) === i)
			expandedKeys.value = expanded as string[]
			searchValue.value = value
			autoExpandParent.value = true
		})

		// 编辑、新增弹框
		const editProcessCategoryVisible = ref<boolean>(false)
		// 新增流程分类（一级）
		const onAddClick = () => {
			editProcessCategoryVisible.value = true
		}

		// 编辑弹框 分类Id
		const editProcessCategoryId = ref<string>()
		const addProcessCategoryParentId = ref<string>()

		// 编辑、新增弹框取消
		const onTreeModalCancelClick = () => {
			editProcessCategoryId.value = undefined
			addProcessCategoryParentId.value = undefined
			editProcessCategoryVisible.value = false

			currentTreeNodeParentName.value = undefined
		}
		// 编辑、新增弹框确认
		const onTreeModalRefreshClick = async () => {
			onTreeModalCancelClick()
			// 刷新流程分类树
			await initTree()
		}

		// 遍历树，isShowIcon切换
		const treeForeach = (tree: ProcessCategoryTreeModel[], key: string) => {
			tree.forEach((v: ProcessCategoryTreeModel) => {
				v.children && treeForeach(v.children, key) // 遍历子树
				v.key === key ? (v['isShowIcon'] = !v.isShowIcon) : ''
			})
		}

		// tree-item 鼠标移入、移出  操作按钮的显示/隐藏
		const onTreeTitleMouseEnter = (key: string) => {
			treeForeach(gData.value, key)
		}

		// tree-item 操作按钮的点击
		// 新增下级分类
		const onIconAddClick = (key: string) => {
			editProcessCategoryVisible.value = true
			addProcessCategoryParentId.value = key

			let _curSelectNodeParentName = treeFindPath(
				gData.value,
				data => data.key === key,
				'title'
			)
			currentTreeNodeParentName.value =
				!validatenull(_curSelectNodeParentName) &&
				_curSelectNodeParentName.join('/')
		}

		// 编辑当前分类
		const onIconEditClick = (key: string) => {
			editProcessCategoryVisible.value = true
			editProcessCategoryId.value = key

			let _curSelectNodeParentName = treeFindPath(
				gData.value,
				data => data.key === key,
				'title'
			)
			currentTreeNodeParentName.value =
				!validatenull(_curSelectNodeParentName) &&
				_curSelectNodeParentName.join('/')
		}

		// 删除当前分类
		const deleteProcessCategoryVisible = ref<boolean>(false)
		// 确认删除按钮loading
		const deleteCategoryId = ref<string>()
		const onIconDeleteClick = (key: string) => {
			deleteProcessCategoryVisible.value = true
			deleteCategoryId.value = key
		}
		// 确认删除
		const onDeleteOkClick = async () => {
			let params: DeleteProcessCategoryParamsModel = {
				id: deleteCategoryId.value,
			}
			await deleteProcessCategoryApi(params).then(res => {
				if (res.data && res.data.code == 200) {
					message.success(getI18n('common', 'Common_Success'))
				}
			})
			deleteProcessCategoryVisible.value = false
			// 刷新流程分类树
			await initTree()
		}
		// 取消删除
		const onDeleteCancelClick = () => {
			deleteProcessCategoryVisible.value = false
		}

		// 树选择
		// 下拉回调
		const onSelect = (
			val: string[],
			e: {
				selectedNodes: {
					props: {
						[x: string]: any
						ancestors: string
						title: string
						hasChildren: false
						deptCategory: number
					}
				}[]
			}
		) => {
			// 返回当前选择的树节点
			context.emit('on-tree-select', val)
			if (e.selectedNodes?.length > 0) {
				let deptId = e.selectedNodes[0].props.key
				// 返回当前树节点的id
				context.emit('on-select-dept-id', deptId)
			} else {
				context.emit('on-select-dept-id', undefined)
			}
		}

		onMounted(() => {
			initTree()
		})

		return {
			style,
			getI18n,
			expandedKeys,
			searchValue,
			autoExpandParent,
			ProcessConstant,
			gData,
			onExpand,
			onSelect,

			onAddClick,
			editProcessCategoryId,
			addProcessCategoryParentId,
			editProcessCategoryVisible,
			onTreeModalRefreshClick,
			onTreeModalCancelClick,

			onTreeTitleMouseEnter,
			onIconAddClick,
			onIconEditClick,
			onIconDeleteClick,

			deleteProcessCategoryVisible,
			onDeleteOkClick,
			onDeleteCancelClick,
			CommonConstant,
			// getButtonPermission,
			currentTreeNodeParentName,
		}
	},
})
</script>
