<template>
  <div class="users-page">
    <a-card title="用户管理" size="small">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <PlusOutlined />
            新增用户
          </a-button>
          <a-button @click="handleRefresh">
            <ReloadOutlined />
            刷新
          </a-button>
        </a-space>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="总用户数"
                :value="statistics.totalUsers"
                :value-style="{ color: '#3f8600' }"
              >
                <template #prefix>
                  <UserOutlined />
                </template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="活跃用户"
                :value="statistics.activeUsers"
                :value-style="{ color: '#1890ff' }"
              >
                <template #prefix>
                  <CheckCircleOutlined />
                </template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="今日新增"
                :value="statistics.todayNew"
                :value-style="{ color: '#722ed1' }"
              >
                <template #prefix>
                  <PlusCircleOutlined />
                </template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small">
              <a-statistic
                title="VIP用户"
                :value="statistics.vipUsers"
                :value-style="{ color: '#fa8c16' }"
              >
                <template #prefix>
                  <CrownOutlined />
                </template>
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 高级搜索 -->
      <AdvancedSearch
        search-type="user"
        :status-options="statusOptions"
        @search="handleSearch"
        @reset="handleSearchReset"
      />

      <!-- 批量操作 -->
      <BatchOperations
        :data-source="users"
        :selected-items="selectedUsers"
        operation-type="user"
        :status-options="statusOptions"
        :export-fields="exportFields"
        @selection-change="(items: any[]) => handleSelectionChange(items as User[])"
        @batch-action="(action: string, items: any[], params?: any) => handleBatchAction(action, items as User[], params)"
      />

      <!-- 用户列表 -->
      <a-table
        :columns="columns"
        :data-source="users"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
        row-key="id"
      >
        <!-- 头像列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.avatar" :size="40">
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
          </template>

          <!-- 用户信息列 -->
          <template v-else-if="column.key === 'userInfo'">
            <div class="user-info">
              <div class="user-name">
                {{ record.nickname || record.username }}
                <a-tag v-if="record.user_type === 'vip'" color="gold" size="small">
                  <CrownOutlined />
                  VIP
                </a-tag>
              </div>
              <div class="user-meta">
                <a-typography-text type="secondary" :style="{ fontSize: '12px' }">
                  ID: {{ record.id }} | {{ record.phone || record.email }}
                </a-typography-text>
              </div>
            </div>
          </template>

          <!-- 状态列 -->
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <!-- 注册信息列 -->
          <template v-else-if="column.key === 'registerInfo'">
            <div class="register-info">
              <div>
                <a-tag :color="getSourceColor(record.register_source)" size="small">
                  {{ getSourceText(record.register_source) }}
                </a-tag>
              </div>
              <div class="register-time">
                <a-typography-text type="secondary" :style="{ fontSize: '12px' }">
                  {{ formatDate(record.created_at) }}
                </a-typography-text>
              </div>
            </div>
          </template>

          <!-- 最后登录列 -->
          <template v-else-if="column.key === 'lastLogin'">
            <div v-if="record.last_login_at">
              <div>{{ formatDate(record.last_login_at) }}</div>
              <a-typography-text type="secondary" :style="{ fontSize: '12px' }">
                {{ record.last_login_ip }}
              </a-typography-text>
            </div>
            <a-typography-text v-else type="secondary">
              从未登录
            </a-typography-text>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-dropdown>
                <template #overlay>
                  <a-menu @click="({ key }) => handleMenuAction(key, record)">
                    <a-menu-item key="resetPassword">
                      <KeyOutlined />
                      重置密码
                    </a-menu-item>
                    <a-menu-item key="sendMessage">
                      <MessageOutlined />
                      发送消息
                    </a-menu-item>
                    <a-menu-item 
                      :key="record.status === 'active' ? 'disable' : 'enable'"
                    >
                      <component 
                        :is="record.status === 'active' ? LockOutlined : UnlockOutlined" 
                      />
                      {{ record.status === 'active' ? '禁用' : '启用' }}
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="delete" class="danger-item">
                      <DeleteOutlined />
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link" size="small">
                  更多
                  <DownOutlined />
                </a-button>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 用户详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="用户详情"
      :footer="null"
      width="800px"
    >
      <UserDetail
        v-if="currentUser"
        :user="currentUser"
        @refresh="handleRefresh"
      />
    </a-modal>

    <!-- 用户编辑模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑用户"
      @ok="handleEditSubmit"
      :confirm-loading="editLoading"
    >
      <UserForm
        v-if="currentUser"
        ref="userFormRef"
        :user="currentUser"
        mode="edit"
      />
    </a-modal>

    <!-- 新增用户模态框 -->
    <a-modal
      v-model:open="addModalVisible"
      title="新增用户"
      @ok="handleAddSubmit"
      :confirm-loading="addLoading"
    >
      <UserForm
        ref="addUserFormRef"
        mode="add"
      />
    </a-modal>

    <!-- 发送消息模态框 -->
    <a-modal
      v-model:open="messageModalVisible"
      title="发送消息"
      @ok="handleSendMessage"
      :confirm-loading="messageLoading"
    >
      <a-form :model="messageForm" layout="vertical">
        <a-form-item label="消息标题" required>
          <a-input
            v-model:value="messageForm.title"
            placeholder="请输入消息标题"
            :maxlength="100"
            show-count
          />
        </a-form-item>
        
        <a-form-item label="消息内容" required>
          <a-textarea
            v-model:value="messageForm.content"
            placeholder="请输入消息内容"
            :rows="4"
            :maxlength="500"
            show-count
          />
        </a-form-item>
        
        <a-form-item label="消息类型">
          <a-radio-group v-model:value="messageForm.type">
            <a-radio value="info">通知</a-radio>
            <a-radio value="warning">警告</a-radio>
            <a-radio value="promotion">推广</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { 
  UserOutlined,
  PlusOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  PlusCircleOutlined,
  CrownOutlined,
  KeyOutlined,
  MessageOutlined,
  LockOutlined,
  UnlockOutlined,
  DeleteOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType, TableProps } from 'ant-design-vue'
import AdvancedSearch from '@/components/AdvancedSearch.vue'
import BatchOperations from '@/components/BatchOperations.vue'
import UserDetail from './components/UserDetail.vue'
import UserForm from './components/UserForm.vue'
import userAPI, { type User } from '@/api/user'
// import { formatDate } from '@/utils/date'

interface Statistics {
  totalUsers: number
  activeUsers: number
  newUsersToday: number
  totalRevenue: number
}

// 临时格式化函数，直到utils/date模块可用
const formatDate = (date: string | null | undefined): string => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 响应式数据
const loading = ref(false)
const users = ref<User[]>([])
const selectedUsers = ref<User[]>([])
const currentUser = ref<User | null>(null)

// 统计数据
const statistics = ref<Statistics>({
  totalUsers: 0,
  activeUsers: 0,
  todayNew: 0,
  vipUsers: 0
})

// 模态框状态
const detailModalVisible = ref(false)
const editModalVisible = ref(false)
const addModalVisible = ref(false)
const messageModalVisible = ref(false)

// 加载状态
const editLoading = ref(false)
const addLoading = ref(false)
const messageLoading = ref(false)

// 表单引用
const userFormRef = ref()
const addUserFormRef = ref()

// 消息表单
const messageForm = reactive({
  title: '',
  content: '',
  type: 'info'
})

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

// 搜索参数
const searchParams = ref({})

// 状态选项
const statusOptions = [
  { value: 'active', label: '激活', color: 'green' },
  { value: 'inactive', label: '禁用', color: 'red' },
  { value: 'pending', label: '待审核', color: 'orange' }
]

// 导出字段
const exportFields = [
  { key: 'id', label: 'ID' },
  { key: 'username', label: '用户名' },
  { key: 'nickname', label: '昵称' },
  { key: 'email', label: '邮箱' },
  { key: 'phone', label: '手机号' },
  { key: 'status', label: '状态' },
  { key: 'user_type', label: '用户类型' },
  { key: 'register_source', label: '注册来源' },
  { key: 'created_at', label: '注册时间' },
  { key: 'last_login_at', label: '最后登录' }
]

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '头像',
    key: 'avatar',
    width: 80,
    align: 'center'
  },
  {
    title: '用户信息',
    key: 'userInfo',
    width: 200
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '注册信息',
    key: 'registerInfo',
    width: 150
  },
  {
    title: '最后登录',
    key: 'lastLogin',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right'
  }
]

// 行选择配置
const rowSelection: TableProps['rowSelection'] = {
  selectedRowKeys: computed(() => selectedUsers.value.map(user => user.id)),
  onChange: (selectedRowKeys: (string | number)[], selectedRows: User[]) => {
    selectedUsers.value = selectedRows
  },
  onSelectAll: (selected: boolean, selectedRows: User[], changeRows: User[]) => {
    if (selected) {
      selectedUsers.value = [...selectedUsers.value, ...changeRows]
    } else {
      const changeIds = changeRows.map(row => row.id)
      selectedUsers.value = selectedUsers.value.filter(user => !changeIds.includes(user.id))
    }
  }
}

/**
 * 获取状态颜色
 */
const getStatusColor = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'green',
    inactive: 'red',
    pending: 'orange'
  }
  return statusMap[status] || 'default'
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '激活',
    inactive: '禁用',
    pending: '待审核'
  }
  return statusMap[status] || status
}

/**
 * 获取来源颜色
 */
const getSourceColor = (source: string) => {
  const sourceMap: Record<string, string> = {
    web: 'blue',
    wechat: 'green',
    app: 'purple'
  }
  return sourceMap[source] || 'default'
}

/**
 * 获取来源文本
 */
const getSourceText = (source: string) => {
  const sourceMap: Record<string, string> = {
    web: '网页端',
    wechat: '微信小程序',
    app: '移动应用'
  }
  return sourceMap[source] || source
}

/**
 * 加载用户列表
 */
const loadUsers = async () => {
  loading.value = true
  
  try {
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...searchParams.value
    }
    
    const response = await userAPI.getUsers(params)
    
    users.value = response.data.list
    pagination.value.total = response.data.total
    
    // 更新统计数据
    statistics.value = response.data.statistics || {
      totalUsers: response.data.total,
      activeUsers: response.data.list.filter((u: User) => u.status === 'active').length,
      todayNew: 0,
      vipUsers: response.data.list.filter((u: User) => u.user_type === 'vip').length
    }
  } catch (error) {
    message.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 处理表格变化
 */
const handleTableChange: TableProps['onChange'] = (pag) => {
  if (pag) {
    pagination.value.current = pag.current || 1
    pagination.value.pageSize = pag.pageSize || 20
  }
  loadUsers()
}

/**
 * 处理搜索
 */
const handleSearch = (params: any) => {
  searchParams.value = params
  pagination.value.current = 1
  loadUsers()
}

/**
 * 处理搜索重置
 */
const handleSearchReset = () => {
  searchParams.value = {}
  pagination.value.current = 1
  loadUsers()
}

/**
 * 处理选择变化
 */
const handleSelectionChange = (items: User[]) => {
  selectedUsers.value = items
}

/**
 * 处理批量操作
 */
const handleBatchAction = async (action: string, items: User[], params?: any) => {
  try {
    switch (action) {
      case 'update-status':
        await userAPI.batchUpdateStatus(
          items.map(item => item.id),
          params.status,
          params.reason
        )
        message.success('批量状态更新成功')
        break
      
      case 'delete':
        await userAPI.batchDelete(items.map(item => item.id))
        message.success('批量删除成功')
        break
      
      case 'export':
        await userAPI.exportUsers(items.map(item => item.id), params)
        message.success('导出任务已开始')
        break
      
      case 'send-message':
        // 打开批量发送消息界面
        messageModalVisible.value = true
        break
      
      case 'lock':
        await userAPI.batchUpdateStatus(items.map(item => item.id), 'inactive', '批量锁定')
        message.success('批量锁定成功')
        break
      
      case 'unlock':
        await userAPI.batchUpdateStatus(items.map(item => item.id), 'active', '批量解锁')
        message.success('批量解锁成功')
        break
    }
    
    // 刷新列表
    loadUsers()
    // 清空选择
    selectedUsers.value = []
  } catch (error) {
    message.error('批量操作失败')
  }
}

/**
 * 处理查看
 */
const handleView = (user: User) => {
  currentUser.value = user
  detailModalVisible.value = true
}

/**
 * 处理编辑
 */
const handleEdit = (user: User) => {
  currentUser.value = user
  editModalVisible.value = true
}

/**
 * 处理新增
 */
const handleAdd = () => {
  addModalVisible.value = true
}

/**
 * 处理刷新
 */
const handleRefresh = () => {
  loadUsers()
}

/**
 * 处理菜单操作
 */
const handleMenuAction = async (key: string, user: User) => {
  switch (key) {
    case 'resetPassword':
      Modal.confirm({
        title: '确认重置密码',
        content: `确定要重置用户 ${user.nickname || user.username} 的密码吗？`,
        onOk: async () => {
          try {
            await userAPI.resetPassword(user.id)
            message.success('密码重置成功')
          } catch (error) {
            message.error('密码重置失败')
          }
        }
      })
      break
    
    case 'sendMessage':
      currentUser.value = user
      messageModalVisible.value = true
      break
    
    case 'enable':
    case 'disable':
      const newStatus = key === 'enable' ? 'active' : 'inactive'
      const action = key === 'enable' ? '启用' : '禁用'
      
      Modal.confirm({
        title: `确认${action}用户`,
        content: `确定要${action}用户 ${user.nickname || user.username} 吗？`,
        onOk: async () => {
          try {
            await userAPI.updateStatus(user.id, newStatus)
            message.success(`${action}成功`)
            loadUsers()
          } catch (error) {
            message.error(`${action}失败`)
          }
        }
      })
      break
    
    case 'delete':
      Modal.confirm({
        title: '确认删除用户',
        content: `确定要删除用户 ${user.nickname || user.username} 吗？此操作不可撤销！`,
        okType: 'danger',
        onOk: async () => {
          try {
            await userAPI.deleteUser(user.id)
            message.success('删除成功')
            loadUsers()
          } catch (error) {
            message.error('删除失败')
          }
        }
      })
      break
  }
}

/**
 * 处理编辑提交
 */
const handleEditSubmit = async () => {
  if (!userFormRef.value) return
  
  editLoading.value = true
  
  try {
    const formData = await userFormRef.value.validate()
    await userAPI.updateUser(currentUser.value!.id, formData)
    
    message.success('更新成功')
    editModalVisible.value = false
    loadUsers()
  } catch (error) {
    message.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

/**
 * 处理新增提交
 */
const handleAddSubmit = async () => {
  if (!addUserFormRef.value) return
  
  addLoading.value = true
  
  try {
    const formData = await addUserFormRef.value.validate()
    await userAPI.createUser(formData)
    
    message.success('创建成功')
    addModalVisible.value = false
    loadUsers()
  } catch (error) {
    message.error('创建失败')
  } finally {
    addLoading.value = false
  }
}

/**
 * 处理发送消息
 */
const handleSendMessage = async () => {
  if (!messageForm.title || !messageForm.content) {
    message.error('请填写完整的消息信息')
    return
  }
  
  messageLoading.value = true
  
  try {
    const userIds = currentUser.value 
      ? [currentUser.value.id]
      : selectedUsers.value.map(user => user.id)
    
    await userAPI.sendMessage(userIds, messageForm)
    
    message.success('消息发送成功')
    messageModalVisible.value = false
    
    // 重置表单
    messageForm.title = ''
    messageForm.content = ''
    messageForm.type = 'info'
  } catch (error) {
    message.error('消息发送失败')
  } finally {
    messageLoading.value = false
  }
}

// 初始化
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.users-page {
  padding: 16px;
}

.stats-cards {
  margin-bottom: 16px;
}

.user-info {
  .user-name {
    font-weight: 500;
    margin-bottom: 4px;
  }
  
  .user-meta {
    font-size: 12px;
    color: #666;
  }
}

.register-info {
  .register-time {
    margin-top: 4px;
  }
}

:deep(.danger-item) {
  color: #ff4d4f !important;
}

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

@media (max-width: 768px) {
  .users-page {
    padding: 8px;
  }
  
  .stats-cards :deep(.ant-col) {
    margin-bottom: 8px;
  }
}
</style>