<template>
  <div class="cat-page">
    <el-row :gutter="16">
      <!-- 左侧树 -->
      <el-col :span="8">
        <el-card shadow="never">
          <div class="card-header"><h3>📂 类目结构</h3><el-button size="small" type="primary" @click="addTopCat"><el-icon><Plus /></el-icon>顶级类目</el-button></div>
          <div class="tree-area" v-loading="treeLoad">
            <div v-for="(cat, i) in treeData" :key="cat.id" class="tree-node">
              <div class="node-row" :class="{selected:selected?.id===cat.id}" @click="selectCat(cat)">
                <span class="node-icon">{{ cat.icon||'📁' }}</span>
                <span class="node-name">{{ cat.name }}</span>
                <span class="node-count">({{ cat.product_count||0 }})</span>
                <span class="node-actions" @click.stop>
                  <el-button size="small" link @click="addChild(cat)"><el-icon><Plus /></el-icon></el-button>
                  <el-button size="small" link @click="editCat(cat)"><el-icon><Edit /></el-icon></el-button>
                  <el-popconfirm title="删除此分类？子类将上移" @confirm="delCat(cat)">
                    <template #reference><el-button size="small" link type="danger"><el-icon><Delete /></el-icon></el-button></template>
                  </el-popconfirm>
                </span>
              </div>
              <!-- 子类 -->
              <div v-for="child in cat.children" :key="child.id" class="tree-node child">
                <div class="node-row" :class="{selected:selected?.id===child.id}" @click="selectCat(child)">
                  <span class="node-icon">{{ child.icon||'📄' }}</span>
                  <span class="node-name">{{ child.name }}</span>
                  <span class="node-count">({{ child.product_count||0 }})</span>
                  <span class="node-actions" @click.stop>
                    <el-button size="small" link @click="editCat(child)"><el-icon><Edit /></el-icon></el-button>
                    <el-popconfirm title="删除？" @confirm="delCat(child)">
                      <template #reference><el-button size="small" link type="danger"><el-icon><Delete /></el-icon></el-button></template>
                    </el-popconfirm>
                  </span>
                </div>
              </div>
            </div>
            <el-empty v-if="!treeData.length" description="暂无分类" />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧编辑 -->
      <el-col :span="16">
        <el-card shadow="never">
          <div class="card-header">
            <h3>{{ editing ? '编辑类目' : (selected ? '当前选择: '+selected.name : '请选择类目') }}</h3>
          </div>
          <el-form v-if="editing" :model="form" label-width="100px" class="cat-form">
            <el-form-item label="类目名称" required><el-input v-model="form.name" maxlength="20" show-word-limit /></el-form-item>
            <el-form-item label="父级类目">
              <el-select v-model="form.pid" placeholder="顶级类目" clearable style="width:300px">
                <el-option label="顶级类目（无父级）" :value="0" />
                <el-option v-for="c in topLevelCats" :key="c.id" :disabled="c.id===form.id" :label="c.name" :value="c.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="图标"><el-input v-model="form.icon" placeholder="如: 💡🛋️🔧" maxlength="10" style="width:200px" /></el-form-item>
            <el-form-item label="封面图">
              <el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>form.image=r.data.url">
                <el-image v-if="form.image" :src="form.image" style="width:80px;height:80px;border-radius:6px" />
                <el-button v-else size="small">上传图片</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="排序"><el-input-number v-model="form.sort" :min="0" style="width:200px" /></el-form-item>
            <el-form-item label="状态"><el-switch v-model="form.status" :active-value="1" :inactive-value="0" /></el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveCat">{{ form.id ? '更新' : '添加' }}</el-button>
              <el-button @click="editing=false;form={name:'',pid:0,icon:'',image:'',sort:0,status:1}">取消</el-button>
            </el-form-item>
          </el-form>
          <el-empty v-else-if="!selected" description="从左侧选择一个类目进行编辑" :image-size="80" />
          <div v-else class="cat-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="ID">{{ selected.id }}</el-descriptions-item>
              <el-descriptions-item label="类目名">{{ selected.name }}</el-descriptions-item>
              <el-descriptions-item label="父级">{{ selected.parent_name||'顶级' }}</el-descriptions-item>
              <el-descriptions-item label="排序">{{ selected.sort||0 }}</el-descriptions-item>
              <el-descriptions-item label="状态"><el-tag :type="selected.status===1?'success':'info'" size="small">{{ selected.status===1?'启用':'停用' }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="商品数">{{ selected.product_count||0 }}</el-descriptions-item>
              <el-descriptions-item label="图标">{{ selected.icon||'-' }}</el-descriptions-item>
              <el-descriptions-item label="封面图">
                <el-image v-if="selected.image" :src="selected.image" style="width:60px;height:60px;border-radius:4px" />
                <span v-else>-</span>
              </el-descriptions-item>
            </el-descriptions>
            <el-button type="primary" style="margin-top:12px" @click="editCat(selected)"><el-icon><Edit /></el-icon>编辑此分类</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } 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 uploadUrl='/api/admin/upload/image'
const uh={Authorization:'Bearer '+localStorage.getItem('admin_token')}

const catList=ref([]); const treeLoad=ref(false); const selected=ref(null); const editing=ref(false)
const form=reactive({id:null,name:'',pid:0,icon:'',image:'',sort:0,status:1})

const treeData = computed(()=>{
  const parents = catList.value.filter(c=>!c.pid||c.pid===0)
  const children = catList.value.filter(c=>c.pid&&c.pid>0)
  return parents.map(p=>({...p,children:children.filter(c=>c.pid===p.id)}))
})
const topLevelCats = computed(()=>catList.value.filter(c=>!c.pid||c.pid===0))

async function fetchCats(){
  treeLoad.value=true
  try{
    const r=await API.get('/categories')
    catList.value=(r.data.data||[]).map(c=>({...c}))
  }catch{catList.value=[]}
  finally{treeLoad.value=false}
}

function selectCat(cat){selected.value=cat;editing.value=false}
function addTopCat(){form.id=null;form.name='';form.pid=0;form.icon='';form.image='';form.sort=0;form.status=1;editing.value=true;selected.value=null}
function addChild(cat){form.id=null;form.name='';form.pid=cat.id;form.icon='';form.image='';form.sort=0;form.status=1;editing.value=true;selected.value=cat}
function editCat(cat){form.id=cat.id;form.name=cat.name;form.pid=cat.pid||0;form.icon=cat.icon||'';form.image=cat.image||'';form.sort=cat.sort||0;form.status=cat.status??1;editing.value=true;selected.value=cat}

async function saveCat(){
  if(!form.name)return ElMessage.warning('请输入类目名称')
  try{
    if(form.id) await API.put('/categories/'+form.id,{name:form.name,pid:form.pid,icon:form.icon,image:form.image,sort:form.sort,status:form.status})
    else await API.post('/categories',{name:form.name,pid:form.pid,icon:form.icon,image:form.image,sort:form.sort})
    ElMessage.success(form.id?'更新成功':'添加成功');editing.value=false;fetchCats()
  }catch{ElMessage.error('操作失败')}
}

async function delCat(cat){
  try{
    await API.delete('/categories/'+cat.id)
    if(selected.value?.id===cat.id){selected.value=null;editing.value=false}
    ElMessage.success('已删除');fetchCats()
  }catch{ElMessage.error('删除失败')}
}

onMounted(()=>{fetchCats()})
</script>

<style scoped>
.cat-page{max-width:1200px;margin:0 auto}
.card-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}
.card-header h3{font-size:15px;font-weight:600;color:#333;margin:0}
.tree-area{min-height:400px;max-height:600px;overflow-y:auto}
.tree-node{margin-bottom:0}
.node-row{display:flex;align-items:center;gap:6px;padding:8px 10px;border-radius:6px;cursor:pointer;transition:all .15s}
.node-row:hover{background:#f0f5ff}
.node-row.selected{background:#e6f0ff;border:1px solid #409eff}
.node-row.child{padding-left:36px}
.node-icon{font-size:18px;width:24px;text-align:center}
.node-name{font-size:13px;font-weight:500;flex:1}
.node-count{font-size:11px;color:#999}
.node-actions{display:none;gap:2px}
.node-row:hover .node-actions{display:flex}
.cat-form{max-width:500px}
.cat-info{max-width:500px}
</style>
