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

    <!-- 品牌管理 -->
    <div v-show="aT==='brands'">
      <div class="action-bar"><el-button type="primary" @click="openBrand()"><el-icon><Plus /></el-icon>新增品牌</el-button></div>
      <el-card shadow="never">
        <el-table :data="brandList" border v-loading="bLoad" style="width:100%">
          <el-table-column label="Logo" width="70" align="center"><template #default="{row}"><el-image v-if="row.logo" :src="row.logo" style="width:40px;height:40px;border-radius:4px" /><span v-else>-</span></template></el-table-column>
          <el-table-column label="名称" min-width="160"><template #default="{row}">{{ row.name }}</template></el-table-column>
          <el-table-column label="排序" width="70" align="center"><template #default="{row}">{{ row.sort||0 }}</template></el-table-column>
          <el-table-column label="状态" width="70" align="center"><template #default="{row}"><el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small" @change="saveBrand(row)" /></template></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{row}"><el-button size="small" @click="editBrand(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delBrand(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 轮播图 -->
    <div v-show="aT==='banners'">
      <div class="action-bar"><el-button type="primary" @click="openBanner()"><el-icon><Plus /></el-icon>新增轮播</el-button></div>
      <el-card shadow="never">
        <el-table :data="bannerList" border v-loading="bnLoad" style="width:100%">
          <el-table-column label="图片" width="120" align="center"><template #default="{row}"><el-image :src="row.image" style="width:80px;height:40px;border-radius:4px" /></template></el-table-column>
          <el-table-column label="标题" min-width="160"><template #default="{row}">{{ row.title||'-' }}</template></el-table-column>
          <el-table-column label="链接" min-width="200"><template #default="{row}">{{ row.url||'-' }}</template></el-table-column>
          <el-table-column label="排序" width="70" align="center"><template #default="{row}">{{ row.sort||0 }}</template></el-table-column>
          <el-table-column label="状态" width="70" align="center"><template #default="{row}"><el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small" @change="saveBanner(row)" /></template></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{row}"><el-button size="small" @click="editBanner(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delBanner(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 运费模板 -->
    <div v-show="aT==='shipping'">
      <div class="action-bar"><el-button type="primary" @click="openShip()"><el-icon><Plus /></el-icon>新增模板</el-button></div>
      <el-card shadow="never">
        <el-table :data="shipList" border v-loading="shLoad" style="width:100%">
          <el-table-column prop="name" label="模板名称" min-width="160" />
          <el-table-column label="类型" width="80" align="center"><template #default="{row}"><el-tag size="small">{{ row.type==='piece'?'按件':'按重' }}</el-tag></template></el-table-column>
          <el-table-column label="首件/首重" width="80" align="center"><template #default="{row}">{{ row.first_piece||0 }}</template></el-table-column>
          <el-table-column label="首费" width="80" align="center"><template #default="{row}">¥{{ row.first_fee||0 }}</template></el-table-column>
          <el-table-column label="续件/续重" width="80" align="center"><template #default="{row}">{{ row.extra_piece||0 }}</template></el-table-column>
          <el-table-column label="续费" width="80" align="center"><template #default="{row}">¥{{ row.extra_fee||0 }}</template></el-table-column>
          <el-table-column label="包邮金额" width="100" align="center"><template #default="{row}">¥{{ row.free_shipping_amount||0 }}</template></el-table-column>
          <el-table-column label="状态" width="70" align="center"><template #default="{row}"><el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small" @change="saveShip(row)" /></template></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{row}"><el-button size="small" @click="editShip(row)">编辑</el-button><el-popconfirm title="删除？" @confirm="delShip(row.id)"><template #reference><el-button size="small" type="danger">删除</el-button></template></el-popconfirm></template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 支付记录 -->
    <div v-show="aT==='payments'">
      <el-card shadow="never">
        <el-table :data="payList" border v-loading="payLoad" style="width:100%">
          <el-table-column prop="trade_no" label="交易号" width="200" />
          <el-table-column label="用户" width="120"><template #default="{row}">{{ row.nickname||'用户'+row.user_id }}</template></el-table-column>
          <el-table-column label="关联订单" width="180"><template #default="{row}">{{ row.order_no||'-' }}</template></el-table-column>
          <el-table-column label="金额" width="100" align="center"><template #default="{row}">¥{{ row.amount }}</template></el-table-column>
          <el-table-column label="支付方式" width="100" align="center"><template #default="{row}"><el-tag size="small">{{ {wechat:'微信',alipay:'支付宝',balance:'余额'}[row.method]||row.method||'-' }}</el-tag></template></el-table-column>
          <el-table-column label="状态" width="80" align="center"><template #default="{row}"><el-tag :type="row.status==='success'?'success':'danger'" size="small">{{ row.status==='success'?'成功':'失败' }}</el-tag></template></el-table-column>
          <el-table-column prop="pay_time" label="支付时间" width="160" align="center" />
        </el-table>
        <div class="pagination-wrap"><el-pagination v-model:page-size="payPS" v-model:current-page="payP" :total="payTotal" layout="total,prev,pager,next" @current-change="fetchPays" /></div>
      </el-card>
    </div>

    <!-- 品牌弹窗 -->
    <el-dialog v-model="bVis" :title="bEdit?'编辑品牌':'新增品牌'" width="400px">
      <el-form :model="bForm" label-width="80px">
        <el-form-item label="品牌名"><el-input v-model="bForm.name" maxlength="20" /></el-form-item>
        <el-form-item label="Logo"><el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>bForm.logo=r.data.url"><el-button size="small">上传Logo</el-button><el-image v-if="bForm.logo" :src="bForm.logo" style="width:40px;height:40px;margin-left:8px;border-radius:4px" /></el-upload></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="bForm.sort" :min="0" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="bVis=false">取消</el-button><el-button type="primary" @click="saveBrandSubmit">保存</el-button></template>
    </el-dialog>

    <!-- 轮播弹窗 -->
    <el-dialog v-model="bnVis" :title="bnEdit?'编辑轮播':'新增轮播'" width="450px">
      <el-form :model="bnForm" label-width="80px">
        <el-form-item label="图片" required><el-upload :action="uploadUrl" :headers="uh" :show-file-list="false" :on-success="r=>bnForm.image=r.data.url"><el-image v-if="bnForm.image" :src="bnForm.image" style="width:120px;height:60px;border-radius:6px" /><el-button v-else size="small">上传图片</el-button></el-upload></el-form-item>
        <el-form-item label="标题"><el-input v-model="bnForm.title" maxlength="30" /></el-form-item>
        <el-form-item label="链接"><el-input v-model="bnForm.url" placeholder="https://" maxlength="200" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="bnForm.sort" :min="0" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="bnVis=false">取消</el-button><el-button type="primary" @click="saveBannerSubmit">保存</el-button></template>
    </el-dialog>

    <!-- 运费模板弹窗 -->
    <el-dialog v-model="shVis" :title="shEdit?'编辑模板':'新增模板'" width="700px" class="ship-dialog">
      <el-form :model="shForm" label-width="100px">
        <el-form-item label="模板名称"><el-input v-model="shForm.name" maxlength="30" /></el-form-item>
        <el-form-item label="计费方式"><el-radio-group v-model="shForm.type"><el-radio value="piece">按件</el-radio><el-radio value="weight">按重</el-radio></el-radio-group></el-form-item>
        <el-row :gutter="12"><el-col :span="12"><el-form-item label="首件/首重"><el-input-number v-model="shForm.first_piece" :min="0" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="首费(元)"><el-input-number v-model="shForm.first_fee" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col></el-row>
        <el-row :gutter="12"><el-col :span="12"><el-form-item label="续件/续重"><el-input-number v-model="shForm.extra_piece" :min="0" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="续费(元)"><el-input-number v-model="shForm.extra_fee" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col></el-row>
        <el-form-item label="包邮门槛(元)"><el-input-number v-model="shForm.free_shipping_amount" :min="0" :precision="2" style="width:200px" /><span style="margin-left:8px;font-size:12px;color:#999">满此金额包邮，0为不设</span></el-form-item>

        <el-divider content-position="left">🌍 地区运费设置</el-divider>
        <div style="padding-left:12px">
          <div style="font-size:13px;color:#666;margin-bottom:8px">设置不同地区不同运费，不设置则使用上方默认运费</div>
          <div v-for="(rg, ri) in shipRegions" :key="ri" style="background:#f8f9fa;border-radius:8px;padding:10px;margin-bottom:8px;border:1px solid #eee">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">
              <span style="font-size:13px;font-weight:600;color:#333">地区组 {{ri+1}}</span>
              <el-button size="small" type="danger" plain @click="shipRegions.splice(ri,1)" style="margin-left:auto">删除</el-button>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:6px">
              <el-select v-model="rg.region_ids" multiple collapse-tags collapse-tags-tooltip placeholder="选择地区" style="flex:1;min-width:200px" size="small">
                <el-option v-for="p in provinces" :key="p.id" :value="p.id" :label="p.name" />
              </el-select>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
              <el-form-item label="首费" size="small" label-width="40px" style="margin:0">
                <el-input-number v-model="rg.first_fee" :min="0" :precision="2" size="small" :step="0.5" style="width:120px" />
              </el-form-item>
              <el-form-item label="续费" size="small" label-width="40px" style="margin:0">
                <el-input-number v-model="rg.extra_fee" :min="0" :precision="2" size="small" :step="0.5" style="width:120px" />
              </el-form-item>
              <el-form-item label="首(件/重)" size="small" label-width="65px" style="margin:0">
                <el-input-number v-model="rg.first_piece" :min="0" size="small" style="width:100px" />
              </el-form-item>
              <el-form-item label="续(件/重)" size="small" label-width="65px" style="margin:0">
                <el-input-number v-model="rg.extra_piece" :min="0" size="small" style="width:100px" />
              </el-form-item>
            </div>
          </div>
          <el-button size="small" @click="addRegionGroup" style="margin-bottom:6px">+ 添加地区分组</el-button>
        </div>

        <el-divider content-position="left">🚫 不发货地区</el-divider>
        <div style="padding-left:12px">
          <div style="font-size:13px;color:#666;margin-bottom:8px">选中的地区下单时将提示无法配送</div>
          <el-select v-model="shNoShipIds" multiple collapse-tags collapse-tags-tooltip placeholder="选择不发货地区（新疆/西藏/港澳台等）" style="width:100%" size="default">
            <el-option v-for="p in provinces" :key="p.id" :value="p.id" :label="p.name" />
          </el-select>
          <div style="margin-top:6px">
            <el-button size="small" @click="quickAddNoShip(26)">新疆</el-button>
            <el-button size="small" @click="quickAddNoShip(31)">西藏</el-button>
            <el-button size="small" @click="quickAddNoShip(32,33,34)">港澳台</el-button>
          </div>
        </div>
      </el-form>
      <template #footer><el-button @click="shVis=false">取消</el-button><el-button type="primary" @click="saveShipSubmit">保存</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } 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 tabs=[
  {key:'brands',icon:'🏷️',label:'品牌管理'},
  {key:'banners',icon:'🖼️',label:'轮播图'},
  {key:'shipping',icon:'🚚',label:'运费模板'},
  {key:'payments',icon:'💳',label:'支付记录'},
]
const aT=ref('brands')
function switchTab(k){aT.value=k;if(k==='brands')fetchBrands();else if(k==='banners')fetchBanners();else if(k==='shipping')fetchShip();else if(k==='payments')fetchPays()}

// 品牌
const brandList=ref([]);const bLoad=ref(false);const bVis=ref(false);const bEdit=ref(null)
const bForm=reactive({name:'',logo:'',sort:0})
async function fetchBrands(){bLoad.value=true;try{const r=await API.get('/brands');brandList.value=r.data.data||[]}catch{}finally{bLoad.value=false}}
function openBrand(){bEdit.value=null;bForm.name='';bForm.logo='';bForm.sort=0;bVis.value=true}
function editBrand(r){bEdit.value=r.id;bForm.name=r.name;bForm.logo=r.logo||'';bForm.sort=r.sort||0;bVis.value=true}
async function saveBrandSubmit(){try{if(bEdit.value) await API.put('/brands/'+bEdit.value,bForm);else await API.post('/brands',bForm);ElMessage.success('保存成功');bVis.value=false;fetchBrands()}catch{ElMessage.error('保存失败')}}
async function saveBrand(r){try{await API.put('/brands/'+r.id,{name:r.name,logo:r.logo,sort:r.sort,status:r.status})}catch{}}
async function delBrand(id){try{await API.delete('/brands/'+id);ElMessage.success('已删除');fetchBrands()}catch{}}

// 轮播
const bannerList=ref([]);const bnLoad=ref(false);const bnVis=ref(false);const bnEdit=ref(null)
const bnForm=reactive({image:'',title:'',url:'',sort:0})
async function fetchBanners(){bnLoad.value=true;try{const r=await API.get('/banners');bannerList.value=r.data.data||[]}catch{}finally{bnLoad.value=false}}
function openBanner(){bnEdit.value=null;bnForm.image='';bnForm.title='';bnForm.url='';bnForm.sort=0;bnVis.value=true}
function editBanner(r){bnEdit.value=r.id;bnForm.image=r.image;bnForm.title=r.title||'';bnForm.url=r.url||'';bnForm.sort=r.sort||0;bnVis.value=true}
async function saveBannerSubmit(){try{if(bnEdit.value) await API.put('/banners/'+bnEdit.value,bnForm);else await API.post('/banners',bnForm);ElMessage.success('保存成功');bnVis.value=false;fetchBanners()}catch{}}
async function saveBanner(r){try{await API.put('/banners/'+r.id,{title:r.title,image:r.image,url:r.url,sort:r.sort,status:r.status})}catch{}}
async function delBanner(id){try{await API.delete('/banners/'+id);ElMessage.success('已删除');fetchBanners()}catch{}}

// 运费模板
const shipList=ref([]);const shLoad=ref(false);const shVis=ref(false);const shEdit=ref(null)
const shForm=reactive({name:'',type:'piece',first_piece:1,first_fee:0,extra_piece:1,extra_fee:0,free_shipping_amount:0})
const provinces=ref([])
const shipRegions=ref([])
const shNoShipIds=ref([])

async function fetchProvinces(){try{const r=await axios.get('/api/admin/provinces');provinces.value=r.data.data||[]}catch{}}

function addRegionGroup(){
  shipRegions.value.push({region_ids:[],region_names:[],first_piece:1,first_fee:0,extra_piece:1,extra_fee:0})
}

function quickAddNoShip(...ids){
  ids.forEach(id=>{if(!shNoShipIds.value.includes(id))shNoShipIds.value.push(id)})
}

async function fetchShip(){shLoad.value=true;try{const r=await API.get('/shipping-templates');shipList.value=r.data.data||[]}catch{}finally{shLoad.value=false}}

function openShip(){
  shEdit.value=null
  shForm.name='';shForm.type='piece';shForm.first_piece=1;shForm.first_fee=0
  shForm.extra_piece=1;shForm.extra_fee=0;shForm.free_shipping_amount=0
  shipRegions.value=[]
  shNoShipIds.value=[]
  shVis.value=true
}

async function editShip(r){
  shEdit.value=r.id
  shForm.name=r.name;shForm.type=r.type;shForm.first_piece=r.first_piece;shForm.first_fee=r.first_fee
  shForm.extra_piece=r.extra_piece;shForm.extra_fee=r.extra_fee;shForm.free_shipping_amount=r.free_shipping_amount
  // Load regions
  try{
    const [regRes, noshipRes]=await Promise.all([
      API.get('/shipping-templates/'+r.id+'/regions'),
      API.get('/shipping-templates/'+r.id+'/no-ship')
    ])
    shipRegions.value=(regRes.data.data||[]).map(rg=>({
      ...rg,
      region_ids:JSON.parse(rg.region_ids||'[]'),
      region_names:JSON.parse(rg.region_names||'[]')
    }))
    const ns=noshipRes.data.data||[]
    if(ns.length>0){
      shNoShipIds.value=JSON.parse(ns[0].region_ids||'[]')
    }else{
      shNoShipIds.value=[]
    }
  }catch{shipRegions.value=[];shNoShipIds.value=[]}
  shVis.value=true
}

async function saveShipSubmit(){
  try{
    // 先保存模板基本设置
    if(shEdit.value){
      await API.put('/shipping-templates/'+shEdit.value,shForm)
    }else{
      const r=await API.post('/shipping-templates',shForm)
      shEdit.value=r.data.data?.id||r.id
    }
    const tid=shEdit.value
    // 保存地区分组
    for(const rg of shipRegions.value){
      const regNames=rg.region_ids.map(id=>{
        const p=provinces.value.find(x=>x.id===id)
        return p?p.name:''
      }).filter(Boolean)
      if(rg.id){
        await API.put('/shipping-templates/'+tid+'/regions/'+rg.id,{...rg,region_names:regNames})
      }else{
        await API.post('/shipping-templates/'+tid+'/regions',{...rg,region_names:regNames})
      }
    }
    // 保存不发货地区
    const nsNames=shNoShipIds.value.map(id=>{
      const p=provinces.value.find(x=>x.id===id)
      return p?p.name:''
    }).filter(Boolean)
    await API.post('/shipping-templates/'+tid+'/no-ship',{region_ids:shNoShipIds.value,region_names:nsNames})
    
    ElMessage.success('保存成功')
    shVis.value=false
    fetchShip()
  }catch(e){
    ElMessage.error('保存失败: '+e.message)
  }
}
async function saveShip(r){try{await API.put('/shipping-templates/'+r.id,{name:r.name,type:r.type,first_piece:r.first_piece,first_fee:r.first_fee,extra_piece:r.extra_piece,extra_fee:r.extra_fee,free_shipping_amount:r.free_shipping_amount,status:r.status})}catch{}}
async function delShip(id){try{await API.delete('/shipping-templates/'+id);ElMessage.success('已删除');fetchShip()}catch{}}

// 支付记录
const payList=ref([]);const payLoad=ref(false);const payP=ref(1);const payPS=ref(15);const payTotal=ref(0)
async function fetchPays(){payLoad.value=true;try{const r=await API.get('/payment-records',{params:{page:payP.value,pageSize:payPS.value}});payList.value=r.data.data?.list||[];payTotal.value=r.data.data?.total||0}catch{}finally{payLoad.value=false}}

onMounted(()=>{fetchBrands();fetchBanners();fetchShip();fetchProvinces()})
</script>
<style scoped>
.ext-page{max-width:1400px}
.tabs-card{margin-bottom:16px;padding:4px 0}
.ship-dialog :deep(.el-dialog__body){padding:16px 24px}
.ship-dialog :deep(.el-select .el-tag){max-width:160px;overflow:hidden;text-overflow:ellipsis}
.ship-dialog :deep(.el-divider__text){font-size:14px;font-weight:600}
.e-tabs{display:flex;gap:4px}
.e-tab{display:flex;align-items:center;gap:6px;padding:10px 18px;border-radius:8px;cursor:pointer;font-size:14px;transition:all .2s}
.e-tab:hover{background:#f5f7fa}
.e-tab.active{background:#ecf5ff;color:#409eff;font-weight:600}
.action-bar{margin-bottom:16px}
.pagination-wrap{display:flex;justify-content:flex-end;padding:16px 0 0}
</style>
