<template>
  <div class="tools-page">
    <el-card shadow="never" class="tabs-card">
      <div class="t-tabs">
        <div v-for="t in tabs" :key="t.key" class="t-tab" :class="{active:aT===t.key}" @click="switchTab(t.key)"><span>{{ t.icon }}</span>{{ t.label }}</div>
      </div>
    </el-card>

    <!-- 评价管理 -->
    <div v-show="aT==='reviews'">
      <el-card shadow="never" class="filter-card">
        <el-form inline>
          <el-form-item label="状态"><el-select v-model="rvF.status" placeholder="全部" clearable style="width:130px" @change="fetchReviews"><el-option label="待审核" value="0" /><el-option label="已显示" value="1" /></el-select></el-form-item>
          <el-form-item><el-button type="primary" @click="fetchReviews"><el-icon><Search /></el-icon>搜索</el-button></el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="never">
        <el-table :data="reviewList" border v-loading="rvLoad" style="width:100%">
          <el-table-column label="商品" min-width="180"><template #default="{row}">{{ row.product_name||'商品#'+row.product_id }}</template></el-table-column>
          <el-table-column label="用户" width="120"><template #default="{row}">{{ row.nickname||'用户'+row.user_id }}</template></el-table-column>
          <el-table-column label="评分" width="80" align="center"><template #default="{row}"><el-rate v-model="row.rating" disabled size="small" /></template></el-table-column>
          <el-table-column label="评价内容" min-width="280"><template #default="{row}">{{ row.content||'-' }}</template></el-table-column>
          <el-table-column label="图片" width="100" align="center">
            <template #default="{row}"><el-image v-if="row.images" :src="JSON.parse(row.images||'[]')[0]" style="width:40px;height:40px;border-radius:4px" /><span v-else>-</span></template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small" @change="toggleReview(row)" /></template></el-table-column>
          <el-table-column label="时间" width="150" align="center"><template #default="{row}">{{ row.created_at }}</template></el-table-column>
          <el-table-column label="操作" width="100" align="center"><template #default="{row}"><el-popconfirm title="删除此评价？" @confirm="delReview(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template></el-table-column>
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="rvPS" v-model:current-page="rvP" :total="rvTotal" layout="total,prev,pager,next" @current-change="fetchReviews" /></div>
      </el-card>
    </div>

    <!-- 操作日志 -->
    <div v-show="aT==='oplog'">
      <el-card shadow="never">
        <el-table :data="opList" border v-loading="opLoad" style="width:100%">
          <el-table-column label="操作员" width="120"><template #default="{row}">{{ row.admin_name||'admin' }}</template></el-table-column>
          <el-table-column label="操作类型" width="100" align="center"><template #default="{row}"><el-tag size="small">{{ {add:'添加',update:'更新',delete:'删除',copy:'复制',login:'登录'}[row.action]||row.action }}</el-tag></template></el-table-column>
          <el-table-column label="操作对象" width="100"><template #default="{row}">{{ {product:'商品',order:'订单',user:'用户',category:'类目',setting:'设置'}[row.target]||row.target }}</template></el-table-column>
          <el-table-column label="内容" min-width="300"><template #default="{row}">{{ row.content||row.detail||'-' }}</template></el-table-column>
          <el-table-column label="IP" width="130"><template #default="{row}">{{ row.ip||'-' }}</template></el-table-column>
          <el-table-column prop="created_at" label="操作时间" width="160" align="center" />
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="opPS" v-model:current-page="opP" :total="opTotal" layout="total,prev,pager,next" @current-change="fetchOps" /></div>
      </el-card>
    </div>

    <!-- 系统工具 -->
    <div v-show="aT==='tools'">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-card shadow="never">
            <h4 class="card-title">💾 数据备份</h4>
            <p style="font-size:13px;color:#666;margin:0 0 12px">备份当前数据库到 backup 目录</p>
            <el-button type="primary" :loading="bkLoading" @click="backupDB">立即备份</el-button>
            <el-divider />
            <div v-for="b in backups" :key="b" class="backup-item">
              <span>{{ b }}</span>
              <el-button size="small" link type="primary" @click="restoreDB(b)">还原</el-button>
              <el-popconfirm title="删除此备份？" @confirm="delBackup(b)"><template #reference><el-button size="small" link type="danger">删除</el-button></template></el-popconfirm>
            </div>
            <el-empty v-if="!backups.length" description="暂无备份" :image-size="50" />
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="never">
            <h4 class="card-title">🧹 缓存管理</h4>
            <p style="font-size:13px;color:#666;margin:0 0 12px">清除系统缓存释放空间</p>
            <el-button :loading="cacheLoading" @click="clearCache">清除缓存</el-button>
          </el-card>
          <el-card shadow="never" style="margin-top:12px">
            <h4 class="card-title">🔐 登录日志</h4>
            <el-table :data="loginLogs" border size="small" v-loading="llLoad" style="width:100%" max-height="300">
              <el-table-column label="账号" width="120"><template #default="{row}">{{ row.phone||'-' }}</template></el-table-column>
              <el-table-column label="结果" width="70" align="center"><template #default="{row}"><el-tag :type="row.result==='success'?'success':'danger'" size="small">{{ row.result==='success'?'成功':'失败' }}</el-tag></template></el-table-column>
              <el-table-column label="IP" width="120"><template #default="{row}">{{ row.ip||'-' }}</template></el-table-column>
              <el-table-column prop="created_at" label="时间" width="150" />
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="never">
            <h4 class="card-title">ℹ️ 系统信息</h4>
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="系统版本">LiteMall v1.0.0</el-descriptions-item>
              <el-descriptions-item label="Node.js">{{ sysInfo.node }}</el-descriptions-item>
              <el-descriptions-item label="数据库">{{ sysInfo.db }}</el-descriptions-item>
              <el-descriptions-item label="数据表">{{ sysInfo.tables }} 张</el-descriptions-item>
              <el-descriptions-item label="总数据量">{{ sysInfo.totalRows }} 行</el-descriptions-item>
              <el-descriptions-item label="用户数">{{ sysInfo.users }} 人</el-descriptions-item>
              <el-descriptions-item label="商品数">{{ sysInfo.products }} 个</el-descriptions-item>
              <el-descriptions-item label="订单数">{{ sysInfo.orders }} 单</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 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 tabs = [
  {key:'reviews',icon:'⭐',label:'评价管理'},
  {key:'oplog',icon:'📋',label:'操作日志'},
  {key:'tools',icon:'🔧',label:'系统工具'},
]
const aT=ref('reviews')
function switchTab(k){aT.value=k;if(k==='reviews')fetchReviews();else if(k==='oplog')fetchOps();else if(k==='tools'){fetchBackups();fetchLoginLogs();fetchSysInfo()}}

// ===== 评价管理 =====
const reviewList=ref([]);const rvLoad=ref(false);const rvP=ref(1);const rvPS=ref(10);const rvTotal=ref(0)
const rvF=reactive({status:''})
async function fetchReviews(){
  rvLoad.value=true
  try{const r=await API.get('/reviews/admin',{params:{page:rvP.value,pageSize:rvPS.value,status:rvF.status||undefined}})
    reviewList.value=r.data.data?.list||[];rvTotal.value=r.data.data?.total||0}
  catch{reviewList.value=[];rvTotal.value=0}finally{rvLoad.value=false}
}
async function toggleReview(row){try{await API.put('/reviews/admin/'+row.id,{status:row.status})}catch{}}
async function delReview(id){try{await API.delete('/reviews/admin/'+id);ElMessage.success('已删除');fetchReviews()}catch{}}

// ===== 操作日志 =====
const opList=ref([]);const opLoad=ref(false);const opP=ref(1);const opPS=ref(15);const opTotal=ref(0)
async function fetchOps(){
  opLoad.value=true
  try{const r=await API.get('/operation-logs',{params:{page:opP.value,pageSize:opPS.value}})
    opList.value=r.data.data?.list||[];opTotal.value=r.data.data?.total||0}
  catch{opList.value=[];opTotal.value=0}finally{opLoad.value=false}
}

// ===== 系统工具 =====
const bkLoading=ref(false);const backups=ref([]);const cacheLoading=ref(false)
const loginLogs=ref([]);const llLoad=ref(false)
const sysInfo=ref({node:'',db:'',tables:0,totalRows:0,users:0,products:0,orders:0})

async function fetchBackups(){try{const r=await API.get('/backups');backups.value=r.data.data||[]}catch{}}
async function backupDB(){bkLoading.value=true;try{await API.post('/backup');ElMessage.success('备份成功');fetchBackups()}catch{ElMessage.error('备份失败')}finally{bkLoading.value=false}}
async function restoreDB(n){try{await ElMessageBox.confirm('确认还原 '+n+'？当前数据将被覆盖');await API.post('/backup/restore',{name:n});ElMessage.success('还原成功')}catch{}}
async function delBackup(n){try{await API.delete('/backup/'+encodeURIComponent(n));ElMessage.success('已删除');fetchBackups()}catch{}}
async function clearCache(){cacheLoading.value=true;try{await API.post('/cache/clear');ElMessage.success('缓存已清除')}catch{ElMessage.error('操作失败')}finally{cacheLoading.value=false}}
async function fetchLoginLogs(){llLoad.value=true;try{const r=await API.get('/login-logs',{params:{pageSize:20}});loginLogs.value=r.data.data||[]}catch{}finally{llLoad.value=false}}
async function fetchSysInfo(){try{const r=await API.get('/system-info');sysInfo.value=r.data.data||sysInfo.value}catch{}}

onMounted(()=>{fetchReviews()})
</script>
<style scoped>
.tools-page{max-width:1400px}
.tabs-card{margin-bottom:16px;padding:4px 0}
.t-tabs{display:flex;gap:4px}
.t-tab{display:flex;align-items:center;gap:6px;padding:10px 18px;border-radius:8px;cursor:pointer;font-size:14px;transition:all .2s}
.t-tab:hover{background:#f5f7fa}
.t-tab.active{background:#ecf5ff;color:#409eff;font-weight:600}
.filter-card{margin-bottom:16px}
.pagination-wrap{display:flex;justify-content:flex-end;padding:16px 0 0}
.card-title{font-size:14px;font-weight:600;color:#333;margin:0 0 8px 0}
.backup-item{display:flex;align-items:center;justify-content:space-between;padding:6px 0;font-size:13px;border-bottom:1px solid #f0f0f0}
</style>
