<template>
  <view class="field-item">
    <view class="detail-title">
      <view class="required">
        <text v-show="item?.isMustfill === '1'">*</text>
      </view>
      <view class="label">{{ item?.taskFiledValue }}</view>
    </view>
    <view class="detail-cont">
      <div class="img-box">
        <view class="img-cont" v-for="(item, index) in imgList" :key="index">
          <view class="text">{{ item.type }}</view>
          <image
            :src="item.path"
            mode="aspectFill"
            class="img-item"
            @click="preImg(imgList, index)"
            @error="errorImage(item, index)"
          />
        </view>
      </div>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, getCurrentInstance } from 'vue'
// #ifdef H5
import heic2any from 'heic2any'
// #endif

const props = defineProps({
  item: Object,
  detailInfo: Object
})

onMounted(() => {
  getImgList()
})
const imgList = ref()
const getImgList = () => {
  if (!props.item) return
  const imgStr = props?.detailInfo?.wmTaskContent[props.item.taskFiledKey]
  if (!imgStr) return
  const imgArr = imgStr.split(',')
  imgList.value = imgArr.map((item: string) => {
    const obj = {
      type: '',
      path: ''
    }
    if (item.includes(';1')) {
      obj.type = '当场拍照'
      item = item.replace(';1', '')
    }
    if (item.includes(';2')) {
      obj.type = '相册选取'
      item = item.replace(';2', '')
    }
    obj.path = import.meta.env.VITE_APP_URL + item
    return obj
  })
}

const preImg = (imgList: any[], index: number) => {
  const arr = imgList.map((item) => item.path)
  uni.previewImage({
    current: index,
    urls: arr
  })
}

// #ifdef H5
const errorImage = async (item: any, index: number) => {
  await handleImage(item, index)
}
const instance = getCurrentInstance()
const imgValue = ref('')
const handleImage = async (item: any, index: number) => {
  let url = item.path
  const response = await fetch(url)
  const blob = await response.blob()

  if (await isHeicFile(blob)) {
    const heicImageBlob = await fetch(url).then((res) => res.blob())

    // 使用 heic2any 库将 HEIC 转换为 JPG
    heic2any({ blob: heicImageBlob, toType: 'image/jpeg' })
      .then((convertedBlob) => {
        // @ts-ignore
        const imgURL = URL.createObjectURL(convertedBlob)
        imgList.value[index].path = imgURL
        imgValue.value = imgURL
        instance?.proxy?.$forceUpdate()
      })
      .catch((err) => {
        console.log('err', err)
      })
  }
}

const isHeicFile = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => {
      const buffer: string | ArrayBuffer | null = reader.result
      // HEIC 文件的前几个字节为 "00 00 00 18 66 74 79 70 68 65 69 63" 或 "00 00 00 20 66 74 79 70 68 65 69 63" (小端字节序)
      const signature = new Uint8Array(buffer as ArrayBuffer).subarray(0, 12)
      const heicSignature = [0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63]

      const isHeic = signature.every((byte, index) => byte === heicSignature[index])
      resolve(isHeic)
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}
// #endif
</script>

<style lang="scss" scoped>
.field-item {
  padding: 20rpx;
  color: #000;
  background-color: #fff;
  font-size: 28rpx;
  line-height: 50rpx;
  box-sizing: border-box;

  .detail-title {
    display: flex;
    .required {
      margin-right: 6rpx;
      text {
        color: red;
        width: 10rpx;
      }
    }
    .label {
      flex: 1;
    }
  }
  .detail-cont {
    .img-box {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .img-cont {
        margin-top: 22rpx;
        margin-left: 22rpx;
        .text {
          color: #333;
          font-size: 20rpx;
          padding-left: 15rpx;
        }
      }
      .img-item {
        width: 150rpx;
        height: 150rpx;
        flex-shrink: 0;
      }
    }
  }
}
</style>
