<template>
  <div class="organization-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>组织架构管理</span>
          <el-button type="primary" @click="handleAdd">新增组织架构</el-button>
        </div>
      </template>
      <el-tree
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span>
              <el-button link type="primary" @click="handleAdd(data)">
                添加子级
              </el-button>
              <el-button link type="primary" @click="handleEdit(data)">
                编辑
              </el-button>
              <el-button link type="danger" @click="handleDelete(node, data)">
                删除
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增组织架构' : '编辑组织架构'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="组织名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="组织编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入组织编码" />
        </el-form-item>
        <el-form-item label="组织类型" prop="org_type">
          <el-select v-model="form.org_type" placeholder="请选择组织类型">
            <el-option
              v-for="option in ORG_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
        <!-- <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  GetOrganizationTree,
  CreateOrganization,
  UpdateOrganization,
  DeleteOrganization,
  type OrganizationParams,
  ORG_TYPE_OPTIONS
} from './api'

const treeData = ref([])
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentNode = ref<any>(null)

const defaultProps = {
  children: 'children',
  label: 'name'
}

const formRef = ref<FormInstance>()
const form = ref<OrganizationParams>({
  name: '',
  code: '',
  org_type: 1,
  parent: null,
  sort: 0, // 默认为0
  description: '',
  status: true
})

const rules: FormRules = {
  name: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入机构编码', trigger: 'blur' }],
  org_type: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 获取组织机构树数据
const fetchTreeData = async () => {
  try {
    const res = await GetOrganizationTree()
    treeData.value = res.data
  } catch (error) {
    console.error('获取组织机构树失败:', error)
    ElMessage.error('获取组织机构树失败')
  }
}

// 新增节点
const handleAdd = (data?: any) => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    code: '',
    org_type: data ? (data.org_type === 1 ? 2 : data.org_type === 2 ? 3 : 4) : 1, // 根据父级类型自动选择子级类型
    parent: data?.id || null,
    sort: 0,
    description: '',
    status: true
  }
  dialogVisible.value = true
}

// 编辑节点
const handleEdit = (data: any) => {
  dialogType.value = 'edit'
  currentNode.value = data
  form.value = { ...data }
  dialogVisible.value = true
}

// 删除节点
const handleDelete = async (node: any, data: any) => {
  try {
    await ElMessageBox.confirm('确认删除该组织机构吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await DeleteOrganization(data.id)
    ElMessage.success('删除成功')
    await fetchTreeData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await CreateOrganization(form.value)
      ElMessage.success('新增成功')
    } else {
      await UpdateOrganization(currentNode.value.id, form.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    await fetchTreeData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

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

<style scoped>
.organization-container {
  padding: 20px;
}

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

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