<template>
  <div class="organization-container">
    <el-row :gutter="16">
      <!-- 左侧：组织架构树 -->
      <el-col :span="8">
        <el-card shadow="hover" class="tree-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>组织架构</span>
              <el-button type="primary" link @click="handleAddRoot">
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
            </div>
          </template>
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <span class="node-label">{{ node.label }}</span>
                <div class="node-actions" @click.stop>
                  <el-button link type="primary" size="small" @click="handleAdd(data)">
                    <el-icon><Plus /></el-icon>
                  </el-button>
                  <el-button link type="primary" size="small" @click="handleEdit(data)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button link type="danger" size="small" @click="handleDelete(data)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧：详情面板 -->
      <el-col :span="16">
        <el-card shadow="hover" class="detail-card">
          <template #header>
            <div class="card-header">
              <span>{{ detailTitle }}</span>
            </div>
          </template>
          
          <div v-if="selectedNode" class="detail-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="组织名称">
                {{ selectedNode.org_name }}
              </el-descriptions-item>
              <el-descriptions-item label="组织编码">
                {{ selectedNode.org_code || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="上级组织">
                {{ selectedNode.parent_name || '顶级组织' }}
              </el-descriptions-item>
              <el-descriptions-item label="负责人">
                {{ selectedNode.leader_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="是否是公司"> 
                <el-tag :type="selectedNode.is_company === 1 ? 'primary' : 'info'">
                  {{ selectedNode.is_company === 1 ? '是' : '否' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="状态"> 
                <el-tag :type="selectedNode.status === 1 ? 'success' : 'danger'">
                  {{ selectedNode.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ selectedNode.remark || '-' }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-actions">
              <el-button type="primary" @click="handleEdit(selectedNode)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(selectedNode)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>

          <el-empty v-else description="请选择左侧组织节点查看详情" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑对话框 -->
    <OrganizationEdit
      ref="editRef"
      :tree-data="treeData"
      :tree-props="treeProps"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import OrganizationEdit from './components/edit.vue'
import { getOrganizationList, getOrganizationDetail, deleteOrganization } from '@/api/erp'

// 树形结构数据（与后台字段对应）
interface TreeNode {
  id: number
  tid?: number
  org_name: string
  org_code?: string
  parent_id?: number
  parent_name?: string
  leader_id?: number
  leader_name?: string
  is_company?: number
  sort?: number
  status?: number
  remark?: string
  children?: TreeNode[]
}

// 树形数据
const treeData = ref<TreeNode[]>([])

const treeProps = {
  label: 'org_name',
  children: 'children',
  value: 'id'
}

const treeRef = ref()
const editRef = ref()
const selectedNode = ref<TreeNode | null>(null)
const loading = ref(false)

// 将扁平列表构建为树形结构
const buildTree = (list: any[]): TreeNode[] => {
  const nodeMap = new Map<number, TreeNode>()
  const roots: TreeNode[] = []

  list.forEach(item => {
    const node: TreeNode = {
      id: item.id,
      tid: item.tid,
      org_name: item.org_name,
      org_code: item.org_code,
      parent_id: item.parent_id,
      parent_name: item.parent_name,
      leader_id: item.leader_id,
      leader_name: item.leader_name,
      is_company: item.is_company,
      sort: item.sort,
      status: item.status,
      remark: item.remark,
      children: []
    }
    nodeMap.set(node.id, node)
  })

  nodeMap.forEach(node => {
    if (node.parent_id && nodeMap.has(node.parent_id)) {
      const parent = nodeMap.get(node.parent_id)!
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
}

// 获取组织机构详情
const loadOrganizationDetail = async (id: number) => {
  try {
    const res = await getOrganizationDetail(id)
    if (res.code === 200) {
      const data = res.data || null
      if (data) {
        selectedNode.value = {
          id: data.id,
          tid: data.tid,
          org_name: data.org_name,
          org_code: data.org_code,
          parent_id: data.parent_id,
          parent_name: data.parent_name,
          leader_id: data.leader_id,
          leader_name: data.leader_name,
          is_company: data.is_company,
          sort: data.sort,
          status: data.status,
          remark: data.remark,
          children: []
        }
      } else {
        selectedNode.value = null
      }
    } else {
      ElMessage.error(res.msg || '获取组织机构详情失败')
    }
  } catch (error) {
    console.error('获取组织机构详情失败:', error)
    ElMessage.error('获取组织机构详情失败')
  }
}

// 获取组织机构列表
const fetchOrganizationList = async () => {
  loading.value = true
  try {
    const res = await getOrganizationList()
    if (res.code === 200) {
      const list = res.data || []
      treeData.value = buildTree(list)

      // 如果当前没有选中的节点且有数据，默认加载第一个节点详情
      if (!selectedNode.value && list.length) {
        await loadOrganizationDetail(list[0].id)
      }
    } else {
      ElMessage.error(res.msg || '获取组织机构列表失败')
    }
  } catch (error) {
    console.error('获取组织机构列表失败:', error)
    ElMessage.error('获取组织机构列表失败')
  } finally {
    loading.value = false
  }
}

// 详情标题
const detailTitle = computed(() => {
  return selectedNode.value ? `部门详情 - ${selectedNode.value.org_name}` : '部门详情'
})

// 点击节点，加载详情
const handleNodeClick = (data: TreeNode) => {
  loadOrganizationDetail(data.id)
}

// 添加根节点
const handleAddRoot = () => {
  editRef.value?.open(undefined, undefined)
}

// 添加子节点
const handleAdd = (data: TreeNode) => {
  editRef.value?.open(undefined, data.id)
}

// 编辑
const handleEdit = (data: TreeNode) => {
  editRef.value?.open(data)
}

// 提交成功回调，重新加载列表
const handleSuccess = () => {
  fetchOrganizationList()
}

// 删除
const handleDelete = (data: TreeNode) => {
  ElMessageBox.confirm(`确定要删除部门「${data.org_name}」吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        const res = await deleteOrganization(data.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          fetchOrganizationList()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {})
}

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

<style lang="less" scoped>
.organization-container {
//   padding: 16px;
}

.tree-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 8px;

  .node-label {
    flex: 1;
  }

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

  &:hover .node-actions {
    display: flex;
  }
}

.detail-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .detail-content {
    .el-descriptions {
      margin-bottom: 20px;
    }

    .detail-actions {
      display: flex;
      gap: 12px;
      justify-content: flex-end;
    }
  }
}
</style>
