<template>
  <div class="page order-create">
    <van-nav-bar
      title="我要发单"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="$router.back()"
    />

    <div class="oc-body">
      <!-- 服务类型（从后端动态加载） -->
      <div class="type-tabs card">
        <div
          v-for="s in services"
          :key="s.key"
          class="type-tabs__item"
          :class="{ 'is-active': form.serviceKey === s.key }"
          @click="form.serviceKey = s.key"
        >
          {{ s.name }}
        </div>
        <van-empty v-if="services.length === 0" description="加载中..." />
      </div>

      <!-- 取货地点：单选 -->
      <div class="card block">
        <div class="block__title"><i class="dotf"></i>取货地点</div>
        <div class="pickup-list">
          <div
            v-for="p in pickupOptions"
            :key="p"
            class="pickup-item"
            :class="{ 'is-active': form.from === p }"
            @click="form.from = p"
          >
            <div class="pickup-item__main">
              <div class="pickup-item__name">{{ p }}</div>
              <div class="pickup-item__addr muted">北校区 · 南门快递代取点</div>
            </div>
            <span class="radio" :class="{ 'radio--on': form.from === p }"></span>
          </div>
        </div>
      </div>

      <!-- 送达地点：手动填写 -->
      <div class="card block">
        <div class="block__title"><i class="dott"></i>送达地点</div>
        <van-field
          v-model="form.to"
          class="to-field"
          placeholder="请输入送达地址，如：3 号宿舍楼 512 室 / 图书馆 2 楼自习区"
          maxlength="40"
          clearable
        />
        <div class="quick-addr">
          <span class="quick-addr__label muted">常用</span>
          <span
            v-for="a in commonAddresses"
            :key="a"
            class="chip chip--addr"
            :class="{ 'is-active': form.to === a }"
            @click="form.to = a"
          >
            {{ a }}
          </span>
        </div>
      </div>

      <!-- 物品信息 -->
      <div class="card block">
        <div class="block__title">物品信息</div>
        <div class="chips">
          <span
            v-for="g in goodsTypes"
            :key="g"
            class="chip"
            :class="{ 'is-active': form.goods === g }"
            @click="form.goods = g"
          >
            {{ g }}
          </span>
        </div>
        <van-field
          v-model="form.note"
          rows="2"
          autosize
          type="textarea"
          maxlength="60"
          placeholder="补充说明，如：两个包裹 / 送到寝室楼下即可"
          show-word-limit
        />
      </div>

      <!-- 期望时间 -->
      <div class="card block">
        <div class="block__title">期望送达</div>
        <div class="chips">
          <span
            v-for="t in timeOptions"
            :key="t"
            class="chip"
            :class="{ 'is-active': form.time === t }"
            @click="form.time = t"
          >
            {{ t }}
          </span>
        </div>
      </div>

      <!-- 悬赏 -->
      <div class="card block">
        <div class="block__title">
          悬赏加价
          <span class="block__tip muted">悬赏越高，接单越快</span>
        </div>
        <div class="rewards">
          <span
            v-for="r in rewardOptions"
            :key="r"
            class="reward-chip"
            :class="{ 'is-active': form.reward === r }"
            @click="form.reward = r"
          >
            +{{ r }}元
          </span>
        </div>
      </div>

      <div class="fee-detail card">
        <div class="fee-detail__row">
          <span class="muted">基础配送费</span><span>¥{{ baseFee.toFixed(2) }}</span>
        </div>
        <div class="fee-detail__row">
          <span class="muted">悬赏加价</span><span>¥{{ form.reward.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 底部提交栏 -->
    <div class="submit-bar">
      <div class="submit-bar__price">
        <span class="muted">合计</span>
        <span class="price">¥{{ total.toFixed(2) }}</span>
      </div>
      <van-button
        class="submit-bar__btn"
        type="primary"
        round
        block
        @click="submit"
      >
        立即发单
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showLoadingToast, closeToast } from 'vant'
import { orderTypes, goodsTypes } from '../data/mock.js'
import { api } from '../api/index.js'
import { ensureLogin } from '../store/session.js'

const router = useRouter()

// 🔧 服务类型列表（从后端获取）
const services = ref([])

// 获取当前选中的服务名称（type 字段）
const type = computed(() => {
  const svc = services.value.find(s => s.key === form.serviceKey)
  return svc ? svc.name : ''
})

const timeOptions = ['尽快送达', '30 分钟内', '1 小时内', '指定时间']
const rewardOptions = [0, 2, 3, 5, 8]
// 取货点（单选，目前仅一个，后续可扩展或由后端下发）
const pickupOptions = ['北校区南门菜鸟驿站']
// 常用送达地址（点击带入输入框）
const commonAddresses = ['3 号宿舍楼 512', '图书馆 2 楼自习区', '教学楼 B305', '一号食堂门口']

const form = reactive({
  // 🔧 存储 serviceKey（从后端获取）
  serviceKey: '', 
  from: pickupOptions[0],
  to: '',
  goods: goodsTypes[0],
  note: '',
  time: timeOptions[0],
  reward: 2
})

// 计算当前选中的服务对象
const selectedService = computed(() => {
  return services.value.find(s => s.key === form.serviceKey)
})

// 基础费（从后端服务配置读取）
const baseFee = computed(() => {
  if (selectedService.value) return selectedService.value.base || 4
  return 4
})
const total = computed(() => baseFee.value + form.reward)

async function submit() {
  if (!form.from || !form.to) {
    showToast('请先完善取货和送达地址')
    return
  }
  showLoadingToast({ message: '提交中…', forbidClick: true, duration: 0 })
  try {
    const profile = await ensureLogin()
    const payload = {
      customerId: profile.id,
      customerName: profile.name,
      customerPhone: profile.phone,
      serviceKey: form.serviceKey,
      from: form.from,
      to: form.to,
      goods: form.goods,
      note: form.note,
      reward: form.reward
    }
    await api.createOrder(payload)
    closeToast()
    showSuccessToast('发单成功，正在为您匹配骑手')
    setTimeout(() => router.push('/orders'), 1000)
  } catch (e) {
    closeToast()
    showToast(e.message || '下单失败，请重试')
  }
}
</script>

<style scoped>
.order-create {
  background: var(--brand-bg);
  min-height: 100vh;
  padding-bottom: 80px;
}
:deep(.van-nav-bar) {
  background: linear-gradient(120deg, #1677ff, #0958d9);
}
:deep(.van-nav-bar__title),
:deep(.van-nav-bar .van-icon),
:deep(.van-nav-bar__text) {
  color: #fff !important;
}
.oc-body {
  padding: 12px 14px;
}
.card {
  margin-bottom: 12px;
}

/* 服务类型 */
.type-tabs {
  display: flex;
  padding: 6px;
  gap: 6px;
}
.type-tabs__item {
  flex: 1;
  text-align: center;
  padding: 9px 0;
  font-size: 13px;
  border-radius: 9px;
  color: var(--brand-text-secondary);
}
.type-tabs__item.is-active {
  background: var(--brand-primary-light);
  color: var(--brand-primary);
  font-weight: 700;
}

/* 地址 */
.addr {
  padding: 6px 14px;
  position: relative;
}
.addr__row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 14px 0;
}
.addr__main {
  flex: 1;
  min-width: 0;
}
.addr__label {
  font-size: 12px;
  color: var(--brand-text-tertiary);
}
.addr__val {
  margin-top: 3px;
  font-size: 15px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.addr__val.ph {
  color: var(--brand-text-tertiary);
  font-weight: 400;
}
.addr__go {
  color: var(--brand-text-tertiary);
  font-size: 18px;
}
.addr__swap {
  position: absolute;
  right: 46px;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: var(--brand-primary-light);
  color: var(--brand-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}
.dotf,
.dott {
  width: 9px;
  height: 9px;
  border-radius: 50%;
  flex: 0 0 9px;
}
.dotf {
  background: #00b42a;
}
.dott {
  background: var(--brand-primary);
}

/* 常用地址快捷 */
.quick-addr {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
}
.quick-addr__label {
  font-size: 12px;
}
.chip--addr {
  font-size: 12px;
  padding: 6px 12px;
}

/* 取货点单选 */
.pickup-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.pickup-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 14px;
  border: 1px solid var(--brand-border);
  border-radius: 10px;
  background: #fff;
}
.pickup-item.is-active {
  border-color: var(--brand-primary);
  background: var(--brand-primary-lighter, #f2f7ff);
}
.pickup-item__main {
  flex: 1;
  min-width: 0;
}
.pickup-item__name {
  font-size: 15px;
  font-weight: 600;
  color: var(--brand-text);
}
.pickup-item__addr {
  margin-top: 2px;
  font-size: 12px;
}
.radio {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 2px solid var(--brand-border);
  flex: 0 0 18px;
  position: relative;
}
.radio--on {
  border-color: var(--brand-primary);
}
.radio--on::after {
  content: '';
  position: absolute;
  inset: 3px;
  border-radius: 50%;
  background: var(--brand-primary);
}

/* block */
.block {
  padding: 14px;
}
.block__title {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.block__tip {
  font-size: 12px;
  font-weight: 400;
}
.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 6px;
}
.chip {
  padding: 7px 14px;
  border-radius: 8px;
  font-size: 13px;
  background: var(--brand-bg);
  color: var(--brand-text-secondary);
  border: 1px solid transparent;
}
.chip.is-active {
  background: var(--brand-primary-light);
  color: var(--brand-primary);
  border-color: var(--brand-primary);
  font-weight: 600;
}
:deep(.van-field) {
  background: var(--brand-bg);
  border-radius: 8px;
  margin-top: 4px;
}

/* 悬赏 */
.rewards {
  display: flex;
  gap: 10px;
}
.reward-chip {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  border-radius: 9px;
  font-size: 14px;
  font-weight: 600;
  background: var(--brand-bg);
  color: var(--brand-text-secondary);
  border: 1px solid transparent;
}
.reward-chip.is-active {
  background: linear-gradient(135deg, #fff1e8, #fff);
  color: #fa541c;
  border-color: #fa541c;
}

/* 费用明细 */
.fee-detail {
  padding: 12px 14px;
}
.fee-detail__row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  padding: 4px 0;
}

/* 提交栏 */
.submit-bar {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 480px;
  background: #fff;
  border-top: 1px solid var(--brand-border);
  padding: 10px 14px calc(10px + env(safe-area-inset-bottom));
  display: flex;
  align-items: center;
  gap: 14px;
  z-index: 50;
}
.submit-bar__price {
  display: flex;
  flex-direction: column;
  white-space: nowrap;
}
.submit-bar__price .price {
  font-size: 20px;
}
.submit-bar__btn {
  flex: 1;
}
</style>
