<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { getDefaultAddressApi, getAddressListApi } from '@/api/address'
import { getProductDetailApi } from '@/api/product'
import { submitOrderApi, payOrderApi } from '@/api/order'
import type { Address, ProductSku, ProductDetail } from '@/types'
import { Location, MapLocation, Document } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()

const addressList = ref<Address[]>([])
const address = ref<Address | null>(null)
const remark = ref('')
const submitting = ref(false)

const buyNowItem = ref<{ product: ProductDetail | null; sku: ProductSku | null; quantity: number }>({
  product: null,
  sku: null,
  quantity: 1
})

const isBuyNow = computed(() => route.query.from === 'buyNow')

const orderItems = computed(() => {
  if (isBuyNow.value) {
    if (!buyNowItem.value.sku) return []
    return [{
      productId: buyNowItem.value.product!.id,
      productName: buyNowItem.value.product!.name,
      productImage: buyNowItem.value.sku.image || buyNowItem.value.product!.mainImage,
      skuId: buyNowItem.value.sku.id,
      skuName: buyNowItem.value.sku.skuName,
      price: buyNowItem.value.sku.price,
      quantity: buyNowItem.value.quantity,
      subtotal: Number(buyNowItem.value.sku.price) * buyNowItem.value.quantity
    }]
  }
  return cartStore.items.filter(i => i.selected === 1)
})

const totalAmount = computed(() =>
  orderItems.value.reduce((sum, item) => sum + Number(item.price) * item.quantity, 0)
)
const freight = computed(() => totalAmount.value >= 99 || totalAmount.value === 0 ? 0 : 10)
const payAmount = computed(() => totalAmount.value + freight.value)

onMounted(async () => {
  if (isBuyNow.value) {
    const productId = Number(route.query.productId)
    const skuId = Number(route.query.skuId)
    const quantity = Number(route.query.quantity || 1)
    try {
      const detail = await getProductDetailApi(productId)
      const sku = detail.skuList.find(s => s.id === skuId) || detail.skuList[0] || null
      buyNowItem.value = { product: detail, sku, quantity }
    } catch {
      ElMessage.error('商品信息加载失败')
      router.replace('/')
      return
    }
  } else {
    if (!cartStore.items.length) {
      await cartStore.fetchCart()
    }
  }

  try {
    const list = await getAddressListApi()
    addressList.value = list || []
    const def = list.find(a => a.isDefault === 1)
    address.value = def || list[0] || null
    if (!def) {
      try { address.value = await getDefaultAddressApi() } catch { /* ignore */ }
    }
  } catch {
    addressList.value = []
  }
})

function pickAddress(a: Address) {
  address.value = a
}

async function submitOrder() {
  if (!address.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  if (orderItems.value.length === 0) {
    ElMessage.warning('订单中没有商品')
    return
  }
  submitting.value = true
  try {
    const { orderNo } = await submitOrderApi({
      items: orderItems.value.map(it => ({ skuId: it.skuId, quantity: it.quantity })),
      addressId: address.value.id,
      remark: remark.value || undefined
    })
    if (!isBuyNow.value) {
      const skuIds = orderItems.value.map(it => it.skuId)
      await cartStore.batchRemove(skuIds).catch(() => null)
    }
    try { await payOrderApi(Number(orderNo.split('_').pop()) || 0) } catch { /* ignore */ }
    ElMessage.success('订单提交成功')
    router.push({ name: 'orders' })
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="confirm-page container">
    <div class="page-header">
      <h2 class="page-title">确认订单</h2>
      <p class="page-subtitle">请核对订单信息后提交</p>
    </div>

    <div class="confirm-content">
      <!-- Address Section -->
      <div class="section-card">
        <div class="section-header-row">
          <div class="section-icon location">
            <el-icon><Location /></el-icon>
          </div>
          <span class="section-name">收货地址</span>
        </div>
        <div v-if="addressList.length" class="address-grid">
          <div
            v-for="a in addressList" :key="a.id"
            class="address-card"
            :class="{ active: address?.id === a.id }"
            @click="pickAddress(a)"
          >
            <div class="address-header">
              <div class="address-user">
                <span class="receiver">{{ a.receiver }}</span>
                <span class="phone">{{ a.phone }}</span>
              </div>
              <div class="address-tags">
                <el-tag v-if="a.tag" size="small" effect="plain">{{ a.tag }}</el-tag>
                <el-tag v-if="a.isDefault === 1" type="danger" size="small" effect="dark">默认</el-tag>
              </div>
            </div>
            <p class="address-detail">
              <el-icon size="14"><MapLocation /></el-icon>
              {{ a.fullAddress || `${a.province || ''} ${a.city || ''} ${a.district || ''} ${a.detail}` }}
            </p>
            <div v-if="address?.id === a.id" class="active-indicator">
              <el-icon><CircleCheck /></el-icon>
            </div>
          </div>
        </div>
        <el-button v-else type="primary" text @click="router.push('/address')">
          <el-icon><Location /></el-icon> 添加收货地址
        </el-button>
      </div>

      <!-- Products Section -->
      <div class="section-card">
        <div class="section-header-row">
          <div class="section-icon product">
            <el-icon><Document /></el-icon>
          </div>
          <span class="section-name">商品清单</span>
          <span class="section-count">共 {{ orderItems.length }} 件</span>
        </div>
        <div v-if="orderItems.length" class="item-list">
          <div v-for="item in orderItems" :key="item.skuId" class="item-row">
            <div class="item-thumb">
              <img :src="item.productImage || 'https://placehold.co/100x100?text=SNACK'" />
            </div>
            <div class="item-info">
              <p class="name">{{ item.productName }}</p>
              <p class="sku">{{ item.skuName }}</p>
            </div>
            <div class="item-price">
              <span class="price">¥{{ item.price }}</span>
              <span class="qty">x{{ item.quantity }}</span>
            </div>
          </div>
        </div>
        <el-empty v-else description="没有可结算的商品" />
      </div>

      <!-- Remark Section -->
      <div class="section-card">
        <div class="section-header-row">
          <div class="section-icon remark">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <span class="section-name">订单备注</span>
        </div>
        <el-input
          v-model="remark"
          placeholder="请输入订单备注（选填）"
          maxlength="200"
          show-word-limit
          type="textarea"
          :rows="2"
          class="remark-input"
        />
      </div>

      <!-- Summary Section -->
      <div class="section-card summary-card">
        <div class="summary-row">
          <span>商品总额</span>
          <span>¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="summary-row">
          <span>运费</span>
          <span :class="{ 'free-tag': freight === 0 }">{{ freight === 0 ? '免运费' : '¥' + freight.toFixed(2) }}</span>
        </div>
        <div class="summary-divider"></div>
        <div class="summary-row total">
          <span>应付总额</span>
          <span class="total-price">¥{{ payAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- Submit Bar -->
      <div class="submit-bar">
        <div class="submit-info">
          <span class="submit-label">应付总额：</span>
          <span class="submit-price">¥{{ payAmount.toFixed(2) }}</span>
        </div>
        <el-button
          type="primary"
          size="large"
          class="submit-btn"
          :loading="submitting"
          :disabled="!orderItems.length"
          @click="submitOrder"
        >
          提交订单
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.confirm-page {
  padding: 24px 0 60px;
}
.page-header {
  margin-bottom: 24px;
}
.page-title {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 4px;
}
.page-subtitle {
  color: var(--color-text-muted);
  font-size: 14px;
}

/* Section Card */
.section-card {
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 24px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
}
.section-header-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}
.section-icon {
  width: 36px;
  height: 36px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
.section-icon.location {
  background: linear-gradient(135deg, #FF6B35, #FF8F5D);
}
.section-icon.product {
  background: linear-gradient(135deg, #3B82F6, #60A5FA);
}
.section-icon.remark {
  background: linear-gradient(135deg, #F59E0B, #FBBF24);
}
.section-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text);
}
.section-count {
  margin-left: auto;
  font-size: 13px;
  color: var(--color-text-muted);
}

/* Address Grid */
.address-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}
.address-card {
  position: relative;
  border: 2px solid var(--color-border-light);
  border-radius: var(--radius-lg);
  padding: 18px;
  cursor: pointer;
  transition: all var(--transition-fast);
  background: #fff;
}
.address-card:hover {
  border-color: var(--color-primary);
  box-shadow: var(--shadow-md);
}
.address-card.active {
  border-color: var(--color-primary);
  background: var(--color-primary-light);
}
.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.address-user {
  display: flex;
  align-items: center;
  gap: 10px;
}
.receiver {
  font-weight: 700;
  font-size: 15px;
  color: var(--color-text);
}
.phone {
  color: var(--color-text-secondary);
  font-size: 14px;
}
.address-tags {
  display: flex;
  gap: 6px;
}
.address-detail {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  color: var(--color-text-secondary);
  font-size: 14px;
  line-height: 1.5;
}
.active-indicator {
  position: absolute;
  top: 12px;
  right: 12px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: var(--color-primary);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

/* Item List */
.item-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.item-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  border-radius: var(--radius-md);
  background: var(--color-background);
}
.item-thumb {
  width: 72px;
  height: 72px;
  border-radius: var(--radius-md);
  overflow: hidden;
  flex-shrink: 0;
}
.item-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.item-info {
  flex: 1;
}
.item-info .name {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 6px;
  color: var(--color-text);
}
.item-info .sku {
  color: var(--color-text-muted);
  font-size: 13px;
}
.item-price {
  text-align: right;
  min-width: 100px;
}
.item-price .qty {
  color: var(--color-text-muted);
  margin-left: 8px;
  font-size: 13px;
}

/* Remark */
.remark-input :deep(.el-textarea__inner) {
  border-radius: var(--radius-md);
}

/* Summary Card */
.summary-card {
  background: linear-gradient(135deg, #FFF0EB 0%, #FFF7ED 100%);
  border: 1px solid rgba(255, 107, 53, 0.1);
}
.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  color: var(--color-text-secondary);
  font-size: 15px;
}
.summary-row.total {
  font-size: 18px;
  font-weight: 700;
  color: var(--color-text);
  padding-top: 12px;
}
.total-price {
  color: var(--color-primary);
  font-size: 24px;
  font-weight: 700;
}
.free-tag {
  color: var(--color-success);
  font-weight: 600;
}
.summary-divider {
  height: 1px;
  background: var(--color-border);
  margin: 8px 0;
}

/* Submit Bar */
.submit-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 24px;
  padding: 20px 24px;
  background: #fff;
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--color-border-light);
  position: sticky;
  bottom: 20px;
}
.submit-info {
  display: flex;
  align-items: baseline;
  gap: 8px;
}
.submit-label {
  font-size: 15px;
  color: var(--color-text-secondary);
}
.submit-price {
  font-size: 28px;
  color: var(--color-primary);
  font-weight: 700;
}
.submit-btn {
  padding: 0 40px;
  height: 48px;
  border-radius: var(--radius-full);
  font-size: 16px;
  font-weight: 600;
}

/* Responsive */
@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }
  .submit-bar {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
    position: fixed;
    bottom: 64px;
    left: 0;
    right: 0;
    border-radius: var(--radius-lg) var(--radius-lg) 0 0;
    z-index: 100;
  }
  .submit-btn {
    width: 100%;
  }
}
</style>
