<template>
  <div class="user-management">
    <a-page-header
      title="用户管理"
      sub-title="管理系统用户和权限"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleExport">
            <download-outlined />
            导出Excel
          </a-button>
          <a-button type="primary" @click="showModal">
            <plus-outlined />
            新增用户
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 搜索区域 -->
    <a-card style="margin-top: 16px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="用户名">
          <a-input
            v-model:value="searchForm.username"
            placeholder="请输入用户名"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">禁用</a-select-option>
            <a-select-option value="suspended">暂停</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <search-outlined />
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            <redo-outlined />
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 用户表格 -->
    <a-card style="margin-top: 16px">
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button
                size="small"
                :type="record.status === 'active' ? 'danger' : 'primary'"
                @click="handleToggleStatus(record)"
              >
                {{ record.status === 'active' ? '禁用' : '启用' }}
              </a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item label="真实姓名" name="real_name">
          <a-input v-model:value="formState.real_name" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-form-item label="角色" name="role_id">
          <a-select v-model:value="formState.role_id" placeholder="请选择角色">
            <a-select-option :value="1">管理员</a-select-option>
            <a-select-option :value="2">保险顾问</a-select-option>
            <a-select-option :value="3">客服人员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status" placeholder="请选择状态">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">禁用</a-select-option>
            <a-select-option value="suspended">暂停</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="!editingId" label="密码" name="password">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

const loading = ref(false)
const modalVisible = ref(false)
const editingId = ref(null)
const userList = ref([])
const formRef = ref()

const searchForm = reactive({
  username: '',
  status: ''
})

const formState = reactive({
  username: '',
  real_name: '',
  email: '',
  phone: '',
  role_id: null,
  status: 'active',
  password: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '真实姓名',
    dataIndex: 'real_name',
    key: 'real_name'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '角色',
    dataIndex: 'role_name',
    key: 'role_name'
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const rules = {
  username: [{ required: true, message: '请输入用户名' }],
  real_name: [{ required: true, message: '请输入真实姓名' }],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '邮箱格式不正确' }
  ],
  phone: [{ required: true, message: '请输入手机号' }],
  role_id: [{ required: true, message: '请选择角色' }],
  password: [{ required: true, message: '请输入密码' }]
}

const modalTitle = computed(() => {
  return editingId.value ? '编辑用户' : '新增用户'
})

const getStatusColor = (status) => {
  const colors = {
    active: 'green',
    inactive: 'red',
    suspended: 'orange'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    active: '活跃',
    inactive: '禁用',
    suspended: '暂停'
  }
  return texts[status] || '未知'
}

const loadUsers = async () => {
  loading.value = true
  try {
    // 构建搜索参数，映射前端字段名到后端期望的字段名
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      // 字段名映射
      search: searchForm.username || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('用户管理API请求参数:', params)
    const response = await userAPI.getList(params)
    console.log('用户管理API响应:', response)
    
    if (response.data && response.data.status === 'success') {
      // 后端返回的数据在data.users字段中
      userList.value = response.data.data.users || []
      pagination.total = response.data.data.pagination?.total || 0
      console.log('用户管理数据设置成功:', userList.value.length, '条')
    } else {
      console.log('用户管理响应格式错误:', response)
      message.error(response.data?.message || '加载用户列表失败')
      userList.value = []
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    message.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUsers()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.status = ''
  handleSearch()
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadUsers()
}

const showModal = () => {
  editingId.value = null
  Object.assign(formState, {
    username: '',
    real_name: '',
    email: '',
    phone: '',
    role_id: null,
    status: 'active',
    password: ''
  })
  modalVisible.value = true
}

const handleEdit = (record) => {
  editingId.value = record.id
  Object.assign(formState, {
    username: record.username,
    real_name: record.real_name,
    email: record.email,
    phone: record.phone,
    role_id: record.role_id,
    status: record.status,
    password: ''
  })
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    
    if (editingId.value) {
      // 编辑用户 - 不包含密码字段
      const updateData = { ...formState }
      delete updateData.password // 编辑时不更新密码
      
      await userAPI.update(editingId.value, updateData)
      message.success('用户更新成功')
    } else {
      // 新增用户
      await userAPI.create(formState)
      message.success('用户创建成功')
    }
    
    modalVisible.value = false
    loadUsers()
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error(editingId.value ? '用户更新失败' : '用户创建失败')
    }
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

const handleToggleStatus = async (record) => {
  try {
    const newStatus = record.status === 'active' ? 'inactive' : 'active'
    await userAPI.update(record.id, { status: newStatus })
    message.success(`用户已${newStatus === 'active' ? '启用' : '禁用'}`)
    loadUsers()
  } catch (error) {
    console.error('状态更新失败:', error)
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('状态更新失败')
    }
  }
}

const handleDelete = async (id) => {
  try {
    await userAPI.delete(id)
    message.success('用户删除成功')
    loadUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('用户删除失败')
    }
  }
}

const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      search: searchForm.username || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await userAPI.export(params)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `用户列表_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

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

<style scoped>
.user-management {
  padding: 0;
}
</style>