<template>
  <a-layout style="min-height: 100vh">
    <a-layout-sider :width="220" theme="dark" collapsible>
      <div style="height: 56px; display:flex; align-items:center; justify-content:center; color:#fff; font-weight:600;">顾客中心</div>
      <a-menu :selected-keys="[active]" @menu-item-click="(k)=>active=k">
        <a-menu-item key="products">商品购买</a-menu-item>
        <a-menu-item key="cart">购物车</a-menu-item>
        <a-menu-item key="orders">订单管理</a-menu-item>
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header style="background:#fff; display:flex; justify-content:space-between; align-items:center; padding:0 16px;">
        <strong>{{ titleMap[active] }}</strong>
        <a-space>
          <a-input v-model="address" style="width: 280px" placeholder="默认收货地址" />
          <a-button @click="goHome">去商城</a-button>
          <a-button status="danger" @click="logout">退出</a-button>
        </a-space>
      </a-layout-header>
      <a-layout-content style="padding:16px;">
        <a-card v-if="active==='products'" title="商品购买">
          <a-space style="margin-bottom: 10px">
            <a-input-search v-model="keyword" placeholder="搜索商品" search-button @search="loadProducts" />
            <a-button @click="loadProducts">刷新</a-button>
          </a-space>
          <a-table :columns="productColumns" :data="products" :pagination="{ pageSize: 8 }">
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" @click="addCart(record.id)">加入购物车</a-button>
                <a-button size="mini" type="primary" @click="buyNow(record.id)">立即购买</a-button>
              </a-space>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='cart'" title="我的购物车">
          <a-space style="margin-bottom: 10px">
            <a-button type="primary" @click="checkout">结算购物车</a-button>
            <a-button @click="loadCart">刷新</a-button>
          </a-space>
          <a-table :columns="cartColumns" :data="cart" :pagination="false">
            <template #actions="{ record }">
              <a-button size="mini" status="danger" @click="delCart(record.productId)">移除</a-button>
            </template>
          </a-table>
        </a-card>

        <a-card v-if="active==='orders'" title="我的订单">
          <a-table :columns="orderColumns" :data="orders" :pagination="{ pageSize: 8 }">
            <template #actions="{ record }">
              <a-space>
                <a-button size="mini" @click="refund(record.id)">退款</a-button>
                <a-button size="mini" @click="delOrder(record.id)">删除</a-button>
              </a-space>
            </template>
          </a-table>
        </a-card>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const active = ref('products')
const titleMap = { products: '商品购买', cart: '购物车管理', orders: '订单管理' }

const address = ref('辽宁省大连市高新区')
const keyword = ref('')
const products = ref([])
const cart = ref([])
const orders = ref([])

const productColumns = [
  { title: '名称', dataIndex: 'name' },
  { title: '分类', dataIndex: 'category' },
  { title: '价格', dataIndex: 'price' },
  { title: '库存', dataIndex: 'stock' },
  { title: '操作', slotName: 'actions' }
]

const cartColumns = [
  { title: '商品名称', dataIndex: 'productName' },
  { title: '分类', dataIndex: 'category' },
  { title: '单价', dataIndex: 'unitPrice' },
  { title: '数量', dataIndex: 'quantity' },
  { title: '小计', dataIndex: 'subtotal' },
  { title: '库存', dataIndex: 'stock' },
  { title: '操作', slotName: 'actions' }
]

const orderColumns = [
  { title: '订单号', dataIndex: 'orderNo' },
  { title: '金额', dataIndex: 'totalAmount' },
  { title: '状态', dataIndex: 'status' },
  { title: '操作', slotName: 'actions' }
]

const goHome = () => router.push('/')
const logout = async () => {
  await userStore.logout()
  router.replace('/login')
}

const loadProducts = async () => {
  products.value = await api.products(keyword.value)
}
const loadCart = async () => {
  cart.value = await api.customerCartViews()
}
const loadOrders = async () => {
  orders.value = await api.customerOrders()
}

const addCart = async (productId) => {
  await api.addCart({ productId, quantity: 1 })
  Message.success('已加入购物车')
  await loadCart()
}

const delCart = async (productId) => {
  await api.delCart(productId)
  Message.success('已移除')
  await loadCart()
}

const buyNow = async (productId) => {
  if (!address.value) return Message.warning('请先填写收货地址')
  await api.customerBuyNow({ productId, quantity: 1, address: address.value })
  Message.success('购买成功')
  await loadOrders()
  active.value = 'orders'
}

const checkout = async () => {
  if (!address.value) return Message.warning('请先填写收货地址')
  await api.checkout({ address: address.value })
  Message.success('结算成功')
  await Promise.all([loadCart(), loadOrders()])
  active.value = 'orders'
}

const refund = async (id) => {
  await api.refundOrder(id, { reason: '不想要了' })
  Message.success('退款申请已提交')
  await loadOrders()
}

const delOrder = async (id) => {
  await api.deleteOrder(id)
  Message.success('订单已删除')
  await loadOrders()
}

watch(active, async (v) => {
  if (v === 'products') await loadProducts()
  if (v === 'cart') await loadCart()
  if (v === 'orders') await loadOrders()
})

onMounted(async () => {
  await userStore.fetchMe()
  if (userStore.role !== 'CUSTOMER') return router.replace('/login')
  await Promise.all([loadProducts(), loadCart(), loadOrders()])
})
</script>
