<template>
  <section class="page-card" v-if="!loading && product">
    <div class="checkout-header">
      <div>
        <h2>立即下单 · {{ product.name }}</h2>
        <p class="tag">一个扫码流程即可完成订单</p>
      </div>
      <button class="ghost" @click="goBack">返回商品</button>
    </div>

    <div class="checkout-grid">
      <div class="checkout-summary">
        <img :src="product.coverUrl" :alt="product.name" />
        <div class="summary-content">
          <h3>{{ product.name }}</h3>
          <p class="tag">库存：{{ product.quantity }}</p>
          <p class="tag">浏览量：{{ product.viewCount || 0 }}</p>
          <p class="product-price">
            <span v-if="isFree" class="free-price">免费</span>
            <span
              v-else-if="product.discountPrice > 0 && product.discountPrice < product.price"
            >
              <span class="price-original">¥ {{ product.price.toFixed(2) }}</span>
              <span class="price-discount">¥ {{ product.discountPrice.toFixed(2) }}</span>
            </span>
            <span v-else>¥ {{ product.price.toFixed(2) }}</span>
          </p>
          <p class="markdown" v-html="renderMarkdown(product.description)"></p>
        </div>
      </div>

      <div class="checkout-form" v-if="!orderResult && product.requireLogin && !loggedIn">
        <div class="require-login-block">
          <p class="require-login-title">该商品需要登录后才能购买</p>
          <a class="primary btn-inline" :href="loginUrl">立即登录</a>
        </div>
      </div>

      <form class="checkout-form" @submit.prevent="submitOrder" v-else-if="!orderResult">
        <div class="form-field">
          <label>下单数量</label>
          <input
            v-model.number="form.quantity"
            min="1"
            :max="product.maxPerAccount > 0 ? product.maxPerAccount : undefined"
            type="number"
          />
        </div>
        <p class="tag">预计总价：¥ {{ totalPrice.toFixed(2) }}</p>
        <p class="tag limit-hint" v-if="product.maxPerAccount > 0">
          该商品每个账户最多可购买 {{ product.maxPerAccount }} 个
        </p>

        <div class="form-field" v-if="product.showNote">
          <label>备注（选填）</label>
          <textarea v-model="form.note" placeholder="填写您的备注信息…" rows="3"></textarea>
        </div>

        <template v-if="product.showContact">
          <div class="form-row contact-row">
            <div class="form-field">
              <label>手机号（选填）</label>
              <input v-model="form.contactPhone" type="tel" placeholder="138xxxx0000" />
            </div>
            <div class="form-field">
              <label>邮箱（选填）</label>
              <input v-model="form.contactEmail" type="email" placeholder="you@example.com" />
            </div>
          </div>
        </template>

        <p class="tag login-hint" v-if="!loggedIn">
          <a :href="loginUrl">登录萌芽账号</a> 后购买可享受：历史订单记录、专属优惠商品及更多购买权益
        </p>
        <div class="delivery-tip" v-if="product.deliveryMode === 'manual'">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
          该商品为手动发货，付款后管理员将核验并处理您的订单
        </div>
        <button class="primary" type="submit" :disabled="submitting">
          {{ submitting ? '生成中...' : '生成二维码下单' }}
        </button>
        <p class="error" v-if="error">{{ error }}</p>
      </form>
    </div>

    <section class="order-result" v-if="orderResult">
      <h4>订单 {{ orderResult.orderId }} 已创建</h4>

      <template v-if="!confirmed">
        <p class="tag">请扫描下方二维码完成付款</p>
        <img :src="orderResult.qrCodeUrl" alt="下单二维码" />
        <div class="confirm-area">
          <button class="primary" :disabled="confirming" @click="doConfirm">
            {{ confirming ? '确认中...' : '我已完成扫码付款' }}
          </button>
          <p class="tag">扫码完成后点击上方按钮获取购买内容</p>
        </div>
        <p class="error" v-if="confirmError">{{ confirmError }}</p>
      </template>

      <template v-else>
        <p class="tag confirmed-badge">订单已完成</p>
        <div class="result-content" v-if="deliveredCodes.length">
          <p class="tag">购买后内容</p>
          <textarea class="delivery-box" readonly :value="deliveredCodes.join('\n')"></textarea>
        </div>
        <div v-else-if="isManualDelivery" class="manual-delivery-notice">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
          <div>
            <p class="manual-delivery-title">等待发货中</p>
            <p class="tag">管理员将尽快处理您的订单并进行发货，请关注您的邮箱或联系方式。</p>
          </div>
        </div>
        <p class="tag">感谢购买！如有问题请联系售后邮箱。</p>
      </template>
    </section>
  </section>

  <section class="page-card" v-else-if="!loading">
    <h2>未找到该商品</h2>
    <p class="tag">该商品无法下单，请返回商店页。</p>
    <div class="detail-actions">
      <button class="ghost" @click="goBack">返回商品</button>
    </div>
  </section>

  <section class="page-card" v-else>
    <div class="status">加载中...</div>
  </section>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { fetchProducts, createOrder, confirmOrder } from '../shared/api'
import { authState, isLoggedIn, getLoginUrl } from '../shared/auth'

const route = useRoute()
const router = useRouter()
const md = new MarkdownIt()
const product = ref(null)
const loading = ref(true)
const submitting = ref(false)
const error = ref('')
const orderResult = ref(null)
const confirmed = ref(false)
const confirming = ref(false)
const confirmError = ref('')
const deliveredCodes = ref([])

const loggedIn = computed(() => isLoggedIn())
const loginUrl = computed(() => getLoginUrl())

const form = reactive({
  quantity: 1,
  note: '',
  contactPhone: '',
  contactEmail: ''
})
const isManualDelivery = ref(false)

const renderMarkdown = (content) => md.render(content || '')

const getPayPrice = (p) => {
  if (!p) return 0
  if (p.price === 0) return 0
  if (p.discountPrice > 0 && p.discountPrice < p.price) return p.discountPrice
  return p.price
}

const unitPrice = computed(() => getPayPrice(product.value))
const isFree = computed(() => unitPrice.value === 0)

const totalPrice = computed(() => {
  if (!product.value) {
    return 0
  }
  const qty = form.quantity && form.quantity > 0 ? form.quantity : 1
  return unitPrice.value * qty
})

const goBack = () => router.push('/')

const submitOrder = async () => {
  if (!product.value) {
    return
  }
  error.value = ''
  submitting.value = true
  orderResult.value = null
  confirmed.value = false
  deliveredCodes.value = []
  try {
    const payload = {
      productId: product.value.id,
      quantity: form.quantity,
      note: form.note || '',
      contactPhone: form.contactPhone || '',
      contactEmail: form.contactEmail || '',
      notifyEmail: authState.email || ''
    }
    const token = isLoggedIn() ? authState.token : null
    const response = await createOrder(payload, token)
    orderResult.value = response
  } catch (err) {
    error.value = err?.response?.data?.error || '下单失败，请稍候再试'
  } finally {
    submitting.value = false
  }
}

const doConfirm = async () => {
  if (!orderResult.value?.orderId) {
    return
  }
  confirmError.value = ''
  confirming.value = true
  try {
    const result = await confirmOrder(orderResult.value.orderId)
    deliveredCodes.value = result.deliveredCodes || []
    isManualDelivery.value = result.isManual || result.deliveryMode === 'manual'
    confirmed.value = true
  } catch (err) {
    confirmError.value = err?.response?.data?.error || '确认失败，请重试'
  } finally {
    confirming.value = false
  }
}

onMounted(async () => {
  try {
    const list = await fetchProducts()
    product.value = list.find((item) => item.id === route.params.id) || null
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.checkout-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}

.checkout-grid {
  display: grid;
  grid-template-columns: minmax(280px, 1fr) 320px;
  gap: 24px;
  margin-bottom: 20px;
}

.checkout-summary {
  background: rgba(255, 255, 255, 0.8);
  border-radius: var(--radius);
  border: 1px solid var(--line);
  padding: 18px;
  display: flex;
  gap: 18px;
}

.checkout-summary img {
  width: 140px;
  height: 140px;
  object-fit: cover;
  border-radius: 8px;
}

.summary-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkout-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.login-hint a {
  color: var(--accent-2);
  text-decoration: none;
  font-weight: 600;
}

.login-hint a:hover {
  text-decoration: underline;
}

.order-result {
  margin-top: 16px;
  text-align: center;
}

.order-result img {
  max-width: 320px;
  margin: 12px auto;
  width: 100%;
  border-radius: 8px;
  border: 1px solid var(--line);
}

.confirm-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin: 16px 0;
}

.confirmed-badge {
  display: inline-block;
  padding: 6px 16px;
  border-radius: 999px;
  background: linear-gradient(135deg, var(--accent), var(--accent-2));
  color: white;
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 12px;
}

.result-content {
  margin: 12px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.delivery-box {
  width: min(520px, 100%);
  min-height: 120px;
  padding: 14px 16px;
  border-radius: 8px;
  border: 1px solid var(--line);
  background: rgba(255, 255, 255, 0.9);
  color: var(--text);
  font-size: 16px;
  line-height: 1.7;
  resize: none;
}

.error {
  color: #d64848;
  font-size: 15px;
}

.status {
  padding: 24px 0;
  color: var(--muted);
}

.free-price {
  color: #3a9a68;
  font-weight: 900;
}

.require-login-block {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 32px 24px;
  text-align: center;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.6);
}

.require-login-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text);
}

.btn-inline {
  display: inline-block;
  text-decoration: none;
  padding: 10px 28px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
}

.limit-hint {
  color: var(--accent);
}

textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 10px 12px;
  border-radius: 8px;
  border: 1px solid var(--line);
  font-size: 15px;
  font-family: inherit;
  background: rgba(255, 255, 255, 0.9);
  color: var(--text);
  resize: vertical;
}

.contact-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.delivery-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 14px;
  background: rgba(90, 120, 200, 0.08);
  border: 1px solid rgba(90, 120, 200, 0.2);
  border-radius: 8px;
  color: #5a78c8;
  font-size: 14px;
}

.manual-delivery-notice {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: rgba(90, 180, 120, 0.08);
  border: 1px solid rgba(90, 180, 120, 0.25);
  border-radius: 8px;
  color: var(--text);
}

.manual-delivery-title {
  font-size: 16px;
  font-weight: 600;
  color: #3a9a68;
  margin: 0 0 4px 0;
}

@media (max-width: 900px) {
  .checkout-grid {
    grid-template-columns: 1fr;
  }

  .checkout-summary {
    flex-direction: column;
    align-items: center;
  }

  .checkout-summary img {
    width: 100%;
    height: 200px;
  }

  .contact-row {
    grid-template-columns: 1fr;
  }
}
</style>
