<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleAdd()">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="dept_id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="dept_name" label="部门名称" width="260" />
      <el-table-column prop="order_num" label="排序" width="100" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleAdd(row)">新增</el-button>
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row)" v-if="row.parent_id !== 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :props="{ children: 'children', label: 'label', value: 'id' }"
                placeholder="选择上级部门"
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 部门管理页面
 * @author 湖北新华业务中台研发团队
 */
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 查询参数
const queryParams = reactive({
  deptName: '',
  status: ''
})

// 列表数据
const loading = ref(false)
const deptList = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({})
const deptOptions = ref([])

const rules = {
  deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
}

// 构建树形结构
const buildTree = (list) => {
  const result = []
  const map = {}
  
  list.forEach(item => {
    map[item.dept_id] = { ...item, children: [] }
  })
  
  list.forEach(item => {
    const node = map[item.dept_id]
    if (item.parent_id === 0) {
      result.push(node)
    } else if (map[item.parent_id]) {
      map[item.parent_id].children.push(node)
    }
  })
  
  return result
}

// 获取部门列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/system/dept/list', { params: queryParams })
    deptList.value = buildTree(res.data || [])
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取部门树选项
const getDeptOptions = async (excludeId) => {
  try {
    let url = '/api/system/dept/treeselect'
    if (excludeId) {
      url = `/api/system/dept/list/exclude/${excludeId}`
    }
    const res = await request.get(url)
    if (excludeId) {
      // 需要构建树形结构
      const list = res.data || []
      deptOptions.value = buildTreeOptions(list)
    } else {
      deptOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

const buildTreeOptions = (list) => {
  const result = []
  const map = {}
  
  list.forEach(item => {
    map[item.dept_id] = { id: item.dept_id, label: item.dept_name, children: [] }
  })
  
  list.forEach(item => {
    const node = map[item.dept_id]
    if (item.parent_id === 0) {
      result.push(node)
    } else if (map[item.parent_id]) {
      map[item.parent_id].children.push(node)
    }
  })
  
  return result
}

// 搜索
const handleQuery = () => {
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.deptName = ''
  queryParams.status = ''
  handleQuery()
}

// 展开/折叠
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  setTimeout(() => {
    refreshTable.value = true
  }, 0)
}

// 新增
const handleAdd = (row) => {
  getDeptOptions()
  form.value = {
    parentId: row?.dept_id || 0,
    status: '0',
    orderNum: 0
  }
  dialogTitle.value = '新增部门'
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  getDeptOptions(row.dept_id)
  try {
    const res = await request.get(`/api/system/dept/${row.dept_id}`)
    const data = res.data
    form.value = {
      deptId: data.dept_id,
      parentId: data.parent_id,
      deptName: data.dept_name,
      orderNum: data.order_num,
      leader: data.leader,
      phone: data.phone,
      email: data.email,
      status: data.status
    }
    dialogTitle.value = '编辑部门'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取部门信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value?.validate()
  try {
    if (form.value.deptId) {
      await request.put('/api/system/dept', form.value)
      ElMessage.success('修改成功')
    } else {
      await request.post('/api/system/dept', form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除
const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确认删除部门"${row.dept_name}"?`, '提示', { type: 'warning' })
  try {
    await request.delete(`/api/system/dept/${row.dept_id}`)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

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

<style scoped>
.search-form {
  margin-bottom: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
