<template>
  <div class="tree-panel">
    <div class="tree-header">
      <el-button type="primary" @click="handleAddManufacturer">
        <el-icon><Plus /></el-icon>
        新增车企
      </el-button>
    </div>
    <div class="tree-container">
      <el-tree
        ref="treeRef"
        :data="treeData"
        node-key="id"
        :props="treeProps"
        :expand-on-click-node="false"
        :highlight-current="true"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span class="node-actions">
              <!-- 车企层级 -->
              <template v-if="data.type === 'oem'">
                <el-button link type="primary" @click="handleAddModel(data)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button link type="primary" @click="handleEdit(data)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button link type="danger" @click="handleDelete(data)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
              
              <!-- 车型层级 -->
              <template v-else-if="data.type === 'model'">
                <el-button link type="primary" @click="handleAddVersion(data)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button link type="primary" @click="handleEdit(data)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button link type="danger" @click="handleDelete(data)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
              
              <!-- 车机版本层级 -->
              <template v-else-if="data.type === 'version'">
                <el-button link type="primary" @click="handleEdit(data)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button link type="danger" @click="handleDelete(data)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 树节点编辑对话框 -->
    <TreeDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :level="currentLevel"
      :form-data="formData"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import TreeDialog from './TreeDialog.vue'
import { getTreeDataApi, postTreeData, updateTreeData, deleteTreeData } from '@/api/is/func/index'

// 定义 emits
const emit = defineEmits()

// 树形结构数据
const treeData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentNode = ref(null)
// 表单数据
const formData = reactive({
  name: '',
  remark: '',
  type: 'oem'
})

// 当前操作的相关信息
const currentAction = ref('add')
const currentLevel = ref(0)

// 树形配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 树节点点击
const handleNodeClick = (data) => {
  emit('node-click', data)
}

// 新增车企
const handleAddManufacturer = () => {
  currentAction.value = 'add'
  dialogTitle.value = '新增车企'
  formData.type = 'oem'
  dialogVisible.value = true
  currentNode.value = null
}

// 新增车型
const handleAddModel = (node) => {
  currentAction.value = 'add'
  dialogTitle.value = '新增车型'
  formData.type = 'model'
  dialogVisible.value = true
  currentNode.value = node
}

// 新增车机版本
const handleAddVersion = (node) => {
  currentAction.value = 'add'
  currentNode.value = node
  formData.type = 'version'
  dialogTitle.value = '新增车机版本'
  dialogVisible.value = true
}

// 编辑节点
const handleEdit = (node) => {
  currentAction.value = 'edit'
  dialogTitle.value = getEditTitle(node.level)
  formData.name = node.label
  formData.type = node.type
  currentNode.value = node
  formData.remark = node.remark || ''
  dialogVisible.value = true
}

// 删除节点
const handleDelete = (node) => {
  ElMessageBox.confirm(
    `确定要删除"${node.label}"吗？此操作不可恢复。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteNode(node)
  }).catch(() => {
    // 用户取消删除
  })
}

// 删除节点
const deleteNode = async (node) => {
 if (node.children && node.children.length > 0) {
    ElMessage.warning('请先删除该节点的子节点')
    return
 }
  const res = await deleteTreeData(node.id)
  if (res.code === 200) {
    getTree()
  }
  ElMessage.success(res?.msg || '操作失败')
}

// 重置表单
const resetForm = () => {
  formData.name = ''
  formData.remark = ''
  formData.type = 'oem'
}

// 获取编辑标题
const getEditTitle = (level) => {
  const titles = ['', '编辑车企', '编辑车型', '编辑车机版本']
  return titles[level] || '编辑'
}

// 确认树节点操作
const handleConfirm = async (valid, data) => {
  if (valid) {
    if (currentAction.value === 'add') {
      const res = await postTreeData({
        ...data,
        type: formData.type,
        parentId:  formData.type === 'oem' ? null : currentNode.value.id
      })
      if (res.code === 200) {
        dialogVisible.value = false
        getTree()
        resetForm()
      }
      ElMessage.success(res?.msg || '操作失败')
    } else if (currentAction.value === 'edit') {
      const res = await updateTreeData({
        ...data,
        id: currentNode.value.id
      })
      if (res.code === 200) {
        dialogVisible.value = false
        getTree()
        resetForm()
      }
      ElMessage.success(res?.msg || '操作失败')
    }
  }
}

const getTree = async () => {
  const res = await getTreeDataApi()
  if (res) {
    treeData.value = res
  }
}

onMounted(() => {
  getTree()
})
</script>

<style scoped>
.tree-panel {
  height: 100%;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-container {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  display: flex;
  gap: 4px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}
</style>