<template>
  <el-upload class="upload-demo" action="http://localhost:8080/data/model/saveImage">
    <el-button type="primary">Click to upload</el-button>
  </el-upload>

  <button @click="getImages">获取图片</button>

  <!-- style="max-width: 300px" -->
  <div class="img-container">
    <img
      draggable="false"
      style="max-width: 300px"
      class="display-img"
      :src="displayImageUrl"
      alt="Display Image"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus';

let displayImageUrl = ref<string>('');
async function getImages() {
  console.log('获取图片');
  const response = await fetch('http://localhost:8080/data/model/getImageUrl', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Accept: '*/*'
    }
  });

  // 后端返回JSON格式数据，包含file字段
  const data = await response.json();

  // 检查data.file是否为base64编码的图片数据
  if (data.file && typeof data.file === 'string') {
    // 如果是base64格式，直接使用
    if (data.file.startsWith('data:image')) {
      displayImageUrl.value = data.file;
    } else {
      // 如果只是base64编码的数据，添加必要的前缀
      displayImageUrl.value = `data:image/png;base64,${data.file}`;
    }
  }

  console.log('获取图片数据:', displayImageUrl.value);
}

// 清理函数，组件卸载时释放图片URL资源
onUnmounted(() => {
  if (displayImageUrl.value) {
    URL.revokeObjectURL(displayImageUrl.value);
  }
});

const fileList = ref<UploadUserFile[]>([
  {
    name: 'element-plus-logo.svg',
    url: 'https://element-plus.org/images/element-plus-logo.svg'
  },
  {
    name: 'element-plus-logo2.svg',
    url: 'https://element-plus.org/images/element-plus-logo.svg'
  }
]);
</script>
