<template>
  <div>
    <div class="page-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>用户管理</h1>
      <a-space class="page-actions">
        <a-button @click="exportUsers" :loading="exportLoading">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          添加用户
        </a-button>
      </a-space>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-area" style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
      <a-input
        v-model="searchUsername"
        placeholder="请输入用户名进行搜索"
        class="search-input"
        style="width: 300px;"
        @input="handleSearchInput"
        @focus="handleSearchFocus"
        @blur="handleSearchBlur"
        @change="handleSearchChange"
        @press-enter="searchUsers"
      />
      <div class="search-buttons">
        <a-button type="primary" @click="searchUsers" :loading="searchLoading">
          <template #icon><SearchOutlined /></template>
          查询
        </a-button>
        <a-button @click="resetSearch" :disabled="!isSearching">
          重置
        </a-button>
        
      </div>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="users" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'roles'">
          <a-tag :color="getRoleColor(record.roleName || record.role?.name)">
            {{ getRoleDisplayName(record.roleName || record.role?.name) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editUser(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个用户吗？"
            @confirm="deleteUser(record.id)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑用户模态框 -->
    <a-modal
      :open="modalVisible"
      @update:open="(val) => modalVisible = val"
      :title="isEdit ? '编辑用户' : '添加用户'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model="formData.username" placeholder="请输入用户名" :disabled="isEdit" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model="formData.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="密码" name="password" v-if="!isEdit">
          <a-input-password v-model="formData.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item label="角色" name="roles">
          <a-select v-model="formData.roles" placeholder="请选择角色" :loading="rolesLoading">
            <a-select-option 
              v-for="role in availableRoles" 
              :key="role.id" 
              :value="role.id"
            >
              {{ role.description || role.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const users = ref([])
const loading = ref(false)
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索相关的响应式数据
const searchUsername = ref('')
const searchLoading = ref(false)
const isSearching = ref(false)
const usernameOptions = ref([])

// 搜索监听相关
let searchTimeout = null
let searchFocusTime = null

// 导出相关
const exportLoading = ref(false)

// 角色相关
const availableRoles = ref([])
const rolesLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  username: '',
  email: '',
  password: '',
  roles: 2 // 默认为普通用户ID
})

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roles: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '角色',
    dataIndex: 'roles',
    key: 'roles',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取角色颜色
const getRoleColor = (roleName) => {
  const colorMap = {
    'admin': 'red',
    'farm_manager': 'green',
    'inspector': 'orange',
    'user': 'blue'
  }
  return colorMap[roleName] || 'default'
}

// 获取角色显示名称
const getRoleDisplayName = (roleName) => {
  const role = availableRoles.value.find(r => r.name === roleName)
  if (role) {
    return role.description || role.name
  }
  
  // 如果没有找到角色，使用默认映射
  const nameMap = {
    'admin': '系统管理员',
    'farm_manager': '养殖场管理员',
    'inspector': '监管人员',
    'user': '普通用户'
  }
  return nameMap[roleName] || roleName || '未知角色'
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    rolesLoading.value = true
    console.log('开始获取角色列表...')
    
    const { api } = await import('../utils/api')
    const response = await api.get('/auth/roles')
    
    console.log('角色API响应:', response)
    
    // 处理API响应格式
    // api.get() 已经处理了响应格式，直接返回 result.data
    let roles = []
    if (Array.isArray(response)) {
      // 直接是角色数组
      roles = response
    } else if (response && Array.isArray(response.data)) {
      roles = response.data
    } else if (response && Array.isArray(response.roles)) {
      roles = response.roles
    } else {
      console.warn('API返回角色数据格式异常:', response)
      // 如果是对象，尝试提取角色数据
      if (response && typeof response === 'object') {
        // 可能的字段名
        const possibleFields = ['data', 'roles', 'items', 'list']
        for (const field of possibleFields) {
          if (response[field] && Array.isArray(response[field])) {
            roles = response[field]
            break
          }
        }
      }
    }
    
    console.log('处理后的角色列表:', roles)
    
    if (roles.length > 0) {
      availableRoles.value = roles
      console.log('✅ 角色列表加载成功，数量:', roles.length)
    } else {
      throw new Error('角色列表为空')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    message.error('获取角色列表失败，使用默认角色')
    
    // 如果API失败，使用默认角色
    availableRoles.value = [
      { id: 1, name: 'admin', description: '系统管理员' },
      { id: 2, name: 'user', description: '普通用户' },
      { id: 32, name: 'farm_manager', description: '养殖场管理员' },
      { id: 33, name: 'inspector', description: '监管人员' }
    ]
    console.log('使用默认角色列表')
  } finally {
    rolesLoading.value = false
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const { api } = await import('../utils/api')
    const response = await api.get('/users')
    console.log('用户API响应:', response)
    
    // 检查响应格式
    if (response && response.success && Array.isArray(response.data)) {
      users.value = response.data
    } else if (Array.isArray(response)) {
      // 兼容旧格式
      users.value = response
    } else {
      users.value = []
      console.warn('API返回数据格式异常:', response)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
    users.value = []
  } finally {
    loading.value = false
  }
}

// 导出用户数据
const exportUsers = async () => {
  try {
    if (!users.value || users.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    exportLoading.value = true
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportUserData(users.value)
    
    if (result.success) {
      message.destroy()
      message.success(`导出成功！文件：${result.filename}`)
    } else {
      message.destroy()
      message.error(result.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 显示添加模态框
const showAddModal = async () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
  // 确保角色数据已加载
  if (availableRoles.value.length === 0) {
    await fetchRoles()
  }
}

// 编辑用户
const editUser = async (record) => {
  isEdit.value = true
  Object.assign(formData, {
    ...record,
    password: '' // 编辑时不显示密码
  })
  modalVisible.value = true
  // 确保角色数据已加载
  if (availableRoles.value.length === 0) {
    await fetchRoles()
  }
}

// 删除用户
const deleteUser = async (id) => {
  try {
    const { api } = await import('../utils/api')
    await api.delete(`/users/${id}`)
    message.success('删除成功')
    fetchUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = { ...formData }
    if (isEdit.value && !submitData.password) {
      delete submitData.password // 编辑时如果密码为空则不更新密码
    }
    
    const { api } = await import('../utils/api')
    if (isEdit.value) {
      await api.put(`/users/${formData.id}`, submitData)
      message.success('更新成功')
    } else {
      await api.post('/users', submitData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    username: '',
    email: '',
    password: '',
    roles: 2 // 默认为普通用户ID
  })
  formRef.value?.resetFields()
}

// 搜索用户
const searchUsers = async () => {
  const searchKeywordValue = searchUsername.value
  const searchStartTime = Date.now()
  
  console.log('🔍 [用户搜索监听] 开始搜索:', {
    keyword: searchKeywordValue,
    keywordType: typeof searchKeywordValue,
    keywordLength: searchKeywordValue ? searchKeywordValue.length : 0,
    keywordTrimmed: searchKeywordValue ? searchKeywordValue.trim() : '',
    timestamp: new Date().toISOString(),
    searchStartTime: searchStartTime
  })
  
  // 记录搜索开始日志
  await logUserAction('search_start', {
    keyword: searchKeywordValue,
    searchMethod: 'fetch_direct',
    timestamp: new Date().toISOString()
  })
  
  if (!searchKeywordValue || searchKeywordValue.trim() === '') {
    console.log('🔄 [用户搜索监听] 搜索关键词为空，重新加载所有数据', {
      searchKeywordValue: searchKeywordValue,
      isFalsy: !searchKeywordValue,
      isEmpty: searchKeywordValue === '',
      isWhitespace: searchKeywordValue && searchKeywordValue.trim() === ''
    })
    await fetchUsers()
    return
  }
  
  try {
    console.log('🔄 [用户搜索监听] 发送搜索请求到后端:', searchKeywordValue)
    searchLoading.value = true
    
    const searchUrl = `/users/search?username=${encodeURIComponent(searchKeywordValue.trim())}`
    console.log('🌐 [用户搜索监听] 请求URL:', searchUrl)
    
    // 获取认证token
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    const token = userInfo.token || localStorage.getItem('token')
    
    console.log('🔐 [用户搜索监听] 认证信息:', {
      hasUserInfo: !!userInfo,
      hasToken: !!token,
      tokenLength: token ? token.length : 0,
      tokenPreview: token ? token.substring(0, 20) + '...' : 'none'
    })
    
    if (!token) {
      console.error('❌ [用户搜索监听] 未找到认证token')
      message.error('未找到认证token，请重新登录')
      throw new Error('未找到认证token，请重新登录')
    }
    
    // 检查token是否过期（简单检查）
    try {
      const tokenPayload = JSON.parse(atob(token.split('.')[1]))
      const currentTime = Math.floor(Date.now() / 1000)
      if (tokenPayload.exp && tokenPayload.exp < currentTime) {
        console.error('❌ [用户搜索监听] Token已过期')
        message.error('登录已过期，请重新登录')
        throw new Error('Token已过期，请重新登录')
      }
    } catch (e) {
      console.warn('⚠️ [用户搜索监听] Token解析失败:', e.message)
    }
    
    // 使用API工具查询后端API
    const result = await api.get(searchUrl)
    
    const responseTime = Date.now() - searchStartTime
    console.log('⏱️ [用户搜索监听] 后端响应时间:', responseTime + 'ms')
    console.log('📊 [用户搜索监听] 后端返回数据:', {
      success: result.success,
      dataCount: result.data ? result.data.length : 0,
      message: result.message
    })
    
    if (result.success) {
      users.value = result.data
      isSearching.value = true
      
      console.log(`✅ [用户搜索监听] 搜索成功，找到 ${users.value.length} 条记录`)
      message.success(`搜索完成，找到 ${users.value.length} 个用户`)
      
      // 记录搜索成功日志
      await logUserAction('search_success', {
        keyword: searchKeywordValue,
        resultCount: users.value.length,
        searchMethod: 'fetch_direct',
        responseTime: responseTime,
        backendData: result.data
      })
    } else {
      throw new Error(result.message || '搜索失败')
    }
  } catch (error) {
    const errorTime = Date.now() - searchStartTime
    console.error('❌ [用户搜索监听] 搜索失败:', {
      error: error.message,
      keyword: searchKeywordValue,
      errorTime: errorTime
    })
    message.error('搜索失败: ' + (error.message || '网络错误'))
    
    // 记录搜索失败日志
    await logUserAction('search_failed', {
      keyword: searchKeywordValue,
      error: error.message,
      errorTime: errorTime,
      searchMethod: 'fetch_direct'
    })
  } finally {
    searchLoading.value = false
    const totalTime = Date.now() - searchStartTime
    console.log('⏱️ [用户搜索监听] 搜索总耗时:', totalTime + 'ms')
  }
}

// 监听searchUsername变化
watch(searchUsername, (newValue, oldValue) => {
  console.log('👀 [用户搜索监听] searchUsername变化:', {
    oldValue: oldValue,
    newValue: newValue,
    timestamp: new Date().toISOString(),
    type: typeof newValue,
    length: newValue ? newValue.length : 0
  })
}, { immediate: true })

// 输入框获得焦点
const handleSearchFocus = async (e) => {
  searchFocusTime = Date.now()
  console.log('🎯 [用户搜索监听] 搜索框获得焦点:', {
    timestamp: new Date().toISOString(),
    currentValue: searchUsername.value,
    eventValue: e.target.value,
    focusTime: searchFocusTime,
    valuesMatch: searchUsername.value === e.target.value
  })
  
  await logUserAction('search_focus', {
    field: 'searchUsername',
    currentValue: searchUsername.value,
    eventValue: e.target.value,
    timestamp: new Date().toISOString()
  })
}

// 输入框失去焦点
const handleSearchBlur = async (e) => {
  const blurTime = Date.now()
  const focusDuration = searchFocusTime ? blurTime - searchFocusTime : 0
  
  console.log('👋 [用户搜索监听] 搜索框失去焦点:', {
    timestamp: new Date().toISOString(),
    finalValue: searchUsername.value,
    focusDuration: focusDuration + 'ms',
    blurTime: blurTime
  })
  
  await logUserAction('search_blur', {
    field: 'searchUsername',
    finalValue: searchUsername.value,
    focusDuration: focusDuration,
    timestamp: new Date().toISOString()
  })
  
  searchFocusTime = null
}

// 输入框值改变（与input不同，change在失焦时触发）
const handleSearchChange = async (e) => {
  const value = e.target.value
  console.log('🔄 [用户搜索监听] 搜索框值改变:', {
    newValue: value,
    timestamp: new Date().toISOString(),
    eventType: 'change'
  })
  
  await logUserAction('search_change', {
    field: 'searchUsername',
    newValue: value,
    eventType: 'change',
    timestamp: new Date().toISOString()
  })
}

// 实时搜索输入处理
const handleSearchInput = async (e) => {
  const value = e.target.value
  const oldValue = searchUsername.value
  
  // 更新searchUsername的值
  searchUsername.value = value
  
  console.log('🔍 [用户搜索监听] 搜索输入变化:', {
    oldValue: oldValue,
    newValue: value,
    timestamp: new Date().toISOString(),
    inputLength: value ? value.length : 0,
    searchUsernameValue: searchUsername.value
  })
  
  // 记录输入变化日志
  await logUserAction('search_input_change', {
    field: 'searchUsername',
    oldValue: oldValue,
    newValue: value,
    inputLength: value ? value.length : 0,
    isEmpty: !value || value.trim() === ''
  })
  
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
    console.log('⏰ [用户搜索监听] 清除之前的搜索定时器')
  }
  
  // 如果输入为空，立即重新加载所有数据
  if (!value || value.trim() === '') {
    console.log('🔄 [用户搜索监听] 输入为空，重新加载所有数据')
    await fetchUsers()
    return
  }
  
  // 延迟500ms执行搜索，避免频繁请求
  searchTimeout = setTimeout(async () => {
    console.log('⏰ [用户搜索监听] 延迟搜索触发，关键词:', value, 'searchUsername.value:', searchUsername.value)
    await searchUsers()
  }, 500)
}

// 更新用户名选项（在数据加载后）
const updateUsernameOptions = () => {
  usernameOptions.value = users.value.map(user => ({
    value: user.username,
    label: user.username
  }))
}

// 重置搜索
const resetSearch = () => {
  searchUsername.value = ''
  isSearching.value = false
  usernameOptions.value = []
  fetchUsers() // 重新加载全部用户
}

// 调试搜索关键词
const debugSearchKeyword = () => {
  console.log('🐛 [用户搜索调试] 搜索关键词调试信息:', {
    searchUsername: searchUsername.value,
    searchUsernameType: typeof searchUsername.value,
    searchUsernameLength: searchUsername.value ? searchUsername.value.length : 0,
    searchUsernameTrimmed: searchUsername.value ? searchUsername.value.trim() : '',
    searchUsernameIsEmpty: !searchUsername.value,
    searchUsernameIsWhitespace: searchUsername.value && searchUsername.value.trim() === '',
    timestamp: new Date().toISOString()
  })
  
  message.info(`搜索关键词: "${searchUsername.value}" (长度: ${searchUsername.value ? searchUsername.value.length : 0})`)
}

// 用户操作日志记录
const logUserAction = async (action, data = {}) => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    
    const logData = {
      module: 'user-management',
      action: action,
      timestamp: new Date().toISOString(),
      userId: userInfo.id || null,
      username: userInfo.username || 'anonymous',
      ...data
    }
    
    console.log('📝 [用户操作日志]', action, {
      time: new Date().toLocaleString(),
      user: userInfo.username || 'anonymous',
      action: action,
      data: logData
    })
    
    // 发送到后端记录
    const { api } = await import('../utils/api')
    await api.formLogs.add({
      action: action,
      module: 'user-management',
      userId: userInfo.id || null,
      formData: JSON.stringify(logData),
      oldValues: null,
      newValues: JSON.stringify(data),
      success: true,
      errorMessage: null
    })
  } catch (error) {
    console.error('❌ 记录用户操作日志失败:', error)
  }
}



// 组件挂载时获取数据
onMounted(async () => {
  // 并行获取用户列表和角色列表
  await Promise.all([
    fetchUsers().then(() => {
      updateUsernameOptions()
    }),
    fetchRoles()
  ])
})
</script>