<template>
  <el-drawer :model-value="visible" title="物流信息" size="50%" style="--el-drawer-padding-primary: 0"
    :before-close="close">
    <div class="h-full bg-[#f2f3f4] overflow-y-auto pb-20px">
      <div class="bg-white p-15px">
        <div class="font-bold text-16px mb-10px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          收货信息
        </div>
        <div class="text-14px text-gray-700 leading-28px">
          <div>
            收货人：<span class="text-gray-900">{{ detail.receiveName || "--" }}</span>
            <span class="ml-10px text-gray-900">{{ detail.receivePhone || "" }}</span>
          </div>
          <div class="flex">
            <span class="flex-shrink-0">收货地址：</span>
            <span class="text-gray-900">{{ recipientAddress }}</span>
          </div>
        </div>
      </div>

      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-10px flex items-center justify-between">
          <div class="flex items-center">
            <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
            物流单号
          </div>
          <el-button v-if="detail.shippingNo" link type="primary" @click="copy(detail.shippingNo)">复制</el-button>
        </div>
        <div class="text-14px text-gray-700 leading-28px">
          <div>
            配送方式：<span class="text-gray-900">{{ shippingTypeText }}</span>
          </div>
          <div class="flex items-center">
            <span class="flex-shrink-0">单号：</span>
            <span class="text-gray-900">{{ detail.shippingNo || "--" }}</span>
          </div>
        </div>
      </div>

      <div class="mt-10px bg-white p-15px">
        <div class="font-bold text-16px mb-10px flex items-center">
          <span class="w-4px h-16px bg-blue-500 mr-10px"></span>
          物流轨迹
        </div>

        <div v-loading="loading" class="min-h-120px">
          <el-empty v-if="!loading && timeline.length === 0" description="暂无物流轨迹" />
          <el-timeline v-else class="pt-5px">
            <el-timeline-item v-for="(item, index) in timeline" :key="index" :timestamp="item.time"
              :type="index === 0 ? 'primary' : 'info'">
              <div class="text-14px text-gray-900">{{ item.status }}</div>
              <template v-f="detail.shippingType === 'fengniao'">
                <div v-if="item.knightName || item.knightPhone" class="text-13px text-gray-500 mt-5px">
                  <span v-if="item.knightName">骑手：{{ item.knightName }}</span>
                  <span v-if="item.knightPhone" class="ml-10px">电话：{{ item.knightPhone }}</span>
                  <el-button v-if="item.knightPhone" link type="primary" class="ml-10px"
                    @click="copyPhone(item.knightPhone)">
                    复制骑手电话
                  </el-button>
                </div>
              </template>
              <template v-if="detail.shippingType === 'ems'">
                <div class="mt-5px text-14px text-gray-900">{{ item.place }}</div>
                <div class="text-13px text-gray-500 mt-5px">
                  <span v-for="data in item.descTextList" :key="data.key" class="mr-2 text-13px"
                    :class="data.type === 'phone' ? 'text-blue-500' : 'text-dark-500'">
                    {{ data.text }}
                  </span>
                </div>
              </template>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { getShippingDetail } from "@/api/hlw";
import copy from 'copy-to-clipboard';

const props = defineProps({
  visible: { type: Boolean, default: false },
  orderId: { type: String, default: "" },
  accountId: { type: String, default: "" },
});

const emits = defineEmits(["close"]);

const loading = ref(false);
const detail = ref({});

const recipientAddress = computed(() => {
  const region = Array.isArray(detail.value.receiveRegion) ? detail.value.receiveRegion.join("") : "";
  const address = detail.value.receiveAddress || "";
  return (region + address).trim() || "--";
});

const shippingTypeText = computed(() => {
  const t = detail.value.shippingType;
  if (t === "fengniao") return "蜂鸟配送";
  if (t === "ems") return "快递邮寄";
  return t || "--";
});

const timeline = computed(() => {
  if (detail.value && detail.value.shippingType === "fengniao") {
    const shippingDetail = detail.value.shippingDetail || {};
    const eventLogDetails = Array.isArray(shippingDetail.eventLogDetails)
      ? shippingDetail.eventLogDetails
      : [];
    const list = eventLogDetails
      .map((i) => ({
        knightName: i.knightName,
        knightPhone: i.knightPhone,
        time: i.time,
        status: i.status,
      }))
      .sort((a, b) => new Date(b.time) - new Date(a.time));
    if (list.length === 0 && shippingDetail.status) {
      return [{ status: shippingDetail.status, time: "", knightName: "", knightPhone: "" }];
    }
    return list;
  } else if (detail.value && detail.value.shippingType === 'ems') {
    const eventLogDetails = Array.isArray(detail.value.shippingDetail) ? detail.value.shippingDetail : [];
    return eventLogDetails.map((i, idx) => ({
      status: i.opName,
      time: i.opTime,
      place: `${i.opOrgProvName}-${i.opOrgCity}-${i.opOrgName}`,
      descTextList: getDescTextList(i.opDesc, idx),
    }))
  }
  return [];
});

function close() {
  emits("close");
}

async function copyPhone(text) {
  const content = String(text || "");
  if (!content) return;
  copy(content);
  ElMessage.success("复制成功");
}

async function fetchDetail() {
  if (!props.orderId || !props.accountId) {
    detail.value = {};
    return;
  }
  loading.value = true;
  try {
    const { success, data, message } = await getShippingDetail({
      id: props.orderId,
      accountId: props.accountId,
    });
    if (!success) {
      ElMessage.error(message || "获取物流信息失败");
      detail.value = {};
      return;
    }
    // PC 端 axios 包装会把后端返回的 `data` 再包一层：{ data: {...} }
    const payload = data && typeof data === "object" && data.data ? data.data : data;
    detail.value = payload || {};
  } finally {
    loading.value = false;
  }
}

function getDescTextList(desc, index) {
  if (typeof desc !== 'string') return [];

  // 匹配11位手机号（以1开头的数字）
  const phoneRegex = /1[3-9]\d{9}/g;
  const result = [];
  let lastIndex = 0;
  let match;

  // 查找所有手机号
  while ((match = phoneRegex.exec(desc)) !== null) {
    // 添加手机号之前的普通文本
    if (match.index > lastIndex) {
      const textBefore = desc.substring(lastIndex, match.index);
      if (textBefore) {
        result.push({
          text: textBefore,
          type: 'text'
        });
      }
    }

    // 添加手机号
    result.push({
      text: match[0],
      type: 'phone'
    });

    lastIndex = match.index + match[0].length;
  }

  // 添加最后一个手机号之后的普通文本
  if (lastIndex < desc.length) {
    const textAfter = desc.substring(lastIndex);
    if (textAfter) {
      result.push({
        text: textAfter,
        type: 'text'
      });
    }
  }

  // 如果没有找到手机号，返回整个文本作为普通文本
  if (result.length === 0) {
    result.push({
      text: desc,
      type: 'text'
    });
  }
  return result.map((i, idx) => ({
    key: `${index}-${Date.now()}-${idx}`,
    text: i.text,
    type: i.type
  }));
}


watch(
  () => props.visible,
  async (val) => {
    if (val) {
      await fetchDetail();
    }
  }
);
</script>

<style scoped>
.text-gray-900 {
  color: #303133;
}
</style>
