<template>
  <view class="spec-panel-mask" @click.self="$emit('close')">
    <view class="spec-panel" @click.stop>
      <!-- 滚动区域 -->
      <scroll-view class="spec-panel__scroll" scroll-y>
        <!-- 加载中 -->
        <view v-if="loadingConfig" class="spec-panel__loading">加载中...</view>

        <template v-else-if="config">
          <!-- 成色选择 -->
          <view class="spec-group" v-if="config.fineness.length">
            <text class="spec-group__label">成 色</text>
            <view class="spec-group__options">
              <view v-for="item in config.fineness" :key="item" class="spec-option"
                :class="{ 'spec-option--active': selected.fineness === item }"
                @click="selectOption('fineness', item)">{{ item }}</view>
            </view>
          </view>

          <!-- 主石选择 -->
          <view class="spec-group" v-if="config.mainStone.length">
            <text class="spec-group__label">主 石</text>
            <view class="spec-group__options">
              <view v-for="item in config.mainStone" :key="item" class="spec-option"
                :class="{ 'spec-option--active': selected.mainStone === item }"
                @click="selectOption('mainStone', item)">{{ item }}</view>
            </view>
          </view>

          <!-- 手寸选择 -->
          <view class="spec-group" v-if="config.ringSize.length">
            <text class="spec-group__label">手 寸</text>
            <view class="spec-group__options">
              <view v-for="item in config.ringSize" :key="item" class="spec-option"
                :class="{ 'spec-option--active': selected.ringSize === item }"
                @click="selectOption('ringSize', item)">{{ item }}</view>
            </view>
          </view>
        </template>

        <!-- 规格数据列表 -->
        <view v-if="loadingData" class="spec-panel__loading">查询中...</view>
        <view v-else-if="specDataList.length" class="spec-data-list">
          <view v-for="spec in specDataList" :key="spec.id" class="spec-data-card"
            :class="{ 'spec-data-card--selected': selectedSpecs.has(spec.id) }"
            @click="toggleSelect(spec)">
            <!-- 卡片标题 -->
            <view class="spec-card__header">
              <text class="spec-card__title">{{ spec.modelName }}  {{ spec.fineness }}/外径</text>
              <text class="spec-card__gold-price">金价 ¥{{ spec.goldPrice }}</text>
            </view>
            <!-- 两列数据 -->
            <view class="spec-card__body">
              <view class="spec-card__col">
                <view class="spec-card__row">
                  <text class="spec-card__label">型号名称</text>
                  <text class="spec-card__value">{{ spec.modelName }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">金料总重</text>
                  <text class="spec-card__value">{{ spec.goldTotalWeight }}g</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">金料净重</text>
                  <text class="spec-card__value">{{ spec.goldNetWeight }}g</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">金耗</text>
                  <text class="spec-card__value">{{ spec.goldLoss }}g</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">金值</text>
                  <text class="spec-card__value">¥{{ spec.goldValue }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">主石数量</text>
                  <text class="spec-card__value">{{ spec.mainStoneCount }}粒</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">主石石重</text>
                  <text class="spec-card__value">{{ spec.mainStoneWeight }}ct</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">主石单价</text>
                  <text class="spec-card__value">¥{{ spec.mainStoneUnitPrice }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">主石金额</text>
                  <text class="spec-card__value">¥{{ spec.mainStoneAmount }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">配件金额</text>
                  <text class="spec-card__value">¥{{ spec.accessoryAmount }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">总工费</text>
                  <text class="spec-card__value">¥{{ spec.totalLaborCost }}</text>
                </view>
              </view>
              <view class="spec-card__col">
                <view class="spec-card__row">
                  <text class="spec-card__label">成色</text>
                  <text class="spec-card__value">{{ spec.fineness }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">损耗</text>
                  <text class="spec-card__value">{{ spec.loss }}%</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">主石</text>
                  <text class="spec-card__value">{{ spec.mainStone }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">手寸</text>
                  <text class="spec-card__value">{{ spec.ringSize }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">金价</text>
                  <text class="spec-card__value">¥{{ spec.goldPrice }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">副石数量</text>
                  <text class="spec-card__value">{{ spec.sideStoneCount }}粒</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">副石石重</text>
                  <text class="spec-card__value">{{ spec.sideStoneWeight }}ct</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">副石单价</text>
                  <text class="spec-card__value">¥{{ spec.sideStoneUnitPrice }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">副石金额</text>
                  <text class="spec-card__value">¥{{ spec.sideStoneAmount }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">加工工费</text>
                  <text class="spec-card__value">¥{{ spec.processingFee }}</text>
                </view>
                <view class="spec-card__row">
                  <text class="spec-card__label">镶石工费</text>
                  <text class="spec-card__value">¥{{ spec.settingFee }}</text>
                </view>
              </view>
            </view>
            <!-- 总价行 -->
            <view class="spec-card__footer">
              <text class="spec-card__total-label">金工石总金额</text>
              <text class="spec-card__total-price">¥{{ spec.totalPrice }}</text>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="spec-panel__bottom">
        <view class="spec-panel__cart-btn"
          :class="{ 'spec-panel__cart-btn--disabled': selectedSpecs.size === 0 }"
          @click="handleAddToCart">
          加入购物车<text v-if="selectedSpecs.size">({{ selectedSpecs.size }})</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { DetailParameterConfig, SpecData } from '../types'
import { getProductSpecs, getSpecDataList } from '../api/product'
import { useCartStore } from '../store/cart'

const props = defineProps<{ productId: number }>()
const emit = defineEmits<{ close: [] }>()

const config = ref<DetailParameterConfig | null>(null)
const loadingConfig = ref(false)
const loadingData = ref(false)
const specDataList = ref<SpecData[]>([])
const selectedSpecs = ref<Map<number, SpecData>>(new Map())
const cartStore = useCartStore()

const selected = reactive({ fineness: '', mainStone: '', ringSize: '' })

function selectOption(key: 'fineness' | 'mainStone' | 'ringSize', item: string) {
  selected[key] = selected[key] === item ? '' : item
  if (selected.fineness || selected.mainStone || selected.ringSize) {
    querySpecData()
  } else {
    specDataList.value = []
  }
}

function toggleSelect(spec: SpecData) {
  if (selectedSpecs.value.has(spec.id)) {
    selectedSpecs.value.delete(spec.id)
  } else {
    selectedSpecs.value.set(spec.id, spec)
  }
  selectedSpecs.value = new Map(selectedSpecs.value)
}

function handleAddToCart() {
  if (selectedSpecs.value.size === 0) return
  selectedSpecs.value.forEach((spec) => {
    cartStore.addToCart({
      id: Date.now() + spec.id,
      userId: 0,
      productId: props.productId,
      specDataId: spec.id,
      quantity: 1,
      product: {} as any,
      specData: spec,
      checked: true,
    })
  })
  uni.showToast({ title: `已加入${selectedSpecs.value.size}件`, icon: 'success' })
  selectedSpecs.value = new Map()
  emit('close')
}

onMounted(async () => {
  loadingConfig.value = true
  try { config.value = await getProductSpecs(props.productId) }
  catch { /* handled */ }
  finally { loadingConfig.value = false }
})

async function querySpecData() {
  loadingData.value = true
  try {
    specDataList.value = await getSpecDataList(props.productId, {
      fineness: selected.fineness || undefined,
      mainStone: selected.mainStone || undefined,
      ringSize: selected.ringSize || undefined,
    })
  } catch { /* handled */ }
  finally { loadingData.value = false }
}
</script>

<style scoped>
.spec-panel-mask {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5); z-index: 999;
  display: flex; align-items: flex-end;
}
.spec-panel {
  background: #fff; width: 100%; height: 85vh;
  border-radius: 24rpx 24rpx 0 0;
  display: flex; flex-direction: column;
}
.spec-panel__scroll {
  flex: 1; padding: 32rpx 28rpx 0; overflow: hidden;
}
.spec-panel__loading {
  text-align: center; padding: 60rpx 0; color: #999; font-size: 28rpx;
}

/* 规格分组 */
.spec-group { margin-bottom: 32rpx; }
.spec-group__label {
  font-size: 30rpx; color: #333; font-weight: 600;
  margin-bottom: 20rpx; display: block; letter-spacing: 8rpx;
}
.spec-group__options { display: flex; flex-wrap: wrap; gap: 16rpx; }
.spec-option {
  padding: 14rpx 32rpx; font-size: 26rpx; color: #333;
  background: #f5f5f5; border-radius: 8rpx; border: 2rpx solid #f5f5f5;
}
.spec-option--active {
  color: #e91e63; background: #fce4ec; border-color: #e91e63;
}

/* 规格数据卡片 */
.spec-data-list { padding-bottom: 20rpx; }
.spec-data-card {
  border: 2rpx solid #f0e0e0; border-radius: 16rpx;
  padding: 24rpx; margin-bottom: 20rpx; background: #fff;
}
.spec-data-card--selected {
  border-color: #e91e63; background: #fff5f7;
}
.spec-card__header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 16rpx; padding-bottom: 16rpx; border-bottom: 1rpx solid #f0f0f0;
}
.spec-card__title { font-size: 26rpx; color: #333; font-weight: 600; }
.spec-card__gold-price { font-size: 24rpx; color: #666; }
.spec-card__body { display: flex; gap: 12rpx; }
.spec-card__col { flex: 1; }
.spec-card__row { display: flex; justify-content: space-between; padding: 5rpx 0; }
.spec-card__label { font-size: 23rpx; color: #999; flex-shrink: 0; }
.spec-card__value { font-size: 23rpx; color: #333; text-align: right; }
.spec-card__footer {
  display: flex; justify-content: flex-end; align-items: center;
  margin-top: 16rpx; padding-top: 16rpx; border-top: 1rpx solid #f0f0f0; gap: 12rpx;
}
.spec-card__total-label { font-size: 26rpx; color: #e91e63; }
.spec-card__total-price { font-size: 32rpx; color: #e91e63; font-weight: bold; }

/* 底部操作栏 */
.spec-panel__bottom {
  padding: 20rpx 28rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #fff; box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}
.spec-panel__cart-btn {
  background: linear-gradient(to right, #FFB6C8, #FF6D9B);
  color: #fff; text-align: center; padding: 24rpx 0;
  border-radius: 44rpx; font-size: 30rpx; font-weight: 500;
}
.spec-panel__cart-btn--disabled {
  background: linear-gradient(to right, #ddd, #ccc);
}
</style>
