<template>
  <div class="employee-management-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>员工管理</h1>
      <a-button type="primary" @click="handleAdd">
        <template #icon>
          <PlusOutlined />
        </template>
        新增人员
      </a-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-section">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-input
            v-model:value="searchQuery.value"
            placeholder="请输入员工姓名"
            @pressEnter="handleSearch"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
        </a-col>
        <a-col :span="4">
          <a-button @click="handleReset">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 员工表格 -->
    <div class="employees-table-section">
      <a-table
        :columns="columns"
        :data-source="employees"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        row-key="id"
        :scroll="{ x: 800 }"
      >
        <!-- 序号列 -->
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.key === 'index'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          
          <!-- 员工姓名列 -->
          <template v-else-if="column.key === 'name'">
            <span class="employee-name">{{ record.name }}</span>
          </template>
          
          <!-- 联系电话列 -->
          <template v-else-if="column.key === 'phone'">
            <span class="phone-number">{{ maskPhone(record.phone) }}</span>
          </template>
          
          <!-- 贷款专员列 -->
          <template v-else-if="column.key === 'isLoanSpecialist'">
            <a-tag :color="record.isLoanSpecialist ? 'green' : 'default'">
              {{ record.isLoanSpecialist ? '是' : '否' }}
            </a-tag>
          </template>
          
          <!-- 账号状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-switch
              :checked="record.status === 'active'"
              @change="(checked) => handleStatusChange(record, checked)"
              :loading="record.statusLoading"
            />
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleResetPassword(record)">
                重设密码
              </a-button>
              <a-button type="link" @click="handleEdit(record)">
                编辑
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑员工弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      :title="isEdit ? '编辑员工' : '新增员工'"
      width="600px"
      :confirm-loading="editLoading"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
        v-if="editModalVisible"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="员工编号" name="employeeNumber">
              <a-input
                v-model:value="editForm.employeeNumber"
                placeholder="请输入员工编号"
                :disabled="isEdit"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="员工姓名" name="name">
              <a-input
                v-model:value="editForm.name"
                placeholder="请输入员工姓名"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系电话" name="phone">
              <a-input
                v-model:value="editForm.phone"
                placeholder="请输入联系电话"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" name="email">
              <a-input
                v-model:value="editForm.email"
                placeholder="请输入邮箱"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="部门" name="department">
              <a-input
                v-model:value="editForm.department"
                placeholder="请输入部门"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="职位" name="position">
              <a-input
                v-model:value="editForm.position"
                placeholder="请输入职位"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="是否为贷款专员" name="isLoanSpecialist">
          <a-switch
            v-model:checked="editForm.isLoanSpecialist"
            checked-children="是"
            un-checked-children="否"
          />
        </a-form-item>
        
        <a-form-item v-if="!isEdit" label="初始密码" name="password">
          <a-input
            v-model:value="editForm.password"
            placeholder="请输入初始密码，默认为123456"
            type="password"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 重设密码弹窗 -->
    <a-modal
      v-model:open="resetPasswordModalVisible"
      title="重设密码"
      width="400px"
      :confirm-loading="resetPasswordLoading"
      @ok="handleResetPasswordSubmit"
      @cancel="handleResetPasswordCancel"
    >
      <a-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordFormRules"
        layout="vertical"
      >
        <a-form-item label="新密码" name="newPassword">
          <a-input
            v-model:value="resetPasswordForm.newPassword"
            placeholder="请输入新密码"
            type="password"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const searchQuery = ref({
  field: 'name',
  value: ''
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共${total}条`
})

// 表格列配置
const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center'
  },
  {
    title: '员工姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 150
  },
  {
    title: '贷款专员',
    dataIndex: 'isLoanSpecialist',
    key: 'isLoanSpecialist',
    width: 100,
    align: 'center'
  },
  {
    title: '账号状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

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

// 调试：监听employees变化
watch(employees, (newVal) => {
  console.log('employees数据变化:', newVal)
}, { deep: true })

// 编辑弹窗相关
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const isEdit = ref(false)
const editForm = reactive({
  id: null,
  employeeNumber: '',
  name: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  isLoanSpecialist: false,
  password: '123456'
})

const editFormRules = {
  employeeNumber: [
    { required: true, message: '请输入员工编号', trigger: 'blur' },
    { min: 3, max: 20, message: '员工编号长度在3-20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '员工姓名长度在2-50个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  department: [
    { max: 50, message: '部门名称不能超过50个字符', trigger: 'blur' }
  ],
  position: [
    { max: 50, message: '职位名称不能超过50个字符', trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ]
}

// 重设密码弹窗相关
const resetPasswordModalVisible = ref(false)
const resetPasswordLoading = ref(false)
const resetPasswordFormRef = ref()
const currentEmployee = ref(null)
const resetPasswordForm = reactive({
  newPassword: ''
})

const resetPasswordFormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ]
}

// 行选择配置
const selectedRowKeys = ref([])
const selectedRows = ref([])

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  }
}))

// 获取员工列表
const fetchEmployees = async () => {
  try {
    loading.value = true
    const response = await api.employees.getList({
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      searchField: searchQuery.value.field,
      searchValue: searchQuery.value.value
    })
    
    if (response.success) {
      console.log('API响应数据:', response.data)
      employees.value = response.data.employees.map(emp => ({
        ...emp,
        statusLoading: false
      }))
      pagination.value.total = response.data.pagination.total
      console.log('设置后的员工数据:', employees.value)
    } else {
      message.error(response.message || '获取员工列表失败')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    message.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchEmployees()
}

// 重置
const handleReset = () => {
  searchQuery.value = {
    field: 'name',
    value: ''
  }
  fetchEmployees()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchEmployees()
}

// 新增员工
const handleAdd = () => {
  isEdit.value = false
  editModalVisible.value = true
  Object.assign(editForm, {
    id: null,
    employeeNumber: '',
    name: '',
    phone: '',
    email: '',
    department: '',
    position: '',
    isLoanSpecialist: false,
    password: '123456'
  })
}

// 编辑员工
const handleEdit = (record) => {
  isEdit.value = true
  editModalVisible.value = true
  Object.assign(editForm, {
    id: record.id,
    employeeNumber: record.employeeNumber,
    name: record.name,
    phone: record.phone,
    email: record.email,
    department: record.department,
    position: record.position,
    isLoanSpecialist: record.isLoanSpecialist,
    password: ''
  })
}

// 编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true

    const data = { ...editForm }
    if (isEdit.value) {
      delete data.password // 编辑时不传密码
    }

    const response = isEdit.value
      ? await api.employees.update(editForm.id, data)
      : await api.employees.create(data)

    if (response.success) {
      message.success(isEdit.value ? '更新员工成功' : '创建员工成功')
      editModalVisible.value = false
      fetchEmployees()
    } else {
      message.error(response.message || (isEdit.value ? '更新员工失败' : '创建员工失败'))
    }
  } catch (error) {
    console.error('编辑员工失败:', error)
    message.error(isEdit.value ? '更新员工失败' : '创建员工失败')
  } finally {
    editLoading.value = false
  }
}

// 编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 重设密码
const handleResetPassword = (record) => {
  currentEmployee.value = record
  resetPasswordModalVisible.value = true
  resetPasswordForm.newPassword = ''
}

// 重设密码提交
const handleResetPasswordSubmit = async () => {
  try {
    await resetPasswordFormRef.value.validate()
    resetPasswordLoading.value = true

    const response = await api.employees.resetPassword(currentEmployee.value.id, {
      newPassword: resetPasswordForm.newPassword
    })

    if (response.success) {
      message.success('重设密码成功')
      resetPasswordModalVisible.value = false
    } else {
      message.error(response.message || '重设密码失败')
    }
  } catch (error) {
    console.error('重设密码失败:', error)
    message.error('重设密码失败')
  } finally {
    resetPasswordLoading.value = false
  }
}

// 重设密码取消
const handleResetPasswordCancel = () => {
  resetPasswordModalVisible.value = false
  resetPasswordFormRef.value?.resetFields()
}

// 状态切换
const handleStatusChange = async (record, checked) => {
  try {
    record.statusLoading = true
    const newStatus = checked ? 'active' : 'inactive'
    
    const response = await api.employees.update(record.id, {
      status: newStatus
    })

    if (response.success) {
      record.status = newStatus
      message.success('状态更新成功')
    } else {
      message.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    message.error('状态更新失败')
  } finally {
    record.statusLoading = false
  }
}

// 手机号脱敏
const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 生命周期
onMounted(() => {
  fetchEmployees()
})
</script>

<style scoped>
.employee-management-page {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 134px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.search-filter-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.employees-table-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow-x: auto;
}

.employee-name {
  font-weight: 500;
  color: #333;
}

.phone-number {
  color: #666;
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 8px;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

/* 状态标签样式 */
:deep(.ant-tag) {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

/* 操作按钮样式 */
:deep(.ant-btn-link) {
  padding: 4px 8px;
  height: auto;
  line-height: 1.2;
}

/* 分页样式 */
:deep(.ant-pagination) {
  margin-top: 16px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-filter-section .ant-col {
    margin-bottom: 16px;
  }
  
  .search-filter-section .ant-col:last-child {
    margin-bottom: 0;
  }
}
</style>