<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">{{ order.receiveInfo?.name || "--" }}</span>
            <span class="ml-10px text-gray-900">{{ order.receiveInfo?.mobile || "" }}</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="order.shippingNo" link type="primary" @click="copy(order.shippingNo)">复制</el-button>
        </div>
        <div class="text-14px text-gray-700 leading-28px">
          <div>
            配送方式：<span class="text-gray-900">快递邮寄</span>
          </div>
          <div class="flex items-center">
            <span class="flex-shrink-0">单号：</span>
            <span class="text-gray-900">{{ order.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>
              <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>
            </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 { getWineShippingDetail } from "@/api/hlw";
import copy from 'copy-to-clipboard';

const props = defineProps({
  visible: { type: Boolean, default: false },
  order: { type: Object, default: () => ({}) },
});

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

const loading = ref(false);
const shipList = ref([]);

const recipientAddress = computed(() => {
  const region = Array.isArray(props.order.receiveInfo?.region) ? props.order.receiveInfo.region.join("") : "";
  const address = props.order.receiveInfo?.address || "";
  return (region + address).trim() || "--";
});


const timeline = computed(() => {
  return shipList.value.map((i, idx) => ({
    status: i.opName,
    time: i.opTime,
    place: `${i.opOrgProvName}-${i.opOrgCity}-${i.opOrgName}`,
    descTextList: getDescTextList(i.opDesc, idx),
  }))
});

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

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

async function fetchDetail() {
  const { success, data, message } = await getWineShippingDetail(props.order.shippingNo);
  shipList.value = data && Array.isArray(data.data) ? data.data : [];
  if (!success) {
    ElMessage.error(message || "获取物流信息失败");
    return;
  }
}

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>
