<template>
  <div class="user-vip-list-container">
    <h2 class="page-title">VIP用户管理</h2>
    
    <el-card shadow="never" class="table-card">
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <div>
          <el-button 
            type="warning" 
            size="small" 
            :disabled="multipleSelection.length === 0"
            @click="handleBatchRemind"
          >
            批量提醒
          </el-button>
          <span v-if="multipleSelection.length" style="margin-left: 10px; color: #909399;">
            已选 {{ multipleSelection.length }} 条
          </span>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="list"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="isRowSelectable"
        />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="vipLevel" label="VIP等级" width="100">
          <template #default="{ row }">
            <el-tag type="warning" size="small">
              {{ row.vipLevel || row.vip_level || 'VIP' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="vipStartTime" label="开通时间" width="180">
          <template #default="{ row }">
            {{ row.vipStartTime || row.vip_start_time || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="vipEndTime" label="到期时间" width="180">
          <template #default="{ row }">
            {{ row.vipEndTime || row.vip_end_time || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="remainingDays" label="剩余天数" width="100">
          <template #default="{ row }">
            <span :class="{ 'text-danger': (row.remainingDays || row.remaining_days || 0) < 7 }">
              {{ row.remainingDays !== undefined ? row.remainingDays : (row.remaining_days !== undefined ? row.remaining_days : 0) }} 天
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleRenew(row)">续费</el-button>
            <el-button type="warning" size="small" link @click="handleRemind(row)">提醒</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])
const multipleSelection = ref([])

// 仅允许勾选剩余天数 >= 2 天的用户
const isRowSelectable = (row) => {
  const days =
    row.remainingDays !== undefined
      ? row.remainingDays
      : row.remaining_days !== undefined
        ? row.remaining_days
        : 0
  return days >= 2
}

const loadList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.USER_VIP_LIST, {
      params: { page: currentPage.value, pageSize: pageSize.value }
    })
    if (response.code === 200) {
      // 后端返回格式: {list: [], total: xx}
      const dataList = response.data.list || []
      // 兼容处理：统一字段格式为驼峰
      list.value = dataList.map(item => ({
        ...item,
        userId: item.userId || item.user_id,
        nickname: item.nickname,
        vipLevel: item.vipLevel || item.vip_level,
        vipStartTime: item.vipStartTime || item.vip_start_time,
        vipEndTime: item.vipEndTime || item.vip_end_time,
        remainingDays: item.remainingDays !== undefined ? item.remainingDays : (item.remaining_days !== undefined ? item.remaining_days : 0)
      }))
      total.value = response.data.total || 0
      console.log('VIP用户列表数据:', list.value)
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleRenew = (row) => {
  ElMessage.info('续费功能开发中')
}

const handleSelectionChange = (val) => {
  multipleSelection.value = (val || []).filter(isRowSelectable)
}

// 发送系统提醒
const handleRemind = async (row) => {
  const userId = row.userId || row.user_id
  if (!userId) {
    ElMessage.error('缺少用户ID，无法发送提醒')
    return
  }

  const days =
    row.remainingDays !== undefined
      ? row.remainingDays
      : row.remaining_days !== undefined
        ? row.remaining_days
        : 0

  let content = ''
  if (days <= 0) {
    content = '尊敬的用户，您的会员已经到期，请及时充值'
  } else if (days <= 2) {
    content = '尊敬的用户，您的会员不足2天，请及时充值'
  } else {
    ElMessage.info('该用户会员剩余时间大于2天，无需提醒')
    return
  }

  try {
    const res = await request.post(API_ENDPOINTS.USER_VIP_REMIND, {
      userId,
      content
    })
    if (res.code === 200) {
      ElMessage.success('提醒发送成功')
    } else {
      ElMessage.error(res.message || '提醒发送失败')
    }
  } catch (error) {
    console.error('发送提醒失败:', error)
    ElMessage.error('发送提醒失败，请稍后重试')
  }
}

// 批量提醒
const handleBatchRemind = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请先选择需要提醒的用户')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要对选中的 ${multipleSelection.value.length} 位用户发送会员到期提醒吗？`,
      '批量提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  let successCount = 0
  let skipCount = 0
  let failCount = 0

  for (const row of multipleSelection.value) {
    const userId = row.userId || row.user_id
    if (!userId) {
      failCount++
      continue
    }

    const days =
      row.remainingDays !== undefined
        ? row.remainingDays
        : row.remaining_days !== undefined
          ? row.remaining_days
          : 0

    let content = ''
    if (days <= 0) {
      content = '尊敬的用户，您的会员已经到期，请及时充值'
    } else if (days <= 2) {
      content = '尊敬的用户，您的会员不足2天，请及时充值'
    } else {
      skipCount++
      continue
    }

    try {
      const res = await request.post(API_ENDPOINTS.USER_VIP_REMIND, {
        userId,
        content
      })
      if (res.code === 200) {
        successCount++
      } else {
        failCount++
      }
    } catch {
      failCount++
    }
  }

  let msg = `批量提醒完成：成功 ${successCount} 条`
  if (skipCount) msg += `，已跳过（剩余时间>2天）${skipCount} 条`
  if (failCount) msg += `，失败 ${failCount} 条`

  if (failCount) {
    ElMessage.warning(msg)
  } else {
    ElMessage.success(msg)
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.user-vip-list-container { padding: 0; }
.page-title { font-size: 24px; font-weight: bold; color: #333; margin: 0 0 20px 0; }
.table-card { margin-top: 20px; }
.pagination-container { display: flex; justify-content: flex-end; margin-top: 20px; }
.text-danger { color: #f56c6c; font-weight: bold; }
</style>

