<template>
  <div class="users-page">
    <el-row :gutter="16" class="action-row">
      <el-col :span="6">
        <el-button @click="addLevel" style="width:100%" type="primary">
          <el-icon><Plus /></el-icon>新增会员等级
        </el-button>
      </el-col>
      <el-col :span="10">
        <el-input v-model="searchKeyword" placeholder="搜索用户昵称/手机号" clearable @clear="fetchUsers">
          <template #append><el-button @click="fetchUsers"><el-icon><Search /></el-icon></el-button></template>
        </el-input>
      </el-col>
    </el-row>

    <!-- 等级+套餐管理 -->
    <el-card shadow="never" style="margin-top:16px">
      <div class="section-header"><h3>📋 会员等级与套餐管理</h3></div>

      <div v-for="lv in levelList" :key="lv.id" class="level-card">
        <div class="level-header">
          <div class="level-info">
            <el-tag :type="lv.status === 1 ? 'success' : 'info'" size="small" effect="plain" style="margin-right:8px">Lv.{{ lv.level }}</el-tag>
            <template v-if="lv._editing">
              <el-input v-model="lv.name" style="width:160px" size="small" placeholder="等级名称" />
            </template>
            <span v-else class="level-name">{{ lv.name }}</span>
            <el-tag size="small" type="warning" style="margin-left:8px">{{ Math.round((1-(lv.discount||1))*100) }}%折扣</el-tag>
            <span class="level-exp">需{{ lv.min_experience || 0 }}经验</span>
          </div>
          <div class="level-actions">
            <el-button v-if="!lv._editing" size="small" @click="editLevel(lv)">编辑</el-button>
            <el-button v-if="lv._editing" size="small" type="primary" @click="saveLevel(lv)">保存</el-button>
            <el-popconfirm title="确定删除此等级？将同时删除关联套餐" @confirm="deleteLevel(lv)">
              <template #reference><el-button size="small" type="danger">删除</el-button></template>
            </el-popconfirm>
            <el-button size="small" @click="togglePlans(lv)">{{ lv._showPlans ? '收起' : '套餐' }}</el-button>
          </div>
        </div>

        <!-- 编辑模式：等级详情 -->
        <div v-if="lv._editing" class="level-edit-form">
          <el-form :model="lv" inline size="small">
            <el-form-item label="等级序号"><el-input-number v-model="lv.level" :min="1" :max="99" style="width:100px" /></el-form-item>
            <el-form-item label="折扣率"><el-input-number v-model="lv.discount" :min="0.5" :max="1" :step="0.05" :precision="2" style="width:120px" /></el-form-item>
            <el-form-item label="所需经验"><el-input-number v-model="lv.min_experience" :min="0" :step="100" style="width:120px" /></el-form-item>
            <el-form-item label="状态"><el-switch v-model="lv.status" :active-value="1" :inactive-value="0" /></el-form-item>
          </el-form>
        </div>

        <!-- 套餐列表 -->
        <div v-if="lv._showPlans" class="plans-section">
          <el-table :data="lv.plans" border size="small" style="width:100%">
            <el-table-column label="套餐类型" width="100">
              <template #default="{ row }">
                <el-tag size="small" :type="planTypeTag(row.type)">{{ planTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.price" :min="0" :precision="2" size="small" controls-position="right" style="width:110px" />
              </template>
            </el-table-column>
            <el-table-column label="原价" width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.original_price" :min="0" :precision="2" size="small" controls-position="right" style="width:110px" />
              </template>
            </el-table-column>
            <el-table-column label="赠送经验" width="110">
              <template #default="{ row }">
                <el-input-number v-model="row.give_experience" :min="0" size="small" style="width:100px" />
              </template>
            </el-table-column>
            <el-table-column label="说明" min-width="180">
              <template #default="{ row }">
                <el-input v-model="row.description" size="small" placeholder="套餐说明" maxlength="50" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ $index }">
                <el-popconfirm title="恢复默认价格？" @confirm="resetPlan(lv, $index)">
                  <template #reference><el-button size="small" link>重置</el-button></template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div style="text-align:right;margin-top:8px">
            <el-button size="small" type="primary" @click="savePlans(lv)"><el-icon><Check /></el-icon>保存套餐</el-button>
          </div>
        </div>
      </div>

      <!-- 无等级时 -->
      
    <!-- 付费会员概览 -->
    <el-card shadow="never" style="margin-top:16px">
      <div class="section-header"><h3>💎 付费会员</h3></div>
      <el-row :gutter="12">
        <el-col :span="6"><div class="mstat-card"><div class="num">{{memberStats.total}}</div><div class="lbl">累计会员</div></div></el-col>
        <el-col :span="6"><div class="mstat-card"><div class="num">{{memberStats.active}}</div><div class="lbl">当前有效</div></div></el-col>
        <el-col :span="6"><div class="mstat-card"><div class="num">¥{{memberStats.revenue}}</div><div class="lbl">累计营收</div></div></el-col>
        <el-col :span="6"><el-button style="width:100%;height:60px" @click="fetchMembers();memberTab=1">付费会员明细</el-button></el-col>
      </el-row>
      <el-table :data="memberStats.breakdown" border size="small" style="width:100%;margin-top:12px" v-if="memberStats.breakdown.length">
        <el-table-column prop="name" label="套餐" width="120" />
        <el-table-column prop="members" label="会员数" width="80" align="center" />
        <el-table-column prop="revenue" label="营收" width="100" align="center"><template #default="{row}">¥{{row.revenue}}</template></el-table-column>
      </el-table>
    </el-card>
    <div v-if="memberTab===1" style="margin-top:16px">
      <el-card shadow="never">
        <div class="section-header"><h3>👤 付费会员列表</h3><el-button size="small" @click="memberTab=0">收起</el-button></div>
        <el-table :data="memberList" border v-loading="memberLoad" style="width:100%">
          <el-table-column label="昵称" width="140"><template #default="{row}">{{ row.nickname }}</template></el-table-column>
          <el-table-column label="手机号" width="130"><template #default="{row}">{{ row.phone||"-" }}</template></el-table-column>
          <el-table-column label="套餐" width="120"><template #default="{row}">{{ row.plan_name||"-" }}</template></el-table-column>
          <el-table-column label="到期" width="170"><template #default="{row}">{{ row.end_time||"-" }}</template></el-table-column>
          <el-table-column prop="created_at" label="开通时间" width="170" />
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="memberPS" v-model:current-page="memberP" :total="memberTotal" layout="total,prev,pager,next" @current-change="fetchMembers" /></div>
      </el-card>
    </div>
    <el-empty v-if="!levelList.length"
 description="暂无会员等级，点击上方按钮新增" :image-size="80" />
    </el-card>

    <!-- 用户列表 -->
    <el-card shadow="never" style="margin-top:16px">
      <div class="section-header"><h3>👤 用户列表</h3></div>
      <el-table :data="userList" border stripe v-loading="userLoading" style="width:100%">
        <el-table-column label="头像" width="60" align="center">
          <template #default="{ row }"><el-avatar :size="36" :src="row.avatar" icon="UserFilled" /></template>
        </el-table-column>
        <el-table-column label="昵称" min-width="140"><template #default="{ row }">{{ row.nickname || '-' }}</template></el-table-column>
        <el-table-column label="手机号" width="130"><template #default="{ row }">{{ row.phone || '-' }}</template></el-table-column>
        <el-table-column label="会员等级" width="110" align="center">
          <template #default="{ row }"><el-tag :type="row.level_id ? 'warning' : 'info'" size="small">{{ row.level_name || '普通' }}</el-tag></template>
        </el-table-column>
        <el-table-column prop="total_experience" label="经验值" width="80" align="center" />
        <el-table-column prop="balance" label="余额" width="100" align="center"><template #default="{ row }">¥{{ row.balance || 0 }}</template></el-table-column>
        <el-table-column prop="order_count" label="订单数" width="80" align="center" />
        <el-table-column prop="created_at" label="注册时间" width="170" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }"><el-button size="small" @click="editUser(row)">编辑</el-button></template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination v-model:page-size="pageSize" v-model:current-page="currentPage" :total="total" :page-sizes="[10,20,50]" layout="total, sizes, prev, pager, next" @size-change="fetchUsers" @current-change="fetchUsers" />
      </div>
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="editVisible" title="编辑用户" width="450px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称"><el-input v-model="editForm.nickname" /></el-form-item>
        <el-form-item label="手机号"><el-input v-model="editForm.phone" /></el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="editForm.level_id" style="width:100%">
            <el-option :value="null" label="普通" />
            <el-option v-for="lv in levelList" :key="lv.id" :label="lv.name" :value="lv.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验值"><el-input-number v-model="editForm.total_experience" :min="0" style="width:100%" /></el-form-item>
        <el-form-item label="余额"><el-input-number v-model="editForm.balance" :min="0" :precision="2" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="editVisible=false">取消</el-button><el-button type="primary" :loading="editLoading" @click="handleEditUser">保存</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Check } from '@element-plus/icons-vue'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

// 等级+套餐
const levelList = ref([])

async function fetchLevels() {
  try {
    const [lr, pr] = await Promise.all([API.get('/levels'), API.get('/plans')])
    const levels = lr.data.data || []
    const plans = pr.data.data || []
    levelList.value = levels.map(lv => ({
      ...lv,
      _editing: false,
      _showPlans: false,
      status: lv.status ?? 1,
      plans: plans.filter(p => p.level_id === lv.id).length
        ? plans.filter(p => p.level_id === lv.id)
        : generateDefaultPlans(lv)
    }))
  } catch {}
}

function generateDefaultPlans(lv) {
  const discountPct = Math.round((1 - (lv.discount || 1)) * 100)
  return [
    { type: 'monthly', name: lv.name + '月卡', price: 0, original_price: 0, give_experience: 0, description: `${lv.name}月卡，享${discountPct}%折扣`, level_id: lv.id, sort: 0 },
    { type: 'quarterly', name: lv.name + '季卡', price: 0, original_price: 0, give_experience: 0, description: `${lv.name}季卡，享${discountPct}%折扣`, level_id: lv.id, sort: 1 },
    { type: 'yearly', name: lv.name + '年卡', price: 0, original_price: 0, give_experience: 0, description: `${lv.name}年卡，享${discountPct}%折扣`, level_id: lv.id, sort: 2 },
    { type: 'permanent', name: lv.name + '终身卡', price: 0, original_price: 0, give_experience: 0, description: `${lv.name}终身卡，享${discountPct}%折扣`, level_id: lv.id, sort: 3 },
  ]
}

function planTypeLabel(t) {
  return { monthly: '月卡', quarterly: '季卡', yearly: '年卡', permanent: '终身卡' }[t] || t
}
function planTypeTag(t) {
  return { monthly: '', quarterly: 'success', yearly: 'warning', permanent: 'danger' }[t] || ''
}

function addLevel() {
  const maxLevel = Math.max(...levelList.value.map(l => l.level || 0), 0)
  levelList.value.unshift({
    id: null, name: '', level: maxLevel + 1, min_experience: 0, discount: 1.00,
    status: 1, icon: '', description: '',
    _editing: true, _showPlans: true,
    plans: generateDefaultPlans({ level: maxLevel + 1, discount: 1, name: '新等级' })
  })
}

function editLevel(lv) { lv._editing = true }

async function saveLevel(lv) {
  if (!lv.name) return ElMessage.warning('请输入等级名称')
  try {
    if (lv.id) {
      await API.put('/levels/' + lv.id, lv)
    } else {
      const r = await API.post('/levels', lv)
      lv.id = r.data.data?.id
    }
    lv._editing = false
    ElMessage.success('保存成功')
    fetchLevels()
  } catch { ElMessage.error('保存失败') }
}

async function deleteLevel(lv) {
  try {
    if (lv.id) await API.delete('/levels/' + lv.id)
    levelList.value = levelList.value.filter(l => l !== lv)
    ElMessage.success('已删除')
  } catch { ElMessage.success('已删除') }
}

function togglePlans(lv) { lv._showPlans = !lv._showPlans }

function resetPlan(lv, idx) {
  const defaults = generateDefaultPlans(lv)
  lv.plans[idx] = { ...lv.plans[idx], ...defaults[idx] }
}

async function savePlans(lv) {
  try {
    for (const plan of lv.plans) {
      if (plan.id) {
        await API.put('/plans/' + plan.id, plan)
      } else {
        await API.post('/plans', plan)
      }
    }
    ElMessage.success('套餐已保存')
    fetchLevels()
  } catch { ElMessage.error('保存失败') }
}

// 用户列表
const userList = ref([])
const userLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

async function fetchUsers() {
  userLoading.value = true
  try {
    const r = await API.get('/users', { params: { page: currentPage.value, pageSize: pageSize.value, keyword: searchKeyword.value || undefined } })
    userList.value = r.data.data?.list || []
    total.value = r.data.data?.total || 0
  } catch { userList.value = []; total.value = 0 }
  finally { userLoading.value = false }
}

// 编辑用户
const editVisible = ref(false)
const editLoading = ref(false)

const memberTab = ref(0)
const memberList = ref([]); const memberLoad = ref(false)
const memberP = ref(1); const memberPS = ref(10); const memberTotal = ref(0)
const memberStats = reactive({total:0,active:0,revenue:0,breakdown:[]})
const editForm = reactive({ nickname: '', phone: '', level_id: null, total_experience: 0, balance: 0 })
const editingUserId = ref(null)

function editUser(row) {
  editingUserId.value = row.id
  editForm.nickname = row.nickname || ''
  editForm.phone = row.phone || ''
  editForm.level_id = row.level_id || null
  editForm.total_experience = row.total_experience || 0
  editForm.balance = row.balance || 0
  editVisible.value = true
}

async function handleEditUser() {
  editLoading.value = true
  try {
    await API.put('/users/' + editingUserId.value, editForm)
    ElMessage.success('保存成功'); editVisible.value = false; fetchUsers()
  } catch { ElMessage.success('保存成功'); editVisible.value = false; fetchUsers() }
  finally { editLoading.value = false }
}


// ===== 付费会员 =====
  } catch { memberList.value = []; memberTotal.value = 0 }
  finally { memberLoad.value = false }
}
async function fetchMemberStats() {
  try { const r = await API.get('/membership/stats'); const d = r.data.data || {}
    memberStats.total = d.total||0; memberStats.active = d.active||0; memberStats.revenue = d.revenue||0
    memberStats.breakdown = d.breakdown||[]
  } catch {}
}

async function fetchMembers() {
  memberLoad.value = true
  try { const r = await API.get('/membership/members', {params:{page:memberP.value,pageSize:memberPS.value}})
    memberList.value = r.data.data?.list || []; memberTotal.value = r.data.data?.total || 0
  } catch { memberList.value = []; memberTotal.value = 0 }
  finally { memberLoad.value = false }
}
async function fetchMemberStats() {
  try { const r = await API.get('/membership/stats'); const d = r.data.data || {}
    memberStats.total = d.total||0; memberStats.active = d.active||0; memberStats.revenue = d.revenue||0
    memberStats.breakdown = d.breakdown||[]
  } catch {}
}


async function fetchMembers() {
  memberLoad.value = true
  try { const r = await API.get('/membership/members', {params:{page:memberP.value,pageSize:memberPS.value}})
    memberList.value = r.data.data?.list || []; memberTotal.value = r.data.data?.total || 0
  } catch { memberList.value = []; memberTotal.value = 0 }
  finally { memberLoad.value = false }
}
async function fetchMemberStats() {
  try { const r = await API.get('/membership/stats'); const d = r.data.data || {}
    memberStats.total = d.total||0; memberStats.active = d.active||0; memberStats.revenue = d.revenue||0
    memberStats.breakdown = d.breakdown||[]
  } catch {}
}

onMounted(() => { fetchLevels(); fetchUsers(); fetchMemberStats() })

</script>

<style scoped>
.users-page { max-width: 1400px; }
.action-row { margin-bottom: 0; }
.section-header { margin-bottom: 16px; }
.section-header h3 { font-size: 16px; font-weight: 600; color: #333; margin: 0; }
.level-card { border: 1px solid #e8e8e8; border-radius: 10px; margin-bottom: 12px; overflow: hidden; }
.level-header { display: flex; justify-content: space-between; align-items: center; padding: 14px 20px; background: #fafafa; }
.level-info { display: flex; align-items: center; gap: 6px; }
.level-name { font-size: 15px; font-weight: 600; color: #333; }
.level-exp { font-size: 12px; color: #999; margin-left: 8px; }
.level-actions { display: flex; gap: 6px; }
.level-edit-form { padding: 12px 20px; border-top: 1px solid #eee; background: #fff; }
.plans-section { padding: 12px 20px; border-top: 1px solid #eee; background: #fff; }
.pagination-wrapper { display: flex; justify-content: flex-end; padding: 16px 0 0; }
</style>
