import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import DictionariesBehavior from "../../../../core/behavior/dictionaries.behavior";
import tickleBehavior from "../../../../core/behavior/tickle.behavior";
import { getLogisticsMethod } from "../../request"
interface TraceItem {
  status: string;
  time: string;
  desc: string;
  timeKey?: string;
}

interface LogisticsTrack {
  time?: string;
  context?: string;
  areaName?: string;
  status?: string;
  location?: string;
  areaCode?: string | null;
  areaCenter?: any;
  areaPinYin?: string | null;
  statusCode?: any;
}

interface MapPoint {
  latitude: number;
  longitude: number;
}

Page({
  behaviors: [PageContainerBehavior, DictionariesBehavior, tickleBehavior],
  async onLoad(options: any) {
    const id = options?.id;
    if (id) {
      try {
        const res = await getLogisticsMethod(id as any);
        const tracks: LogisticsTrack[] = res?.data?.tracks ?? [];
        const [latestTrack, ...historyTracks] = tracks;
        this.setData({
          showAllTrace: false,
          latestTrace: latestTrack ? this.trackToTraceItem(latestTrack) : ({ status: "", time: "", desc: "" } as TraceItem),
          traceHistory: historyTracks.map((t) => this.trackToTraceItem(t)),
        });
        console.log(tracks, "tracks")
        // 顶部地图背景：只使用 tracks.areaCenter 画轨迹
        this.applyMapFromLogistics(tracks);
      } catch (e: any) {
        this.setData({
          showAllTrace: false,
          latestTrace: { status: "", time: "", desc: "" } as TraceItem,
          traceHistory: [],
        });
      }
    }
    if (options.goods) {
      const goosInfo = JSON.parse(options.goods);
      const expressType = goosInfo.expressType
      this.setData({
        deliveryAddress: goosInfo.address,
        recipientName: goosInfo.liaison,
        recipientPhone: goosInfo.phone,
        expressType,
        carrierName: goosInfo.expressType,
        trackingNo: goosInfo.expressNo,
        goosInfo
      });
    }
  },
  data: {
    // 物流start
    hasMapPosition: false,
    latitude: 0,
    longitude: 0,
    mapScale: 14,
    markers: [] as any[],
    polyline: [] as any[],
    includePoints: [] as MapPoint[],
    // end
    carrierName: "",
    expressType: "",
    trackingNo: "",
    courierPhone: "",
    showAllTrace: false,
    latestTrace: {
      status: "",
      time: "",
      desc: "",
    } as TraceItem,
    traceHistory: [
    ] as TraceItem[],
    deliveryAddress: "",
    recipientName: "",
    recipientPhone: "",
    goosInfo: {}
  },
  // --start
  buildRoutePointsFromTracks(tracks: LogisticsTrack[]): MapPoint[] {
    if (!Array.isArray(tracks) || tracks.length === 0) return [];
    const pts: MapPoint[] = [];
    for (const t of [...tracks].reverse()) {
      if (!t?.areaCenter) continue;
      const [lng, lat] = t.areaCenter.split(",").map((s: string) => Number(s.trim()));
      if (!Number.isNaN(lng) && !Number.isNaN(lat)) {
        pts.push({ latitude: lat, longitude: lng });
      }
    }
    return pts;
  },

  applyMapFromLogistics(tracks: LogisticsTrack[]) {
    // 把每个点转为经纬度
    const routePoints = this.buildRoutePointsFromTracks(tracks || []);
    // 多点的情况
    if (routePoints.length >= 2) {
      // 第一个点的经纬度
      const first = routePoints[0];
      // 最后一个点的经纬度
      const last = routePoints[routePoints.length - 1];
      this.setData({
        // 设置地图的显示状态
        hasMapPosition: true,
        // 设置地图的经纬度
        latitude: (first.latitude + last.latitude) / 2,
        longitude: (first.longitude + last.longitude) / 2,
        // 设置地图的缩放级别
        mapScale: 11,
        // 设置轨迹点
        markers: [
          { id: 1, latitude: first.latitude, longitude: first.longitude, width: 26, height: 26 },
          { id: 2, latitude: last.latitude, longitude: last.longitude, width: 26, height: 26 },
        ],
        // 设置轨迹线
        polyline: [
          {
            points: routePoints,
            color: "#FF6B00AA",
            width: 4,
          },
        ],
        // 设置轨迹点
        includePoints: routePoints,
      });
      return;
    }
    // 单点的情况
    if (routePoints.length === 1) {
      const only = routePoints[0];
      this.setData({
        hasMapPosition: true,
        latitude: only.latitude,
        longitude: only.longitude,
        mapScale: 14,
        markers: [{ id: 1, latitude: only.latitude, longitude: only.longitude, width: 28, height: 28 }],
        polyline: [],
        includePoints: [only],
      });
      return;
    }
    // 无轨迹点的情况
    this.setData({
      hasMapPosition: false,
      markers: [],
      polyline: [],
      includePoints: [],
    });
  },
  // end
  trackToTraceItem(track: LogisticsTrack): TraceItem {
    const time = String(track?.time ?? "");
    return {
      status: String(track?.status ?? ""),
      time,
      desc: String(track?.context ?? ""),
      timeKey: time,
    };
  },
  toggleTraceExpand() {
    this.setData({ showAllTrace: !this.data.showAllTrace });
  },
  onCopyTracking() {
    const no = this.data.trackingNo;
    wx.setClipboardData({
      data: no,
      success: () => {
        wx.showToast({ title: "已复制运单号", icon: "none" });
      },
    });
  },
});
