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

    <!-- Tab1: 积分商品管理 -->
    <div v-show="activeTab==='products'">
      <div class="action-bar">
        <el-button type="primary" @click="openProduct()"><el-icon><Plus /></el-icon>新增积分商品</el-button>
        <el-input v-model="prodKeyword" placeholder="搜索商品" clearable style="width:200px;margin-left:12px" @clear="fetchProducts" @keyup.enter="fetchProducts" />
      </div>
      <el-card shadow="never">
        <el-table :data="productList" border v-loading="prodLoad" style="width:100%">
          <el-table-column label="商品" min-width="220">
            <template #default="{row}">
              <div style="display:flex;align-items:center;gap:8px">
                <el-image :src="row.image" style="width:40px;height:40px;border-radius:4px" fit="cover">
                  <template #error><div style="width:40px;height:40px;background:#eee;border-radius:4px;display:flex;align-items:center;justify-content:center;font-size:16px">📷</div></template>
                </el-image>
                <span style="font-weight:500">{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="所需积分" width="100" align="center">
            <template #default="{row}"><span style="color:#e6a23c;font-weight:700">{{ row.points }}</span></template>
          </el-table-column>
          <el-table-column label="现金价" width="90" align="center">
            <template #default="{row}">{{ row.price>0?'¥'+row.price:'纯积分' }}</template>
          </el-table-column>
          <el-table-column label="库存" width="70" align="center">
            <template #default="{row}"><span :style="{color:row.stock<=10?'#e74c3c':'inherit'}">{{ row.stock }}</span></template>
          </el-table-column>
          <el-table-column label="每人限兑" width="80" align="center">
            <template #default="{row}">{{ row.limit_count||'不限' }}</template>
          </el-table-column>
          <el-table-column label="排序" width="60" align="center">
            <template #default="{row}">{{ row.sort||0 }}</template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{row}">
              <el-tag :type="row.status===1?'success':'info'" size="small">{{ row.status===1?'上架':'下架' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{row}">
              <el-button size="small" @click="openProduct(row)">编辑</el-button>
              <el-button size="small" :type="row.status===1?'warning':'success'" @click="toggleProduct(row)">{{ row.status===1?'下架':'上架' }}</el-button>
              <el-popconfirm title="确定删除该商品？" @confirm="delProduct(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="prodPS" v-model:current-page="prodP" :total="prodTotal" layout="total,prev,pager,next" @current-change="fetchProducts" />
        </div>
      </el-card>
    </div>

    <!-- Tab2: 兑换订单管理 -->
    <div v-show="activeTab==='orders'">
      <div class="action-bar">
        <el-select v-model="orderStatus" placeholder="订单状态" clearable style="width:140px" @change="fetchOrders">
          <el-option label="待处理" value="pending" />
          <el-option label="已发货" value="shipped" />
          <el-option label="已收货" value="received" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
        <el-input v-model="orderKeyword" placeholder="单号/收货人/电话" clearable style="width:220px;margin-left:12px" @clear="fetchOrders" @keyup.enter="fetchOrders" />
      </div>
      <el-card shadow="never">
        <el-table :data="orderList" border v-loading="orderLoad" style="width:100%">
          <el-table-column prop="order_no" label="兑换单号" width="180" />
          <el-table-column label="用户" width="120">
            <template #default="{row}">{{ row.nickname||'用户' }}({{ row.phone||'?' }})</template>
          </el-table-column>
          <el-table-column label="商品" min-width="200">
            <template #default="{row}">
              <div style="display:flex;align-items:center;gap:8px">
                <el-image :src="row.product_image" style="width:36px;height:36px;border-radius:4px" fit="cover">
                  <template #error><div style="width:36px;height:36px;background:#eee;border-radius:4px;display:flex;align-items:center;justify-content:center;font-size:12px">📷</div></template>
                </el-image>
                <span>{{ row.product_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="消耗积分" width="90" align="center">
            <template #default="{row}">{{ row.points*row.quantity }}</template>
          </el-table-column>
          <el-table-column label="数量" width="60" align="center">
            <template #default="{row}">{{ row.quantity }}</template>
          </el-table-column>
          <el-table-column label="收货信息" min-width="180">
            <template #default="{row}">
              <div>{{ row.recipient_name||'-' }}</div>
              <div style="font-size:12px;color:#999">{{ row.recipient_phone||'' }}</div>
              <div style="font-size:12px;color:#999;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ row.recipient_address||'' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template #default="{row}">
              <el-tag :type="orderStatusTag(row.status)" size="small">{{ orderStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="时间" width="160" align="center">
            <template #default="{row}">{{ row.created_at }}</template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{row}">
              <el-button size="small" type="primary" @click="shipOrder(row)" v-if="row.status==='pending'">发货</el-button>
              <el-button size="small" type="success" @click="receiveOrder(row)" v-if="row.status==='shipped'">确认收货</el-button>
              <span v-if="row.status==='received'||row.status==='cancelled'" style="color:#999;font-size:12px">--</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrap">
          <el-pagination v-model:page-size="orderPS" v-model:current-page="orderP" :total="orderTotal" layout="total,prev,pager,next" @current-change="fetchOrders" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑积分商品弹窗 -->
    <el-dialog v-model="prodVis" :title="prodEdit?'编辑积分商品':'新增积分商品'" width="550px">
      <el-form :model="prodForm" label-width="100px">
        <el-form-item label="商品名称" required>
          <el-input v-model="prodForm.name" maxlength="100" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片">
          <div style="display:flex;align-items:center;gap:8px">
            <el-image v-if="prodForm.image" :src="prodForm.image" style="width:60px;height:60px;border-radius:4px" fit="cover" />
            <el-input v-model="prodForm.image" placeholder="图片URL" style="flex:1" />
          </div>
        </el-form-item>
        <el-form-item label="所需积分" required>
          <el-input-number v-model="prodForm.points" :min="1" style="width:200px" />
        </el-form-item>
        <el-form-item label="现金价">
          <el-input-number v-model="prodForm.price" :min="0" :precision="2" style="width:200px" />
          <span style="margin-left:8px;color:#999;font-size:12px">0为纯积分兑换</span>
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="prodForm.stock" :min="0" style="width:200px" />
        </el-form-item>
        <el-form-item label="每人限兑">
          <el-input-number v-model="prodForm.limit_count" :min="0" style="width:200px" />
          <span style="margin-left:8px;color:#999;font-size:12px">0为不限</span>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="prodForm.sort" :min="0" style="width:200px" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="prodForm.description" type="textarea" :rows="3" maxlength="500" placeholder="商品说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="prodVis=false">取消</el-button>
        <el-button type="primary" @click="saveProduct" :loading="prodSaveLoading">保存</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 tabs = [
  { key:'products', icon:'🎁', label:'积分商品管理' },
  { key:'orders', icon:'📋', label:'兑换订单管理' },
]
const activeTab = ref('products')
const prodKeyword = ref('')

// ===== 积分商品 =====
const productList = ref([])
const prodLoad = ref(false)
const prodP = ref(1)
const prodPS = ref(10)
const prodTotal = ref(0)
const prodVis = ref(false)
const prodEdit = ref(null)
const prodSaveLoading = ref(false)
const prodForm = reactive({
  name:'', image:'', points:100, price:0, stock:10, limit_count:0, description:'', sort:0
})

async function fetchProducts() {
  prodLoad.value = true
  try {
    const params = { page: prodP.value, pageSize: prodPS.value }
    if (prodKeyword.value) params.keyword = prodKeyword.value
    const r = await API.get('/exchange/products', { params })
    const d = r.data.data || {}
    productList.value = d.list || []
    prodTotal.value = d.total || 0
  } catch { productList.value = [] }
  finally { prodLoad.value = false }
}

function openProduct(row) {
  prodEdit.value = row?.id || null
  if (row) {
    prodForm.name = row.name
    prodForm.image = row.image||''
    prodForm.points = row.points
    prodForm.price = row.price||0
    prodForm.stock = row.stock||0
    prodForm.limit_count = row.limit_count||0
    prodForm.description = row.description||''
    prodForm.sort = row.sort||0
  } else {
    prodForm.name = ''
    prodForm.image = ''
    prodForm.points = 100
    prodForm.price = 0
    prodForm.stock = 10
    prodForm.limit_count = 0
    prodForm.description = ''
    prodForm.sort = 0
  }
  prodVis.value = true
}

async function saveProduct() {
  if (!prodForm.name) return ElMessage.warning('请填写商品名称')
  if (!prodForm.points || prodForm.points <= 0) return ElMessage.warning('积分必须大于0')
  prodSaveLoading.value = true
  try {
    if (prodEdit.value) {
      await API.put('/exchange/products/' + prodEdit.value, prodForm)
    } else {
      await API.post('/exchange/products', prodForm)
    }
    ElMessage.success('保存成功')
    prodVis.value = false
    fetchProducts()
  } catch { ElMessage.error('保存失败') }
  finally { prodSaveLoading.value = false }
}

async function toggleProduct(row) {
  try {
    await API.put('/exchange/products/' + row.id + '/toggle')
    ElMessage.success(row.status===1?'已下架':'已上架')
    fetchProducts()
  } catch { ElMessage.error('操作失败') }
}

async function delProduct(id) {
  try {
    await API.delete('/exchange/products/' + id)
    ElMessage.success('已删除')
    fetchProducts()
  } catch { ElMessage.error('删除失败') }
}

// ===== 兑换订单 =====
const orderList = ref([])
const orderLoad = ref(false)
const orderP = ref(1)
const orderPS = ref(10)
const orderTotal = ref(0)
const orderStatus = ref('')
const orderKeyword = ref('')

function orderStatusTag(s) {
  return { pending:'warning', shipped:'primary', received:'success', cancelled:'info' }[s]||'info'
}
function orderStatusLabel(s) {
  return { pending:'待处理', shipped:'已发货', received:'已收货', cancelled:'已取消' }[s]||s
}

async function fetchOrders() {
  orderLoad.value = true
  try {
    const params = { page: orderP.value, pageSize: orderPS.value }
    if (orderStatus.value) params.status = orderStatus.value
    if (orderKeyword.value) params.keyword = orderKeyword.value
    const r = await API.get('/exchange/orders', { params })
    const d = r.data.data || {}
    orderList.value = d.list || []
    orderTotal.value = d.total || 0
  } catch { orderList.value = [] }
  finally { orderLoad.value = false }
}

async function shipOrder(row) {
  try {
    await API.put('/exchange/orders/' + row.id + '/ship')
    ElMessage.success('发货成功')
    fetchOrders()
  } catch { ElMessage.error('发货失败') }
}

async function receiveOrder(row) {
  try {
    await API.put('/exchange/orders/' + row.id + '/receive')
    ElMessage.success('已确认收货')
    fetchOrders()
  } catch { ElMessage.error('操作失败') }
}

function switchTab(k) {
  activeTab.value = k
  if (k === 'products') fetchProducts()
  else if (k === 'orders') fetchOrders()
}

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

<style scoped>
.exchange-page { max-width: 1400px; }
.tabs-card { margin-bottom:16px; padding:4px 0; }
.mkt-tabs { display:flex; gap:4px; }
.mkt-tab { display:flex; align-items:center; gap:6px; padding:10px 18px; border-radius:8px; cursor:pointer; font-size:14px; transition:all .2s; }
.mkt-tab:hover { background:#f5f7fa; }
.mkt-tab.active { background:#ecf5ff; color:#409eff; font-weight:600; }
.action-bar { margin-bottom:16px; display:flex; align-items:center; }
.pagination-wrap { display:flex; justify-content:flex-end; padding:16px 0 0; }
</style>
