<script setup>
const props = defineProps({
  messageContent: String, // 消息内容
  viewType: Number, // 0发送 1接收
});

let imgUrl = ref(null)
let width = ref(75);
let height = ref(75);
let loading = ref(false)

/*const initMessage = () => {
  switch (props.viewType) {
    case 0: // 发送 上传
      sendMessage()
      break;
    case 1: // 接收
      acceptMessage(props.messageContent)
      break;
  }
}*/

const resizeImageToMaxSize = (maxSize, w, h) => {
  let scale = 1;
  if (w > maxSize || h > maxSize) {
    if (w > h) {
      scale = maxSize / w;
    } else {
      scale = maxSize / h;
    }
  }
  return {width: scale * w, height: scale * h}
}

// 处理接收到的消息
const initMessage = async () => {
  try {
    const url = props.messageContent;
    const img = new Image();
    img.onload = function() {
      const size = resizeImageToMaxSize(250, this.width, this.height);
      width.value = size.width;
      height.value = size.height
      imgUrl.value = url;
    };
    img.onerror = function() {
      console.error('图片加载失败');
    };
    img.src = url;
  } catch (e) {

  } finally {

  }
}
// 处理发出去的消息
const sendMessage = async () => {
  try {
    loading.value = true
    const formData = new FormData()
    formData.append('uploadFile', props.messageContent)
    formData.append('asImage', true)
    formData.append('fieldName', 'messageContent')
    const res = await request(`/website/tourMessage/upload`, {
      method: 'post',
      body: formData
    })
    await handleResponse(res)
    const fileUrl = res.data?.fileUrl;
    // 应该读本地图片，但是没做发送失败的情况，就先这样吧
    const img = new Image();
    img.onload = function() {
      const size = resizeImageToMaxSize(250, this.width, this.height);
      width.value = size.width;
      height.value = size.height
      imgUrl.value = fileUrl;
    };
    img.onerror = function() {
      console.error('图片加载失败');
    };
    img.src = fileUrl;
  } catch (e) {

  } finally {
    loading.value = false
  }
}

const preview = () => {
  showImagePreview({
    images: [imgUrl.value]
  });
}

onMounted(() => {
  initMessage()
})

</script>

<template>
  <div class="image-message">
    <van-image :src="imgUrl" :width="width" :height="height" @click="preview">
      <template v-slot:loading>
        <div class="relative">
          <div class="absolute w-full h-full left-0 right-0 flex items-center justify-center">
            <van-loading type="spinner" size="20"/>
          </div>
          <img class="w-full h-full" src="../../../../assets/img/chat/image-loading.png" alt="loading"/>
        </div>
      </template>
      <template v-slot:error>
        <img src="../../../../assets/img/chat/image-error.png" alt="error"/>
      </template>
    </van-image>
  </div>
</template>

<style scoped lang="scss">
.image-message {
  display: flex;
  position: relative;

  .message__operate {
    width: 16px;
    height: 16px;
    border-radius: 100%;
    background: #FF476A;
    color: #fff;
    position: absolute;
    right: 8px;
  }
}

</style>