<template>
  <div class="admin-department-container">
    <template v-for="dept in departments" :key="dept.id">
      <div class="header">
        <div class="title">部门：{{ dept.name }}</div>
        <div class="actions">
          <a-button type="primary" danger @click="handleDeleteDepartment(dept.id)">删除部门</a-button>
          <a-button type="primary" @click="showAddPositionModal(dept.id, dept.name)">新增岗位</a-button>
        </div>
      </div>

      <a-table :columns="columns" :data-source="formatPositionsData(dept.positions)" :pagination="false" class="department-table">
        <template #headerCell="{ column }">
          <span>{{ column.title }}</span>
        </template>
        
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'permission'">
            <a-tag v-if="record.permission === '已设置权限'" color="success">{{ record.permission }}</a-tag>
            <a-tag v-else color="warning">{{ record.permission }}</a-tag>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="showEditPositionModal(record)">编辑岗位名称</a-button>
              <a-button type="link" danger @click="handleDeletePosition(record.id)">删除岗位</a-button>
              <a-button type="link" @click="showSetPermissionModal(record)">设置权限</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </template>

    <div class="add-department">
      <a-button type="primary" @click="showAddDepartmentModal">新增部门</a-button>
    </div>

    <!-- 新增部门模态框 -->
    <a-modal v-model:visible="addDepartmentModalVisible" title="新增部门" @ok="handleAddDepartment" @cancel="handleCancel">
      <a-form-model ref="addDepartmentForm" :model="addDepartmentFormData" :rules="addDepartmentRules">
        <a-form-model-item label="部门名称" name="name">
          <a-input v-model="addDepartmentFormData.name" placeholder="请输入部门名称" />
        </a-form-model-item>
        <a-form-model-item label="部门描述" name="description">
          <a-textarea v-model="addDepartmentFormData.description" placeholder="请输入部门描述" :rows="3" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 新增岗位模态框 -->
    <a-modal v-model:visible="addPositionModalVisible" title="新增岗位" @ok="handleAddPosition" @cancel="handleCancel">
      <a-form-model ref="addPositionForm" :model="addPositionFormData" :rules="addPositionRules">
        <a-form-model-item label="所属部门" name="department_name">
          <a-input v-model="addPositionFormData.department_name" disabled />
        </a-form-model-item>
        <a-form-model-item label="岗位名称" name="name">
          <a-input v-model="addPositionFormData.name" placeholder="请输入岗位名称" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 编辑岗位模态框 -->
    <a-modal v-model:visible="editPositionModalVisible" title="编辑岗位" @ok="handleEditPosition" @cancel="handleCancel">
      <a-form-model ref="editPositionForm" :model="editPositionFormData" :rules="editPositionRules">
        <a-form-model-item label="岗位名称" name="name">
          <a-input v-model="editPositionFormData.name" placeholder="请输入岗位名称" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 设置权限模态框 -->
    <a-modal v-model:visible="setPermissionModalVisible" title="设置权限" @ok="handleSetPermission" @cancel="handleCancel" :width="600">
      <div>
        <p>岗位: {{ currentPosition?.name }}</p>
        <div style="margin-top: 16px;">
          <p>权限设置示例</p>
          <a-alert type="info" message="实际项目中，这里应该是具体的权限选择界面" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/utils/api-redesigned'

// 表格列定义
const columns = [
  {
    title: '岗位',
    dataIndex: 'position',
    key: 'position',
  },
  {
    title: '系统基础权限',
    dataIndex: 'permission',
    key: 'permission',
  },
  {
    title: '操作',
    key: 'action',
  }
]

// 部门数据
const departments = ref([])

// 当前选中的岗位
const currentPosition = ref(null)

// 模态框控制
const addDepartmentModalVisible = ref(false)
const addPositionModalVisible = ref(false)
const editPositionModalVisible = ref(false)
const setPermissionModalVisible = ref(false)

// 表单数据
const addDepartmentFormData = reactive({
  name: '',
  description: ''
})

const addPositionFormData = reactive({
  department_id: '',
  department_name: '',
  name: ''
})

const editPositionFormData = reactive({
  id: '',
  name: ''
})

// 表单验证规则
const addDepartmentRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ]
}

const addPositionRules = {
  name: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ]
}

const editPositionRules = {
  name: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ]
}

// 从API获取部门数据
const fetchDepartments = async () => {
  try {
    const response = await api.government.departments.getList()
    departments.value = response?.data || response
  } catch (error) {
    message.error('获取部门数据失败：' + error.message)
    console.error('获取部门数据失败:', error)
  }
}

// 格式化岗位数据
const formatPositionsData = (positions) => {
  return positions.map(pos => ({
    key: pos.id,
    id: pos.id,
    position: pos.name,
    permission: pos.permission
  }))
}

// 显示新增部门模态框
const showAddDepartmentModal = () => {
  // 重置表单
  Object.keys(addDepartmentFormData).forEach(key => {
    addDepartmentFormData[key] = ''
  })
  addDepartmentModalVisible.value = true
}

// 显示新增岗位模态框
const showAddPositionModal = (departmentId, departmentName) => {
  // 重置表单
  Object.keys(addPositionFormData).forEach(key => {
    addPositionFormData[key] = ''
  })
  addPositionFormData.department_id = departmentId
  addPositionFormData.department_name = departmentName
  addPositionModalVisible.value = true
}

// 显示编辑岗位模态框
const showEditPositionModal = (record) => {
  editPositionFormData.id = record.id
  editPositionFormData.name = record.position
  editPositionModalVisible.value = true
}

// 显示设置权限模态框
const showSetPermissionModal = (record) => {
  currentPosition.value = record
  setPermissionModalVisible.value = true
}

// 新增部门
const handleAddDepartment = async () => {
  try {
    await api.government.departments.create({
      name: addDepartmentFormData.name,
      description: addDepartmentFormData.description
    })
    message.success('部门创建成功')
    addDepartmentModalVisible.value = false
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('创建部门失败：' + error.message)
    console.error('创建部门失败:', error)
  }
}

// 新增岗位
const handleAddPosition = async () => {
  try {
    await api.government.positions.create({
      department_id: addPositionFormData.department_id,
      name: addPositionFormData.name
    })
    message.success('岗位创建成功')
    addPositionModalVisible.value = false
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('创建岗位失败：' + error.message)
    console.error('创建岗位失败:', error)
  }
}

// 编辑岗位
const handleEditPosition = async () => {
  try {
    await api.government.positions.update(editPositionFormData.id, {
      name: editPositionFormData.name
    })
    message.success('岗位编辑成功')
    editPositionModalVisible.value = false
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('编辑岗位失败：' + error.message)
    console.error('编辑岗位失败:', error)
  }
}

// 删除岗位
const handleDeletePosition = async (positionId) => {
  try {
    await api.government.positions.delete(positionId)
    message.success('岗位删除成功')
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('删除岗位失败：' + error.message)
    console.error('删除岗位失败:', error)
  }
}

// 删除部门
const handleDeleteDepartment = async (departmentId) => {
  try {
    await api.government.departments.delete(departmentId)
    message.success('部门删除成功')
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('删除部门失败：' + error.message)
    console.error('删除部门失败:', error)
  }
}

// 设置权限
const handleSetPermission = async () => {
  try {
    await api.government.positions.setPermission(currentPosition.value.id, {
      permission_details: { basic: ['view', 'edit', 'add'], advanced: ['delete'] }
    })
    message.success('权限设置成功')
    setPermissionModalVisible.value = false
    // 重新获取数据
    await fetchDepartments()
  } catch (error) {
    message.error('设置权限失败：' + error.message)
    console.error('设置权限失败:', error)
  }
}

// 取消操作
const handleCancel = () => {
  addDepartmentModalVisible.value = false
  addPositionModalVisible.value = false
  editPositionModalVisible.value = false
  setPermissionModalVisible.value = false
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDepartments()
})
</script>

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

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  margin-left: 8px;
}

.department-table {
  margin-bottom: 24px;
}

.add-department {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>