<template>
  <div id="category-tree" class="p-2 bg-white">
    <p>类目展示：</p>
    <el-tree
      ref="treeRef"
      style="max-width: 600px"
      :props="defaultProps"
      node-key="id"
      draggable
      :render-after-expand="false"
      check-strictly
      :load="handleLoadNode"
      lazy
      highlight-current
      @node-click="onClick"
      :expand-on-click-node="false"
      @node-drag-start="handleDragStart"
      @node-drag-enter="handleDragEnter"
      @node-drag-leave="handleDragLeave"
      @node-drag-over="handleDragOver"
      @node-drag-end="handleDragEnd"
      @node-drop="handleDrop"
    >
      <template #default="{ node, data }">
        <div class="category-tree-node">
          <span v-if="curId !== data.id">{{ data.name }}</span>
          <el-input
            ref="inputRef"
            v-else
            v-model="data.label2"
            size="small"
            class="w-40"
            @keyup.enter="handleInputConfirm(data)"
            @blur="handleInputCancel(node, data)"
          />
          <div>
            <el-button type="primary" link @click="onEdit(data)" size="small">编辑 </el-button>
            <el-button type="primary" link @click="append(data)" size="small"> 添加 </el-button>
            <el-button type="danger" size="small" link @click="remove(node, data)">
              删除
            </el-button>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ElButton } from 'element-plus'
import type { RenderContentContext } from 'element-plus'
import {
  handleDragStart,
  handleDragEnter,
  handleDragOver,
  handleDragLeave,
  handleDragEnd,
  handleDrop
} from './use-drag'

interface Tree {
  id: number
  name: string
  children?: Tree[]
}
type Node = RenderContentContext['node']
type Data = RenderContentContext['data']

const curId = ref(NaN)
const curParentId = ref(NaN)
// const curId = ref(NaN)
const inputRef = ref()
const treeRef = ref()

// 编辑类目名称
const onEdit = (data: Data) => {
  data.label2 = data.name
  curId.value = data.id
  nextTick(() => {
    inputRef.value.focus()
  })
}

// 回车确认
const handleInputConfirm = (data: any) => {
  if (curId.value === Infinity) {
    api.commodity.updateCategory.post!({ ...data, name: data.label2, parentId: curParentId.value })
  } else {
    api.commodity.updateCategory.post!({ ...data, name: data.label2 })
  }
  data.name = data.label2
  data.label2 = ''
  curId.value = NaN
}

// 失焦
const handleInputCancel = (node: Node, data: Data) => {
  if (data.id === Infinity) {
    remove(node, data)
  }
  curId.value = NaN
}

// 增加类目
const append = async (data: Data) => {
  const node = treeRef.value.getNode(data.id)
  curId.value = Infinity
  curParentId.value = data.id
  const newChild = { id: curId.value, name: '', label2: 'test', hasChild: false }
  if (!node.expanded) {
    await api.commodity.getCategoryList.post!<any>({ parentId: data.id || 0 }).then((res) => {
      res.data.forEach((item: any) => {
        treeRef.value.append(
          {
            ...item,
            children: item.hasChild ? [] : undefined
          },
          data
        )
      })
    })
  }
  treeRef.value.append(newChild, data)
  node.expanded = true
  nextTick(() => {
    inputRef.value.focus()
  })
}

// 删除类目
const remove = (node: Node, data: Data) => {
  const parent = node.parent
  const children: Tree[] = parent?.data.children || parent?.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
}

const defaultProps = {
  label: 'name',
  children: 'children',
  disabled: 'disabled',
  isLeaf: (data: any) => {
    return !data.hasChild
  }
}

// 获取类目列表
const handleLoadNode = (node, resolve) => {
  api.commodity.getCategoryList.post!<any>({ parentId: node.data.id || 0 }).then((res) => {
    resolve(
      res.data.map((item: any) => ({
        ...item,
        children: item.hasChild ? [] : undefined
      }))
    )
  })
}

const onClick = (data) => {
  console.warn('----- my data is data111: ', data)
}
</script>

<style lang="scss" scoped>
#category-tree {
  .category-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
