<template>
  <div class="admin-staff-container">
    <div class="header">
      <a-button type="primary" @click="showCreateModal">新增人员</a-button>
      <a-input-search
        v-model:value="searchValue"
        placeholder="请输入员工姓名"
        style="width: 200px"
        @search="onSearch"
      />
    </div>

    <a-table :columns="columns" :data-source="staffData" :pagination="pagination" class="staff-table">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-switch v-model:checked="record.status" @change="updateStaffStatus(record)" />
        </template>
        
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="showEditModal(record)">编辑</a-button>
            <a-button type="link" @click="handleResetPassword(record)">修改密码</a-button>
            <a-button type="link" danger @click="deleteStaff(record)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:open="isModalOpen"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="formData" layout="vertical">
        <a-form-item label="员工姓名">
          <a-input v-model:value="formData.name" placeholder="请输入员工姓名" />
        </a-form-item>
        <a-form-item label="所属部门">
          <a-select v-model:value="formData.department_id" placeholder="请选择部门">
            <a-select-option v-for="dept in departments" :key="dept.id" :value="dept.id">
              {{ dept.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="任职岗位">
          <a-select v-model:value="formData.position_id" placeholder="请选择岗位">
            <a-select-option v-for="pos in positions" :key="pos.id" :value="pos.id">
              {{ pos.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input v-model:value="formData.phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="身份证号码">
          <a-input v-model:value="formData.id_card" placeholder="请输入身份证号码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 搜索值
const searchValue = ref('')

// 员工数据
const staffData = ref([])

// 部门列表
const departments = ref([])

// 岗位列表
const positions = ref([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条记录`,
  onChange: (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    fetchAdminStaffList()
  },
  onShowSizeChange: (current, pageSize) => {
    pagination.current = 1
    pagination.pageSize = pageSize
    fetchAdminStaffList()
  }
})

// 模态框相关
const isModalOpen = ref(false)
const modalTitle = ref('新增行政人员')
const currentStaffId = ref(null)

// 表单数据
const formData = reactive({
  name: '',
  department_id: '',
  position_id: '',
  phone: '',
  id_card: '',
  status: true
})

// 表格列定义
const columns = [
  {
    title: '员工姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '所属部门',
    dataIndex: 'department',
    key: 'department',
  },
  {
    title: '任职岗位',
    dataIndex: 'position',
    key: 'position',
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '身份证号码',
    dataIndex: 'id_card',
    key: 'id_card',
  },
  {
    title: '账号使用状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    sorter: (a, b) => new Date(a.created_at) - new Date(b.created_at),
  },
  {
    title: '操作',
    key: 'action',
  }
]

// 获取行政人员列表
const fetchAdminStaffList = async () => {
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchValue.value
    }
    const response = await api.government.adminStaff.getList(params)
    
    // 确保response.data是一个数组
    if (response && Array.isArray(response.data)) {
      staffData.value = response.data.map(item => ({
        ...item,
        department: departments.value.find(dept => dept.id === item.department_id)?.name || '',
        position: positions.value.find(pos => pos.id === item.position_id)?.name || '',
        key: item.id
      }))
      pagination.total = response.total || response.data.length
    } else {
      // 处理异常情况
      staffData.value = []
      pagination.total = 0
      console.error('行政人员列表数据格式错误:', response)
    }
    
    console.log('行政人员列表数据:', staffData.value)
  } catch (error) {
    message.error('获取行政人员列表失败')
    console.error('获取行政人员列表失败:', error)
    // 添加错误详细信息展示
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误数据:', error.response.data)
    }
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await api.government.departments.getList()
    // 处理数据格式 - 确保departments是一个数组
    if (response && response.data && Array.isArray(response.data)) {
      departments.value = response.data
    } else if (response) {
      // 处理API返回的非标准格式数据
      departments.value = Object.values(response).map(item => 
        typeof item === 'object' ? item : { id: item, name: item }
      )
    }
    console.log('部门列表数据:', departments.value)
  } catch (error) {
    message.error('获取部门列表失败')
    console.error('获取部门列表失败:', error)
  }
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    const response = await api.government.positions.getList()
    // 处理数据格式 - 确保positions是一个数组
    if (response && response.data && Array.isArray(response.data)) {
      positions.value = response.data
    } else if (response) {
      // 处理API返回的非标准格式数据
      positions.value = Object.values(response).map(item => 
        typeof item === 'object' ? item : { id: item, name: item }
      )
    }
    console.log('岗位列表数据:', positions.value)
  } catch (error) {
    message.error('获取岗位列表失败')
    console.error('获取岗位列表失败:', error)
  }
}

// 初始化数据
const initData = async () => {
  await fetchDepartments()
  await fetchPositions()
  await fetchAdminStaffList()
}

// 搜索处理
const onSearch = (value) => {
  searchValue.value = value
  pagination.current = 1
  fetchAdminStaffList()
}

// 显示新增模态框
const showCreateModal = () => {
  currentStaffId.value = null
  modalTitle.value = '新增行政人员'
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  formData.status = true
  isModalOpen.value = true
}

// 显示编辑模态框
const showEditModal = (record) => {
  currentStaffId.value = record.id
  modalTitle.value = '编辑行政人员'
  formData.name = record.name
  formData.department_id = record.department_id
  formData.position_id = record.position_id
  formData.phone = record.phone
  formData.id_card = record.id_card
  formData.status = record.status
  isModalOpen.value = true
}

// 处理模态框确认
const handleModalOk = async () => {
  try {
    if (currentStaffId.value) {
      // 编辑
      await api.government.adminStaff.update(currentStaffId.value, formData)
      message.success('编辑行政人员成功')
    } else {
      // 新增
      await api.government.adminStaff.create(formData)
      message.success('新增行政人员成功')
    }
    isModalOpen.value = false
    fetchAdminStaffList()
  } catch (error) {
    message.error(currentStaffId.value ? '编辑行政人员失败' : '新增行政人员失败')
    console.error('操作行政人员失败:', error)
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  isModalOpen.value = false
}

// 更新员工状态
const updateStaffStatus = async (record) => {
  try {
    await api.government.adminStaff.update(record.id, {
      status: record.status
    })
    message.success('更新状态成功')
  } catch (error) {
    record.status = !record.status // 回滚状态
    message.error('更新状态失败')
    console.error('更新状态失败:', error)
  }
}

// 处理重置密码
const handleResetPassword = (record) => {
  Modal.confirm({
    title: '确认重置密码',
    content: `确定要重置 ${record.name} 的密码吗？重置后密码将变为 123456`,
    onOk: async () => {
      try {
        await api.government.adminStaff.resetPassword(record.id)
        message.success('重置密码成功')
      } catch (error) {
        message.error('重置密码失败')
        console.error('重置密码失败:', error)
      }
    }
  })
}

// 删除员工
const deleteStaff = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除 ${record.name} 吗？`,
    onOk: async () => {
      try {
        await api.government.adminStaff.delete(record.id)
        message.success('删除成功')
        fetchAdminStaffList()
      } catch (error) {
        message.error('删除失败')
        console.error('删除失败:', error)
      }
    }
  })
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>

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

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

.staff-table {
  margin-top: 16px;
}
</style>