<template>
  <view class="logistics-page">
    <view class="logistics-header">
      <view class="product-info">
        <image class="product-image" :src="productImage" mode="aspectFill"></image>
        <view class="info-right">
          <text class="status-text">{{ logisticsStatus }}</text>
          <text class="courier-name">{{ courierName }}: {{ trackingNo }}</text>
          <text class="phone-text">官方电话: {{ courierPhone }}</text>
        </view>
      </view>
    </view>

    <view class="logistics-body">
      <view class="track-list">
        <view 
          v-for="(item, index) in trackList" 
          :key="index" 
          class="track-item"
          :class="{ first: index === 0 }"
        >
          <view class="node-icon">
            <view class="dot"></view>
            <view class="line" v-if="index !== trackList.length - 1"></view>
          </view>
          <view class="node-content">
            <text class="track-desc">{{ item.desc }}</text>
            <text class="track-time">{{ item.time }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { supabaseService } from '@/utils/supabaseService.uts'

const orderId = ref('')
const productImage = ref('/static/product1.jpg')
const logisticsStatus = ref('暂无物流信息')
const courierName = ref('')
const courierPhone = ref('')
const trackingNo = ref('')

type TrackItem = {
  desc: string,
  time: string
}

const trackList = ref<TrackItem[]>([])

// 加载物流信息函数 - 必须在 onLoad 之前定义
const loadLogisticsInfo = async () => {
    if (orderId.value == '') return
    
    try {
        console.log('[logistics] 开始加载物流信息, orderId:', orderId.value)
        const order = await supabaseService.getOrderDetail(orderId.value)
        console.log('[logistics] 获取订单结果:', order != null ? '成功' : '失败')
        
        if (order != null) {
            const orderStr = JSON.stringify(order)
            console.log('[logistics] 订单JSON:', orderStr)
            const orderParsed = JSON.parse(orderStr)
            if (orderParsed == null) {
                console.error('[logistics] 解析订单数据失败')
                return
            }
            const orderObj = orderParsed as UTSJSONObject
            
            // 获取物流信息
            const trackingNoVal = orderObj.getString('tracking_no')
            const carrierNameVal = orderObj.getString('carrier_name')
            const shippingStatus = orderObj.getNumber('shipping_status')
            
            console.log('[logistics] tracking_no:', trackingNoVal)
            console.log('[logistics] carrier_name:', carrierNameVal)
            console.log('[logistics] shipping_status:', shippingStatus)
            
            if (trackingNoVal != null && trackingNoVal != '') {
                trackingNo.value = trackingNoVal
            } else {
                console.log('[logistics] 物流单号为空，订单可能未发货')
                // 物流单号为空时显示提示
                trackingNo.value = '暂无物流单号'
                logisticsStatus.value = '商家未填写物流信息'
            }
            
            if (carrierNameVal != null && carrierNameVal != '') {
                courierName.value = carrierNameVal
                // 根据快递公司设置电话
                if (carrierNameVal.includes('顺丰')) {
                    courierPhone.value = '95338'
                } else if (carrierNameVal.includes('中通')) {
                    courierPhone.value = '95311'
                } else if (carrierNameVal.includes('圆通')) {
                    courierPhone.value = '95554'
                } else if (carrierNameVal.includes('韵达')) {
                    courierPhone.value = '95546'
                } else if (carrierNameVal.includes('申通')) {
                    courierPhone.value = '95543'
                } else {
                    courierPhone.value = ''
                }
            }
            
            // 根据发货状态设置物流状态
            if (shippingStatus == 2) {
                logisticsStatus.value = '已签收'
            } else if (shippingStatus == 1) {
                logisticsStatus.value = '运输中'
            } else {
                logisticsStatus.value = '待发货'
            }
            
            // 获取商品图片
            const itemsRaw = orderObj.get('ml_order_items')
            if (itemsRaw != null && Array.isArray(itemsRaw)) {
                const items = itemsRaw as any[]
                if (items.length > 0) {
                    const firstItem = items[0]
                    const itemStr = JSON.stringify(firstItem)
                    const itemParsed = JSON.parse(itemStr)
                    if (itemParsed != null) {
                        const itemObj = itemParsed as UTSJSONObject
                        const imgUrl = itemObj.getString('image_url')
                        if (imgUrl != null && imgUrl != '') {
                            productImage.value = imgUrl
                        }
                    }
                }
            }
            
            // 构建物流轨迹（如果有发货时间）
            const shippedAt = orderObj.getString('shipped_at')
            if (shippedAt != null && shippedAt != '') {
                const trackItem: TrackItem = {
                    desc: '商家已发货，等待快递揽收',
                    time: shippedAt
                }
                trackList.value.push(trackItem)
            }
            
            // 如果已签收，添加签收信息
            const deliveredAt = orderObj.getString('delivered_at')
            if (deliveredAt != null && deliveredAt != '') {
                const trackItem: TrackItem = {
                    desc: '快件已签收',
                    time: deliveredAt
                }
                trackList.value.unshift(trackItem)
                logisticsStatus.value = '已签收'
            }
        }
    } catch (e) {
        console.error('加载物流信息失败:', e)
    }
}

onLoad((options) => {
    if (options == null) return
  const optionsObj = options as UTSJSONObject
  const orderIdValue = optionsObj.getString('orderId') ?? ''
  if (orderIdValue != '') {
    orderId.value = orderIdValue
        loadLogisticsInfo()
    }
})

onMounted(() => {
    // 逻辑已移到 onLoad
})
</script>

<style scoped>
.logistics-page {
  /* min-height: 100%; */
  flex: 1;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

.logistics-header {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
  background-color: #eee;
}

.info-right {
  display: flex;
  flex-direction: column;
}

.status-text {
  font-size: 16px;
  color: #ff5000;
  font-weight: bold;
  margin-bottom: 5px;
}

.courier-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.phone-text {
  font-size: 12px;
  color: #999;
}

.logistics-body {
  background-color: #fff;
  padding: 20px 15px;
}

.track-list {
  display: flex;
  flex-direction: column;
}

.track-item {
  display: flex;
  position: relative;
  padding-bottom: 25px;
}

.track-item:last-child {
  padding-bottom: 0;
}

.node-icon {
  width: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 15px;
}

.dot {
  width: 8px;
  height: 8px;
    border-radius: 4px;
}

.first .dot {
  background-color: #ff5000;
  width: 12px;
  height: 12px;
  margin-top: 4px;
  box-shadow: 0 0 0 4px rgba(255, 80, 0, 0.2);
}

.line {
  width: 1px;
  background-color: #eee;
  flex: 1;
  margin-top: 2px;
}

.node-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.track-desc {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 5px;
}

.first .track-desc {
  color: #ff5000;
  font-weight: bold;
}

.track-time {
  font-size: 12px;
  color: #999;
}
</style>

