<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">Lv.{{ lv.level }}</el-tag>
            <template v-if="lv._editing"><el-input v-model="lv.name" style="width:160px" size="small" /></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" 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" style="width:120px" /></el-form-item>
          </el-form>
        </div>
        <div v-if="lv._showPlans" class="plans-section">
          <el-table :data="lv.plans" border size="small">
            <el-table-column label="类型" width="100"><template #default="{row}"><el-tag size="small">{{ {monthly:'月卡',quarterly:'季卡',yearly:'年卡',permanent:'终身卡'}[row.type]||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" 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" 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" /></template></el-table-column>
          </el-table>
          <div style="text-align:right;margin-top:8px"><el-button size="small" type="primary" @click="savePlans(lv)">保存套餐</el-button></div>
        </div>
      </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-row :gutter="12">
        <el-col :span="6"><div class="mcard"><div class="num">{{mStats.total}}</div><div class="lbl">总会员</div></div></el-col>
        <el-col :span="6"><div class="mcard"><div class="num">{{mStats.active}}</div><div class="lbl">有效会员</div></div></el-col>
        <el-col :span="6"><div class="mcard"><div class="num">¥{{mStats.revenue}}</div><div class="lbl">累计营收</div></div></el-col>
        <el-col :span="6"><el-button style="width:100%;height:60px" @click="showMemberList=!showMemberList">{{ showMemberList?'收起':'查看明细' }}</el-button></el-col>
      </el-row>
      <el-table :data="mStats.breakdown" border size="small" style="width:100%;margin-top:12px" v-if="mStats.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>

    <el-card v-if="showMemberList" shadow="never" style="margin-top:16px">
      <div class="section-header"><h3>付费会员列表</h3></div>
      <el-table :data="memberList" border v-loading="mLoad" 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>
    </el-card>

    <el-card shadow="never" style="margin-top:16px">
      <div class="section-header"><h3>用户列表</h3></div>
      <el-table :data="userList" border v-loading="userLoad" style="width:100%">
        <el-table-column label="头像" width="60"><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="100"><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="balance" label="余额" width="100"><template #default="{row}">¥{{ row.balance||0 }}</template></el-table-column>
        <el-table-column prop="created_at" label="注册" width="170" />
        <el-table-column label="操作" width="120"><template #default="{row}"><el-button size="small" @click="editUser(row)">编辑</el-button></template></el-table-column>
      </el-table>
      <div class="pagination-wrap"><el-pagination v-model:page-size="pageSize" v-model:current-page="currentPage" :total="total" layout="total,prev,pager,next" @size-change="fetchUsers" @current-change="fetchUsers" /></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } 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 searchKeyword=ref('');const userList=ref([]);const userLoad=ref(false);const currentPage=ref(1);const pageSize=ref(10);const total=ref(0)
const levelList=ref([]);const showMemberList=ref(false);const memberList=ref([]);const mLoad=ref(false)
const mStats=reactive({total:0,active:0,revenue:0,breakdown:[]})
const editVisible=ref(false);const editLoading=ref(false);const editingUserId=ref(null)
const editForm=reactive({nickname:'',phone:'',level_id:null,total_experience:0,balance:0})

async function fetchUsers(){
  userLoad.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{userLoad.value=false}
}
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):genDefaultPlans(lv)}))}catch{}
}
function genDefaultPlans(lv){const pct=Math.round((1-(lv.discount||1))*100);return[
  {type:'monthly',name:lv.name+'月卡',price:0,original_price:0,give_experience:0,description:lv.name+'月卡',sort:0,level_id:lv.id},
  {type:'quarterly',name:lv.name+'季卡',price:0,original_price:0,give_experience:0,description:lv.name+'季卡',sort:1,level_id:lv.id},
  {type:'yearly',name:lv.name+'年卡',price:0,original_price:0,give_experience:0,description:lv.name+'年卡',sort:2,level_id:lv.id},
  {type:'permanent',name:lv.name+'终身卡',price:0,original_price:0,give_experience:0,description:lv.name+'终身卡',sort:3,level_id:lv.id}]}
function addLevel(){const max=Math.max(...levelList.value.map(l=>l.level||0),0);levelList.value.unshift({id:null,name:'',level:max+1,min_experience:0,discount:1.00,status:1,_editing:true,_showPlans:true,plans:genDefaultPlans({level:max+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{}}
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{}}
function togglePlans(lv){lv._showPlans=!lv._showPlans}
async function savePlans(lv){try{for(const p of lv.plans){if(p.id)await API.put('/plans/'+p.id,p);else await API.post('/plans',p)}ElMessage.success('已保存');fetchLevels()}catch{}}
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{}finally{editLoading.value=false}}
async function fetchMembers(){mLoad.value=true;try{const r=await API.get('/membership/members');memberList.value=r.data.data?.list||[]}catch{}finally{mLoad.value=false}}
async function fetchMemberStats(){try{const r=await API.get('/membership/stats');const d=r.data.data||{};mStats.total=d.total||0;mStats.active=d.active||0;mStats.revenue=d.revenue||0;mStats.breakdown=d.breakdown||[]}catch{}}
onMounted(()=>{fetchUsers();fetchLevels();fetchMemberStats()})
</script>

<style scoped>
.users-page{max-width:1400px}
.action-row{margin-bottom:0}
.section-header h3{font-size:15px;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}
.plans-section{padding:12px 20px;border-top:1px solid #eee}
.pagination-wrap{display:flex;justify-content:flex-end;padding:16px 0 0}
.mcard{text-align:center;padding:12px;background:#f8f9ff;border-radius:8px}
.mcard .num{font-size:22px;font-weight:700;color:#409eff}
.mcard .lbl{font-size:12px;color:#999;margin-top:4px}
</style>
