<script setup lang="ts">
import { computed, ref } from 'vue';
import { notification } from 'ant-design-vue';
import { DownOutlined, UpOutlined, StarOutlined } from '@ant-design/icons-vue';

const props = defineProps<{
  data?: any;
}>();

const showAllLogistics = ref(false);

const expressTypeText: Record<string, string> = {
  '0': '邮政速递',
  '1': '顺丰速运',
  '2': '京东快递',
  '3': '中通快递',
  '4': '圆通速递',
  '5': '申通快递',
  '6': '韵达快递',
  '7': '极兔速递',
};

// 假数据定义
const mockData = {
  receiptType: '0', // 0-快递 1-线下取货
  expressType: '4', // 圆通
  expressNo: 'YT7596102092888',
  liaison: '何美丹',
  phone: '158****5026',
  provinceName: '浙江省',
  cityName: '杭州市',
  areaName: '西湖区',
  detailAddress: '文新街道 文新街道西湖区金成花园13幢一单元602',
  sameExpress: [
    {
      conditioningProgramPhoto: 'https://img0.baidu.com/it/u=3025010615,2026135017&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      conditioningProgramName: '元气茶',
      convertDose: 10,
      convertUnit: '包',
      unitPrice: 32,
      totalMeasure: 3,
    },
    {
      conditioningProgramPhoto: 'https://img1.baidu.com/it/u=1067201099,2862800611&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      conditioningProgramName: '芡实米仁燕麦粥',
      convertDose: 1,
      convertUnit: '袋',
      unitPrice: 1.5,
      totalMeasure: 21,
    }
  ]
};

// 当前显示的数据
const displayData = computed(() => {
  return {
    ...mockData,
    // ...(props.data || {})
  };
});

// 物流信息
const logisticsInfo = computed(() => {
  const d = displayData.value;
  return {
    expressName: expressTypeText[d.expressType || ''] || '圆通速递',
    trackingNumber: d.expressNo || '无单号',
    recipientName: d.liaison || '',
    recipientPhone: d.phone || '',
    recipientAddress: (d.provinceName || '') + ' ' + (d.cityName || '') + ' ' + (d.areaName || '') + ' ' + (d.detailAddress || '')
  };
});

type LogisticsTimelineItem = {
  title: string;
  time: string;
  detail: string;
};

const mockLogisticsTimeline: LogisticsTimelineItem[] = [
  {
    title: '已签收',
    time: '01-09 19:15',
    detail: '您已在杭州金成花园15幢4号店完成取件，感谢使用菜鸟驿站，期待再次为您服务。',
  },
  {
    title: '待取件',
    time: '01-09 16:11',
    detail: '您的快件已暂存在杭州金成花园15幢4号店菜鸟驿站，请凭取货码及时领取。如有疑问请联系15067159925',
  },
  {
    title: '运输中',
    time: '01-08 13:26',
    detail: '快件离开杭州分拨中心，正在发往目的地站点。',
  },
  {
    title: '包裹已揽收',
    time: '01-08 09:42',
    detail: '快递员已揽收您的包裹，正在安排发出。',
  },
];

function normalizeLogisticsItem(item: any): LogisticsTimelineItem | null {
  if (!item || typeof item !== 'object') return null;
  const time = String(item.time ?? item.acceptTime ?? item.ftime ?? item.createTime ?? item.updateTime ?? '').trim();
  const title = String(item.title ?? item.status ?? item.statusName ?? item.statusDesc ?? '').trim();
  const detail = String(item.content ?? item.context ?? item.remark ?? item.description ?? item.message ?? '').trim();
  const fallbackTitle = detail || title;
  if (!time && !fallbackTitle && !detail) return null;
  return {
    title: fallbackTitle || '-',
    time,
    detail: detail && detail !== fallbackTitle ? detail : '',
  };
}

const timelineData = computed<LogisticsTimelineItem[]>(() => {
  const source = displayData.value;
  const listCandidate =
    source?.expressDetails ??
    source?.logisticsDetails ??
    source?.logisticsList ??
    source?.expressRouteList ??
    source?.expressRoutes ??
    source?.traces ??
    source?.traceList ??
    source?.routeList ??
    source?.tracks ??
    [];
  if (!Array.isArray(listCandidate) || listCandidate.length === 0) return mockLogisticsTimeline;
  const normalizedList = listCandidate
    .map((item: any) => normalizeLogisticsItem(item))
    .filter((item): item is LogisticsTimelineItem => Boolean(item));
  return normalizedList.length > 0 ? normalizedList : mockLogisticsTimeline;
});

const visibleTimeline = computed(() => {
  if (showAllLogistics.value) return timelineData.value;
  return timelineData.value.slice(0, 2);
});

const canExpandLogistics = computed(() => timelineData.value.length > 2);

function toggleLogisticsExpand() {
  showAllLogistics.value = !showAllLogistics.value;
}

// 复制物流信息
function handleCopyTracking() {
  const trackingNumber = logisticsInfo.value.trackingNumber;
  if (trackingNumber) {
    navigator.clipboard.writeText(trackingNumber).then(() => {
      notification.success({ message: '复制成功' });
    }).catch(() => {
      notification.error({ message: '复制失败' });
    });
  }
}

// 包裹商品
const packageItems = computed(() => {
  return displayData.value.sameExpress ?? []
});
</script>

<template>
  <div class="logistics-details-container">
    <div v-if="displayData.receiptType === '0'">
      <!-- 通道/单号 -->
      <div class="header-line">
        <div class="header-left">
          <div class="express-logo">YT</div>
          <span class="express-name">{{ logisticsInfo.expressName }}</span>
          <span class="tracking-no">{{ logisticsInfo.trackingNumber }}</span>
          <a @click="handleCopyTracking" class="copy-link">复制</a>
        </div>
        <div class="header-right">
          联系电话：95554
        </div>
      </div>

      <!-- 物流线 -->
      <div class="timeline-box">
        <div class="timeline-row" v-for="(item, index) in visibleTimeline" :key="index">
          <div class="dot-col">
            <span class="dot" :class="{ 'dot-active': index === 0 }"></span>
            <div class="line" v-if="index !== visibleTimeline.length - 1 || canExpandLogistics"></div>
          </div>
          <div class="content-col">
            <div class="status-title" :class="{ 'text-active': index === 0 }">
              <span class="title-text">{{ item.title }}</span>
              <span class="time-text">{{ item.time }}</span>
            </div>
            <div class="status-detail">{{ item.detail }}</div>
          </div>
        </div>

        <!-- 展开按钮 -->
        <div class="expand-row" v-if="canExpandLogistics">
          <div class="dot-col">
            <span class="dot"></span>
          </div>
          <div class="content-col">
            <a @click="toggleLogisticsExpand" class="expand-link">
              {{ showAllLogistics ? '收起更多物流明细' : '展开更多物流明细' }}
              <DownOutlined :class="{ 'rotate-180': showAllLogistics }" class="arrow-icon" />
            </a>
          </div>
        </div>
      </div>

      <!-- 收货人行 -->
      <div class="recipient-line">
        <span class="receive-badge">收</span>
        <span class="recipient-text">
          {{ logisticsInfo.recipientName }}， {{ logisticsInfo.recipientPhone }}， {{ logisticsInfo.recipientAddress }}
        </span>
      </div>

      <!-- 包裹商品 -->
      <div class="package-items-wrapper" v-if="packageItems.length > 0">
        <div class="package-header">
          <StarOutlined class="star-icon" />
          <span class="title">包裹内商品</span>
        </div>
        <div class="package-list">
          <div class="package-item" v-for="(item, index) in packageItems" :key="index">
            <div class="item-thumb">
              <img v-if="item.conditioningProgramPhoto" :src="item.conditioningProgramPhoto" />
              <div v-else class="img-placeholder">📦</div>
            </div>
            <div class="item-main">
              <div class="item-name">{{ item.conditioningProgramName }}</div>
              <div class="item-spec">{{ item.convertDose }}{{ item.convertUnit }}</div>
            </div>
            <div class="item-side">
              <div class="item-price">¥{{ item.unitPrice }}</div>
              <div class="item-qty">x{{ item.totalMeasure }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 线下 -->
    <div v-else-if="displayData.receiptType === '1'">
      <div class="offline-box">线下取货模式</div>
    </div>

    <div v-else class="empty-box">暂无物流数据</div>
  </div>
</template>

<style scoped lang="scss">
.logistics-details-container {
  padding: 10px;
  background: #fff;
  color: #333;
  font-size: 14px;
}

/* Header Line */
.header-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .express-logo {
      width: 24px;
      height: 24px;
      background: #722ed1;
      color: #fff;
      border-radius: 50%;
      text-align: center;
      line-height: 24px;
      font-size: 10px;
      font-weight: bold;
    }

    .express-name {
      font-weight: bold;
    }

    .tracking-no {
      margin-left: 4px;
    }

    .copy-link {
      color: #999;
      font-size: 13px;
      cursor: pointer;
      text-decoration: none;

      &:hover {
        color: #666;
      }
    }
  }

  .header-right {
    color: #999;
    font-size: 13px;
  }
}

/* Timeline */
.timeline-box {
  margin-bottom: 24px;
}

.timeline-row {
  display: flex;
  gap: 12px;
}

.dot-col {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 16px;

  .dot {
    width: 10px;
    height: 10px;
    background: #e8e8e8;
    border-radius: 50%;
    margin-top: 6px;
    flex-shrink: 0;
  }

  .dot-active {
    background: #FF6A00;
    box-shadow: 0 0 0 4px rgba(255, 106, 0, 0.1);
  }

  .line {
    width: 1px;
    background: #f0f0f0;
    flex: 1;
    min-height: 40px;
  }
}

.content-col {
  flex: 1;
  padding-bottom: 24px;

  .status-title {
    margin-bottom: 8px;
    font-size: 15px;
    display: flex;
    gap: 10px;
    color: #666;

    &.text-active {
      color: #FF6A00;
      font-weight: 500;
    }

    .time-text {
      font-size: 14px;
    }
  }

  .status-detail {
    font-size: 14px;
    color: #999;
    line-height: 1.6;
  }
}

.expand-row {
  display: flex;
  gap: 12px;
  margin-top: -10px;

  .expand-link {
    color: #666;
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;

    &:hover {
      color: #333;
    }

    .arrow-icon {
      font-size: 10px;
      transition: transform 0.3s;
    }
    .rotate-180 {
      transform: rotate(180deg);
    }
  }
}

/* Recipient */
.recipient-line {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;

  .receive-badge {
    width: 20px;
    height: 20px;
    background: #fff1f0;
    border: 1px solid #ff4d4f;
    color: #ff4d4f;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    flex-shrink: 0;
  }

  .recipient-text {
    font-weight: 500;
    color: #333;
  }
}

/* Package Items */
.package-items-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 2px;
  padding: 16px;

  .package-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;

    .star-icon {
      color: #ccc;
      font-size: 18px;
    }

    .title {
      font-weight: bold;
      font-size: 15px;
    }
  }
}

.package-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 0;
  
  &:not(:last-child) {
    border-bottom: 1px solid #f5f5f5;
  }

  .item-thumb {
    width: 60px;
    height: 60px;
    background: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .img-placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      font-size: 24px;
    }
  }

  .item-main {
    flex: 1;

    .item-name {
      font-weight: 500;
      font-size: 15px;
      margin-bottom: 6px;
    }

    .item-spec {
      color: #999;
      font-size: 13px;
    }
  }

  .item-side {
    text-align: right;

    .item-price {
      font-size: 15px;
      margin-bottom: 4px;
    }

    .item-qty {
      color: #999;
      font-size: 14px;
    }
  }
}

.offline-box, .empty-box {
  padding: 40px;
  text-align: center;
  color: #999;
}
</style>
