<template>
  <div class="user-management">
    <a-page-header
      title="用户管理"
      sub-title="管理系统用户信息"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('user:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            新增用户
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总用户数"
            :value="statistics.totalUsers"
            :precision="0"
            suffix="人"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="活跃用户"
            :value="statistics.activeUsers"
            :precision="0"
            suffix="人"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <CheckCircleOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="今日新增"
            :value="statistics.newUsersToday"
            :precision="0"
            suffix="人"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <RiseOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="周增长率"
            :value="statistics.userGrowthRate"
            :precision="2"
            suffix="%"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <RiseOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="关键词">
            <a-input
              v-model:value="searchForm.keyword"
              placeholder="用户名/昵称/手机号"
              allow-clear
            />
          </a-form-item>
          
          <a-form-item label="状态">
            <a-select
              v-model:value="searchForm.status"
              placeholder="全部状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="active">正常</a-select-option>
              <a-select-option value="inactive">禁用</a-select-option>
              <a-select-option value="banned">封禁</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="用户类型">
            <a-select
              v-model:value="searchForm.userType"
              placeholder="全部类型"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="normal">普通用户</a-select-option>
              <a-select-option value="merchant">商家</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.avatar" :size="32" />
          </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 === 'userType'">
            <a-tag :color="getTypeColor(record.userType)">
              {{ getTypeText(record.userType) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'actions'">
            <a-space :size="8">
              <a-button size="small" @click="handleView(record)">
                <EyeOutlined />
                查看
              </a-button>
              
              <a-button 
                v-if="hasPermission('user:write')" 
                size="small" 
                @click="handleEdit(record)"
              >
                <EditOutlined />
                编辑
              </a-button>
              
              <a-dropdown>
                <a-button size="small">
                  更多
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="record.status === 'active' && hasPermission('user:write')"
                      @click="handleDisable(record)"
                    >
                      <StopOutlined />
                      禁用
                    </a-menu-item>
                    <a-menu-item
                      v-if="record.status === 'inactive' && hasPermission('user:write')"
                      @click="handleEnable(record)"
                    >
                      <CheckCircleOutlined />
                      启用
                    </a-menu-item>
                    <a-menu-item
                      v-if="record.status !== 'banned' && hasPermission('user:write')"
                      @click="handleBan(record)"
                    >
                      <LockOutlined />
                      封禁
                    </a-menu-item>
                    <a-menu-item
                      v-if="record.status === 'banned' && hasPermission('user:write')"
                      @click="handleUnban(record)"
                    >
                      <UnlockOutlined />
                      解封
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑用户模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="userFormRef"
        :model="currentUser"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="currentUser.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="currentUser.nickname" placeholder="请输入昵称" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="手机号" name="phone">
              <a-input v-model:value="currentUser.phone" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" name="email">
              <a-input v-model:value="currentUser.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户类型" name="userType">
              <a-select v-model:value="currentUser.userType" placeholder="请选择用户类型">
                <a-select-option value="normal">普通用户</a-select-option>
                <a-select-option value="merchant">商家</a-select-option>
                <a-select-option value="admin">管理员</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="currentUser.status" placeholder="请选择状态">
                <a-select-option value="active">正常</a-select-option>
                <a-select-option value="inactive">禁用</a-select-option>
                <a-select-option value="banned">封禁</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="头像URL" name="avatar">
          <a-input v-model:value="currentUser.avatar" placeholder="请输入头像URL" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  UserOutlined,
  CheckCircleOutlined,
  RiseOutlined,
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  StopOutlined,
  LockOutlined,
  UnlockOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { getUsers, getUser, createUser, updateUser, updateUserStatus } from '@/api/user'
import userAPI from '@/api/user'
import type { User, UserQueryParams } from '@/types/user'

interface SearchForm {
  keyword: string
  status: string
  userType: string
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const loading = ref(false)
const statistics = ref({
  totalUsers: 1234,
  activeUsers: 1120,
  newUsersToday: 25,
  userGrowthRate: 2.5
})

const searchForm = reactive<SearchForm>({
  keyword: '',
  status: '',
  userType: ''
})

const userList = ref<User[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 60,
    align: 'center'
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 120
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    width: 120
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    width: 150
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '用户类型',
    key: 'userType',
    width: 100,
    align: 'center'
  },
  {
    title: '注册时间',
    dataIndex: 'registerTime',
    key: 'registerTime',
    width: 120
  },
  {
    title: '最后登录',
    dataIndex: 'lastLoginTime',
    key: 'lastLoginTime',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center'
  }
]

// 状态映射
const getStatusColor = (status: string) => {
  const colors = {
    active: 'green',
    inactive: 'orange',
    banned: 'red'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    active: '正常',
    inactive: '禁用',
    banned: '封禁'
  }
  return texts[status as keyof typeof texts] || '未知'
}

// 类型映射
const getTypeColor = (type: string) => {
  const colors = {
    normal: 'blue',
    merchant: 'purple',
    admin: 'red'
  }
  return colors[type as keyof typeof colors] || 'default'
}

const getTypeText = (type: string) => {
  const texts = {
    normal: '普通用户',
    merchant: '商家',
    admin: '管理员'
  }
  return texts[type as keyof typeof texts] || '未知'
}

// 添加模态框相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增用户')
const isEditing = ref(false)
const userFormRef = ref<FormInstance>()

// 当前用户数据
const currentUser = ref<Partial<User>>({})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名' }
  ],
  nickname: [
    { required: true, message: '请输入昵称' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '邮箱格式不正确' }
  ],
  userType: [
    { required: true, message: '请选择用户类型' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
}

// 生命周期
onMounted(() => {
  loadUsers()
})

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const params: UserQueryParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status as any,
      userType: searchForm.userType as any
    }
    
    const response = await getUsers(params)
    userList.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    message.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

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

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    userType: ''
  })
  pagination.current = 1
  loadUsers()
}

const handleRefresh = () => {
  loadUsers()
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadUsers()
}

const handleView = async (record: User) => {
  try {
    const response = await getUser(record.id)
    Modal.info({
      title: '用户详情',
      width: 600,
      content: h('div', { class: 'user-detail-modal' }, [
        h('a-descriptions', {
          column: 1,
          bordered: true
        }, [
          h('a-descriptions-item', { label: '用户名' }, response.data.username),
          h('a-descriptions-item', { label: '昵称' }, response.data.nickname),
          h('a-descriptions-item', { label: '手机号' }, response.data.phone),
          h('a-descriptions-item', { label: '邮箱' }, response.data.email),
          h('a-descriptions-item', { label: '状态' }, [
            h('a-tag', { color: getStatusColor(response.data.status) }, getStatusText(response.data.status))
          ]),
          h('a-descriptions-item', { label: '用户类型' }, [
            h('a-tag', { color: getTypeColor(response.data.userType) }, getTypeText(response.data.userType))
          ]),
          h('a-descriptions-item', { label: '注册时间' }, response.data.registerTime),
          h('a-descriptions-item', { label: '最后登录' }, response.data.lastLoginTime)
        ])
      ]),
      okText: '关闭'
    })
  } catch (error) {
    message.error('获取用户详情失败')
  }
}

const handleEdit = async (record: User) => {
  try {
    modalLoading.value = true
    const response = await getUser(record.id)
    modalTitle.value = '编辑用户'
    isEditing.value = true
    currentUser.value = response.data
    modalVisible.value = true
  } catch (error) {
    message.error('获取用户详情失败')
  } finally {
    modalLoading.value = false
  }
}

const showCreateModal = () => {
  modalTitle.value = '新增用户'
  isEditing.value = false
  currentUser.value = {
    status: 'active',
    userType: 'normal'
  }
  modalVisible.value = true
}

const handleModalOk = () => {
  userFormRef.value
    ?.validate()
    .then(() => {
      if (isEditing.value) {
        handleUpdateUser()
      } else {
        handleCreateUser()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

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

const handleCreateUser = async () => {
  try {
    modalLoading.value = true
    await createUser(currentUser.value as any)
    message.success('创建用户成功')
    modalVisible.value = false
    loadUsers()
  } catch (error) {
    message.error('创建用户失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdateUser = async () => {
  try {
    modalLoading.value = true
    await updateUser(currentUser.value.id!, currentUser.value as any)
    message.success('更新用户成功')
    modalVisible.value = false
    loadUsers()
  } catch (error) {
    message.error('更新用户失败')
  } finally {
    modalLoading.value = false
  }
}

const handleDisable = async (record: User) => {
  Modal.confirm({
    title: '确认禁用',
    content: `确定要禁用用户 "${record.username}" 吗？`,
    onOk: async () => {
      try {
        await userAPI.disableUser(record.id)
        message.success('用户已禁用')
        loadUsers()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleEnable = async (record: User) => {
  Modal.confirm({
    title: '确认启用',
    content: `确定要启用用户 "${record.username}" 吗？`,
    onOk: async () => {
      try {
        await userAPI.enableUser(record.id)
        message.success('用户已启用')
        loadUsers()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleBan = async (record: User) => {
  Modal.confirm({
    title: '确认封禁',
    content: `确定要封禁用户 "${record.username}" 吗？`,
    onOk: async () => {
      try {
        await userAPI.banUser(record.id)
        message.success('用户已封禁')
        loadUsers()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleUnban = async (record: User) => {
  Modal.confirm({
    title: '确认解封',
    content: `确定要解封用户 "${record.username}" 吗？`,
    onOk: async () => {
      try {
        await userAPI.unbanUser(record.id)
        message.success('用户已解封')
        loadUsers()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}
</script>

<style scoped lang="less">
.user-management {
  .stats-row {
    margin-bottom: 24px;
  }
  
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>