<template>
  <div class="demo-timeline">
    <div v-if="loading" v-loading="loading" style="height: 180px"></div>
    <template v-else>
      <div v-if="records.length" style="margin-bottom: 10px">{{ title }}</div>
      <el-timeline v-if="records.length">
        <el-timeline-item
          v-for="(item, index) in records"
          :key="index"
          :timestamp="item.createTime"
          :color="item.label"
        >
          <div style="display: flex; align-items: center; flex-wrap: wrap">
            <el-icon :size="14" :color="item.label">
              <Flag />
            </el-icon>
            <span>{{ item.createName }}：</span>
            <span>{{ item.remark }}</span>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无数据" :image-size="80"></el-empty>
    </template>
  </div>
</template>

<script setup>
  import { watch, ref, onMounted } from 'vue';
  import request from '@/utils/request';
  import { Flag } from '@element-plus/icons-vue';

  const props = defineProps({
    orderId: {
      type: [String, Number],
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  });

  const records = ref([]);
  const loading = ref(false);
  // 添加缓存来存储已获取的数据
  const dataCache = ref(new Map());
  // 跟踪上一次请求的订单ID，防止重复请求
  const lastRequestedOrderId = ref('');

  //获取备注
  const getRemarks = async (orderId) => {
    if (!orderId || loading.value) return;

    // 如果缓存中已有该数据，直接使用缓存
    if (dataCache.value.has(orderId)) {
      records.value = dataCache.value.get(orderId);
      return;
    }

    // 防止对同一订单ID重复请求
    if (lastRequestedOrderId.value === orderId) return;
    lastRequestedOrderId.value = orderId;

    loading.value = true;
    try {
      const res = await request.get(`/order/remark/list?orderId=${orderId}`);
      records.value = res.data.data;
      // 缓存结果
      dataCache.value.set(orderId, res.data.data);
    } catch (error) {
      console.error('Failed to fetch remarks:', error);
    } finally {
      loading.value = false;
    }
  };

  defineExpose({
    getRemarks
  });
</script>
