<template>
  <div class="user-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p>管理系统用户信息和权限</p>
    </div>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-input
              v-model="searchForm.userAccount"
              placeholder="账号"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-input
              v-model="searchForm.userName"
              placeholder="昵称"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-input
              v-model="searchForm.phone"
              placeholder="手机号"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="3">
            <div class="custom-select-wrapper">
              <select 
                v-model="searchForm.userRole" 
                class="custom-select"
                @change="handleSearch"
              >
                <option value="">全部角色</option>
                <option value="user">普通用户</option>
                <option value="admin">管理员</option>
                <option value="superAdmin">超级管理员</option>
              </select>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="custom-select-wrapper">
              <select 
                v-model="searchForm.status" 
                class="custom-select"
                @change="handleSearch"
              >
                <option value="">全部状态</option>
                <option :value="0">正常</option>
                <option :value="1">禁用</option>
              </select>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="custom-select-wrapper">
              <select 
                v-model="searchForm.isVip" 
                class="custom-select"
                @change="handleSearch"
              >
                <option value="">全部会员</option>
                <option :value="1">是</option>
                <option :value="0">否</option>
              </select>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px;">
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="success" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-button @click="refreshList">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="userList"
        v-loading="tableLoading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="userAccount" label="账号" width="120">
          <template #default="{ row }">
            {{ row.userAccount || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="昵称" width="120">
          <template #default="{ row }">
            {{ row.userName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130">
          <template #default="{ row }">
            {{ row.phone || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="userRole" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.userRole)">
              {{ getRoleText(row.userRole) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isVip" label="会员" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isVip === 1 ? 'warning' : 'info'">
              {{ row.isVip === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vipExpire" label="VIP到期" width="120">
          <template #default="{ row }">
            <span v-if="row.vipExpire">{{ formatDate(row.vipExpire) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="showUserDetail(row)">
              详情
            </el-button>
            <el-button type="primary" size="small" @click="editUser(row)">
              编辑
            </el-button>
            <el-button 
              :type="row.status === 0 ? 'warning' : 'success'" 
              size="small" 
              @click="toggleUserStatus(row)"
              :loading="row.statusLoading"
              :disabled="row.statusLoading"
            >
              {{ row.status === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="deleteUser(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="userAccount">
          <el-input v-model="userForm.userAccount" placeholder="请输入账号" />
        </el-form-item>

        <el-form-item label="昵称" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="密码" prop="editPassword">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
          <div class="form-tip" v-if="userForm.id">
            <small>不修改密码请留空</small>
          </div>
        </el-form-item>
        
        <el-form-item label="用户角色" prop="userRole">
          <div class="custom-select-wrapper" style="width: 100%;">
            <select 
              v-model="userForm.userRole" 
              class="custom-select"
            >
              <option value="user">普通用户</option>
              <option value="admin">管理员</option>
              <option value="superAdmin">超级管理员</option>
            </select>
          </div>
        </el-form-item>
        
        <el-form-item label="会员过期时间" prop="vipExpire">
          <input
            v-model="userForm.vipExpire"
            type="date"
            placeholder="选择会员过期时间"
            style="width: 100%; height: 32px; padding: 0 10px; border: 1px solid #dcdfe6; border-radius: 4px; box-sizing: border-box;"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ submitLoading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ currentUserDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="账号">{{ currentUserDetail.userAccount }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentUserDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUserDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="getRoleType(currentUserDetail.userRole)">
            {{ getRoleText(currentUserDetail.userRole) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUserDetail.status === 0 ? 'success' : 'danger'">
            {{ currentUserDetail.status === 0 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="会员状态">
          <el-tag :type="currentUserDetail.isVip === 1 ? 'warning' : 'info'">
            {{ currentUserDetail.isVip === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="套餐类别">
          <el-tag :type="getVipTypeTag(currentUserDetail.vipType)">
            {{ currentUserDetail.vipType || '体验会员' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="VIP到期时间">
          {{ currentUserDetail.vipExpire ? formatDate(currentUserDetail.vipExpire) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="所在省市">
          {{ currentUserDetail.location || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="彩票偏好">
          {{ currentUserDetail.preference || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="获客渠道">
          {{ currentUserDetail.channel || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="注册时间" :span="2">
          {{ formatDate(currentUserDetail.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ formatDate(currentUserDetail.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <div style="margin-top: 20px;">
        <div class="custom-select-wrapper" style="width: 200px; margin-bottom: 10px;">
          <select v-model="selectedLotteryType" class="custom-select">
            <option value="ssq">双色球</option>
            <option value="dlt">大乐透</option>
          </select>
        </div>
        
        <div class="dialog-actions" style="display: flex; justify-content: flex-start; gap: 10px;">
          <el-button type="primary" @click="viewPredictRecords(currentUserDetail)">推测记录</el-button>
          <el-button type="success" @click="viewUsageStats(currentUserDetail)">使用统计</el-button>
          <el-button type="warning" @click="viewPrizeStats(currentUserDetail)">奖金统计</el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用统计弹窗 -->
    <el-dialog
      v-model="usageStatsDialogVisible"
      title="使用统计"
      width="600px"
    >
      <div v-loading="usageStatsLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ usageStats.userId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="彩票类型">
            <el-tag :type="selectedLotteryType === 'ssq' ? 'danger' : 'warning'">
              {{ selectedLotteryType === 'ssq' ? '双色球' : '大乐透' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总推测次数">{{ usageStats.predictCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="待开奖次数">{{ usageStats.pendingCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="已开奖次数">{{ usageStats.drawnCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="命中次数">{{ usageStats.hitCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="命中率" :span="2">
            <el-tag type="success" size="large">{{ formatHitRate(usageStats.hitRate) }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="usageStatsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
      top="360px"
    >
      <div style="text-align:center;">
        <span>确认删除用户 "{{ userToDelete?.userName }}" 吗？此操作不可恢复！</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDeleteUser">取消</el-button>
          <el-button type="danger" @click="confirmDeleteUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { lotteryApi } from '../../api/index.js'
import { userStore } from '../../store/user.js'
import { useRouter } from 'vue-router'

export default {
  name: 'UserList',
  components: {
    Search,
    Refresh,
    Plus,
    Download,
    Edit,
    Delete
  },
  setup() {
    const router = useRouter()
    // 权限检查
    const checkPermission = () => {
      const user = userStore.getUserInfo()
      if (!user || user.userRole !== 'superAdmin') {
        ElMessage({
          type: 'error',
          message: '无权限访问此页面，仅限超级管理员使用'
        })
        // 重定向到控制面板
        setTimeout(() => {
          router.push('/cpzsadmin/dashboard')
        }, 1500)
        return false
      }
      return true
    }

    // 搜索表单
    const searchForm = reactive({
      userAccount: '',
      userName: '',
      phone: '',
      userRole: '',
      status: '',
      isVip: ''
    })

    // 用户列表
    const userList = ref([])
    const tableLoading = ref(false)
    const selectedUsers = ref([])

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 对话框
    const dialogVisible = ref(false)
    const dialogTitle = ref('添加用户')
    const submitLoading = ref(false)
    // 详情对话框
    const detailDialogVisible = ref(false)
    const currentUserDetail = ref({})
    const selectedLotteryType = ref('ssq') // 默认选中双色球
    // 使用统计弹窗
    const usageStatsDialogVisible = ref(false)
    const usageStatsLoading = ref(false)
    const usageStats = ref({
      userId: '',
      predictCount: 0,
      pendingCount: 0,
      hitCount: 0,
      drawnCount: 0,
      hitRate: 0
    })
    // 删除确认弹窗
    const deleteDialogVisible = ref(false)
    const userToDelete = ref(null)

    // 用户表单
    const userFormRef = ref()
    const userForm = reactive({
      id: null,
      userAccount: '',
      userName: '',
      phone: '',
      password: '',
      userRole: 'user', // 设置默认值为普通用户
      vipExpire: null, 
      status: 0
    })

    const userRules = {
      userAccount: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      userName: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      editPassword: [
        { 
          validator: (rule, value, callback) => {
            // 添加用户时，密码必填
            if (!userForm.id && !userForm.password) {
              callback(new Error('请输入密码'))
            } 
            // 编辑用户时，如果填写了密码，则验证长度
            else if (userForm.password && userForm.password.length < 8) {
              callback(new Error('密码长度不小于8位'))
            } 
            else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      userRole: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ]
    }

    // Function to format Date object or ISO string to YYYY-MM-DD string for native input type="date"
    const formatToDateString = (dateInput) => {
      if (!dateInput) return '';
      let date;
      if (dateInput instanceof Date) {
        date = dateInput;
      } else {
        date = new Date(dateInput);
      }

      if (isNaN(date.getTime())) {
        return '';
      }

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    // 加载用户列表
    const loadUserList = async () => {
      try {
        tableLoading.value = true
        const params = {
          page: pagination.current,
          size: pagination.size,
          // 直接将搜索表单对象的每个属性展开，确保参数正确传递
          ...searchForm
        }
        
        // 删除空字符串参数，避免发送不必要的参数
        Object.keys(params).forEach(key => {
          if (params[key] === '') {
            delete params[key]
          }
        })

        console.log('发送请求参数:', params)
        const response = await lotteryApi.getUserList(params)
        console.log('获取用户列表响应:', response)
        
        if (response && response.success) {
          // 数据直接在response.data中，是一个数组
          userList.value = response.data || []
          // 设置总数为数组长度，因为后端没有返回总数
          pagination.total = userList.value.length
        } else {
          ElMessage({
            type: 'error',
            message: response?.message || '获取用户列表失败'
          })
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage({
          type: 'error',
          message: '加载数据失败，请重试'
        })
      } finally {
        tableLoading.value = false
      }
    }

    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1
      loadUserList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        userAccount: '',
        userName: '',
        phone: '',
        userRole: '',
        status: '',
        isVip: ''
      })
      handleSearch()
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      loadUserList()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      loadUserList()
    }

    // 选择处理
    const handleSelectionChange = (selection) => {
      selectedUsers.value = selection
    }

    // 刷新列表
    const refreshList = () => {
      loadUserList()
    }

    // 显示添加对话框
    const showAddDialog = () => {
      dialogTitle.value = '添加用户'
      // 重置表单数据，确保弹窗内容被清空
      resetForm()
      dialogVisible.value = true
    }

    // 显示用户详情
    const showUserDetail = (row) => {
      currentUserDetail.value = { ...row }
      detailDialogVisible.value = true
    }

    // 编辑用户
    const editUser = (row) => {
      dialogTitle.value = '编辑用户'
      Object.assign(userForm, {
        id: row.id,
        userAccount: row.userAccount || '',
        userName: row.userName,
        phone: row.phone || '',
        password: '', // 编辑时密码留空，由用户决定是否修改
        userRole: row.userRole,
        vipExpire: row.vipExpire ? formatToDateString(row.vipExpire) : null, // Convert to YYYY-MM-DD string
        status: row.status
      })
      dialogVisible.value = true
    }

    // 切换用户状态
    const toggleUserStatus = async (row) => {
      console.log('toggleUserStatus called for row:', row)
      try {
        const action = row.status === 0 ? '禁用' : '启用'
        console.log(`Attempting to ${action} user "${row.userName}"`)
        
        // 暂时移除确认对话框以调试
        // await ElMessageBox.confirm(`确认${action}用户 "${row.userName}" 吗？`, '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        // console.log('ElMessageBox.confirm confirmed.')

        // 设置临时状态标记，防止重复点击
        row.statusLoading = true
        
        // 准备请求参数
        const params = {
          id: row.id,
          status: row.status === 0 ? 1 : 0  // 切换状态：0->1 或 1->0
        }
        
        console.log('发送更新用户状态请求:', params)
        const response = await lotteryApi.updateUserStatus(params)
        console.log('更新用户状态响应:', response)
        
        if (response && response.success) {
          // 更新本地状态
          row.status = row.status === 0 ? 1 : 0
          
          ElMessage({
            type: 'success',
            message: `${action}成功`,
            duration: 2000
          })
        } else {
          ElMessage({
            type: 'error',
            message: response?.message || `${action}失败，请重试`
          })
          
          // 如果是未登录或权限错误，可能需要重新登录
          if (response?.code === 40100 || response?.code === 40101) {
            ElMessage.error('登录已过期，请重新登录')
            setTimeout(() => {
              window.location.href = '/cpzsadmin/login'
            }, 1500)
          }
        }
      } catch (error) {
        if (error === 'cancel') { // 这里捕获到的cancel是用户点击取消按钮的情况
          console.log('User canceled the operation.')
        } else {
          console.error('切换用户状态失败:', error)
          const errorMsg = error?.response?.data?.message || '操作失败，请重试'
          ElMessage({
            type: 'error',
            message: errorMsg
          })
          
          // 如果是401错误，可能是登录态过期
          if (error.response && error.response.status === 401) {
            ElMessage.error('登录已过期，请重新登录')
            setTimeout(() => {
              window.location.href = '/cpzsadmin/login'
            }, 1500)
          }
        }
      } finally {
        // 清除临时状态标记
        row.statusLoading = false
        console.log('toggleUserStatus finished.')
      }
    }

    // 删除用户
    const deleteUser = (row) => {
      userToDelete.value = row
      deleteDialogVisible.value = true
    }
    // 确认删除
    const confirmDeleteUser = async () => {
      if (!userToDelete.value) return
      try {
        const response = await lotteryApi.deleteUser(userToDelete.value.id)
        if (response && response.success) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          loadUserList()
        } else {
          ElMessage({
            type: 'error',
            message: response.message || '删除失败，请重试'
          })
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage({
          type: 'error',
          message: '删除失败，请重试'
        })
      } finally {
        deleteDialogVisible.value = false
        userToDelete.value = null
      }
    }
    // 取消删除
    const cancelDeleteUser = () => {
      deleteDialogVisible.value = false
      userToDelete.value = null
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await userFormRef.value.validate()
        submitLoading.value = true

        let payload = { ...userForm }; // Create a copy to avoid modifying original reactive object directly

        // Convert vipExpire string from native date input to ISO string for backend
        if (payload.vipExpire && typeof payload.vipExpire === 'string') {
          try {
            const date = new Date(payload.vipExpire); // Parses "YYYY-MM-DD" string
            payload.vipExpire = date.toISOString(); // Convert to ISO string for backend
          } catch (e) {
            console.error('Error converting vipExpire:', e);
            payload.vipExpire = null; // Set to null if conversion fails
          }
        } else if (payload.vipExpire === '') { // Handle case where input is cleared
          payload.vipExpire = null;
        }

        let response
        if (payload.id) {
          response = await lotteryApi.updateUser(payload)
        } else {
          const { id, ...userData } = payload
          response = await lotteryApi.addUser(userData)
        }
        
        // 检查后端响应的 success 字段
        if (response && response.success) {
          ElMessage({
            type: 'success',
            message: payload.id ? '编辑成功' : '添加成功'
          })
          dialogVisible.value = false // 成功后关闭弹窗
          resetForm()
          loadUserList()
        } else {
          ElMessage({
            type: 'error',
            message: response.message || (payload.id ? '编辑失败' : '添加失败')
          })
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage({
          type: 'error',
          message: '操作失败，请重试'
        })
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(userForm, {
        id: null,
        userAccount: '',
        userName: '',
        phone: '',
        password: '',
        userRole: 'user',
        vipExpire: null,
        status: 0
      })
      userFormRef.value?.resetFields()
    }

    // 角色处理
    const getRoleType = (role) => {
      const types = {
        admin: 'danger',
        superAdmin: 'danger',
        vip: 'warning',
        user: 'info'
      }
      return types[role] || 'info'
    }

    const getRoleText = (role) => {
      const texts = {
        admin: '管理员',
        superAdmin: '超级管理员',
        user: '普通用户'
      }
      return texts[role] || role
    }

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

    onMounted(() => {
      // 检查权限
      if (!checkPermission()) return
      
      loadUserList()
    })

    // 查看推测记录
    const viewPredictRecords = (user) => {
      const path = selectedLotteryType.value === 'dlt' 
        ? '/cpzsadmin/prediction/dlt' 
        : '/cpzsadmin/prediction/ssq'
        
      router.push({
        path: path,
        query: { userId: user.id }
      })
    }

    // 查看使用统计
    const viewUsageStats = async (user) => {
      usageStatsDialogVisible.value = true
      usageStatsLoading.value = true
      
      try {
        let response
        if (selectedLotteryType.value === 'dlt') {
          // 大乐透使用 dlt API
          const dltApi = await import('../../api/dlt/index.js')
          response = await dltApi.dltLotteryApi.getUserPredictStats(user.id)
        } else {
          // 双色球使用主 API
          response = await lotteryApi.getUserPredictStat(user.id, 'ssq')
        }
        
        if (response && response.success) {
          usageStats.value = response.data
        } else {
          ElMessage.error(response?.message || '获取使用统计失败')
        }
      } catch (error) {
        console.error('获取使用统计失败:', error)
        ElMessage.error('获取使用统计失败')
      } finally {
        usageStatsLoading.value = false
      }
    }

    // 查看奖金统计
    const viewPrizeStats = (user) => {
       const path = selectedLotteryType.value === 'dlt'
        ? '/cpzsadmin/prize-statistics/dlt'
        : '/cpzsadmin/prize-statistics/ssq'
        
       router.push({
        path: path,
        query: { userId: user.id }
      })
    }

    // 格式化命中率
    const formatHitRate = (rate) => {
      if (typeof rate !== 'number') return '0.00%'
      return (rate * 100).toFixed(2) + '%'
    }

    // 获取会员类型标签颜色
    const getVipTypeTag = (vipType) => {
      const typeMap = {
        '年度会员': 'warning',
        '月度会员': 'primary',
        '体验会员': 'info'
      }
      return typeMap[vipType] || 'info'
    }

    return {
      searchForm,
      userList,
      tableLoading,
      selectedUsers,
      pagination,
      dialogVisible,
      dialogTitle,
      submitLoading,
      userFormRef,
      userForm,
      userRules,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      refreshList,
      showAddDialog,
      editUser,
      toggleUserStatus,
      deleteUser,
      showUserDetail,
      detailDialogVisible,
      currentUserDetail,
      submitForm,
      resetForm,
      getRoleType,
      getRoleText,
      formatDate,
      deleteDialogVisible,
      userToDelete,
      confirmDeleteUser,
      cancelDeleteUser,
      viewPredictRecords,
      viewUsageStats,
      viewPrizeStats,
      selectedLotteryType,
      usageStatsDialogVisible,
      usageStatsLoading,
      usageStats,
      formatHitRate,
      getVipTypeTag
    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #3a7bd5, #00d2ff);
  padding: 30px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: white;
  margin-bottom: 8px;
  text-align: center;
}

.page-header p {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  margin: 0;
  text-align: center;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 24px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.search-bar {
  padding: 16px 0;
}

/* 列表卡片 */
.list-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 8px;
}

/* 分页 */
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-list {
    padding: 15px;
  }

  .search-bar .el-col {
    margin-bottom: 12px;
  }

  .header-actions {
    flex-direction: column;
    gap: 4px;
  }
}

/* 确保下拉菜单可以正常显示 */
:deep(.el-select__popper) {
  z-index: 3000 !important;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input) {
  width: 100%;
}

:deep(.el-popper) {
  z-index: 3000 !important;
}

/* 自定义下拉框样式 */
.custom-select-wrapper {
  position: relative;
  width: 100%;
}

.custom-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  color: #606266;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23606266'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.custom-select:hover {
  border-color: #c0c4cc;
}

.custom-select:focus {
  outline: none;
  border-color: #409eff;
}

/* 表单提示文字 */
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1;
  margin-top: 4px;
}
</style> 