<template>
  <photo-consumer
      class="carousel-item"
      :src="watermark || base_img_url2 + (photo.resFilename ? photo.resFilename : photo.filename) + resize"
  >
    <img v-if="Math.abs(current - index) < 3" crossorigin="anonymous" @load="drawWatermark($event)" loading="lazy" :src="watermark || (base_img_url2 + (photo.resFilename ? photo.resFilename : photo.filename) + resize)" style="width: 100%;" />
    <canvas  ref="canvasRef" style="position: absolute;"></canvas>
    <div class="tag-text" v-if="showTagBox" >
      <span v-html="photo.growText"></span>
      <button class="close-button" @click="hideTagBox">✖</button>
    </div>
    <div class="tag-box right" :class="{'leftTop': 'leftTop'}">{{ index+1 }}/{{ length }}</div>
<!--    <div class="center-mark">mark</div>-->
  </photo-consumer>

</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, defineProps } from "vue";
import { base_img_url2 } from "@/api/config";
import {imageCache,loadImage} from "./cacheImg.js"
import {dateFormat} from "@/utils/date_util.js"
import {pointToFormat} from "@/utils/util.js"
import {drawTextInRect, drawBorderImageInRect, drawImageInRect, drawRectInRect, drawHorizontalTextList} from "./utils"
const resize = "?x-oss-process=image/resize,p_120/format,webp/quality,q_100";

const canvasRef = ref(null);
const watermark = ref(null)
const baseMapBig = ref(false)

const props = defineProps({
  farmId:{
    type: [Number,String],
    required: true
  },
  photo:{
    type: Object,
    required: true
  },
  index:{
    type: Number,
    required: true
  },
  length:{
    type: Number,
    required: true
  },
  current:{
    type: Number,
    required: true
  }
})
let img = null;
let ctx = null;
let data = {year:props.photo.uploadDate.substring(0,4),
  monthDay:dateFormat(new Date(props.photo.uploadDate),'mm/dd'),
  address:props.photo.district.replaceAll("\"","") + props.photo.gardenName,
  tempImg:imageCache.get("temp"),temp:"10°C-20°C",wendu:"适宜",
  feiniao:imageCache.get("feiniao"),
  baseMap:imageCache.get("base_map_"+props.photo.treeId),
  fusheImg:imageCache.get("fushe"),fushe:"光照优",
  shiduImg:imageCache.get("shidu"),shidu:"湿度适宜",
  text:"病害风险，及时喷药",
  shotCode:props.photo.shotCode,
  treeCode:props.photo.treeCode,
  pingzhong:props.photo.pingzhong,
  uploadDate:props.photo.uploadDate,
}

async function drawWatermark(event) {
  img = event.target
  await loadImage(props.photo.baseMap,"base_map_"+props.photo.treeId)
  data.baseMap = imageCache.get("base_map_"+props.photo.treeId)
  if(!watermark.value){
    let param = {farmId:props.farmId, date: props.photo.uploadDate}
    let weather = null
    VE_API.image.findSuitabilityByPoint(param).then((res)=>{
      if(res.code === 0){
        weather = res.data
        drawWatermark2(img,weather)
      }else{
        drawWatermark2(img,null)
      }
    })
  }
}

function drawWatermark2(img,weather) {
  const canvas = canvasRef.value;
  let scale = 3
  canvas.width = img.width * scale;
  canvas.height = img.height * scale;
  ctx = canvas.getContext('2d');
  ctx.scale(scale, scale)
  ctx.drawImage(img, 0, 0, img.width, img.height);
  drawBottom(img.width, img.height, weather)
  watermark.value = canvas.toDataURL();
}


// console.log(data)
const drawBottom = (imgWidth, imgHeight, weather) => {
  if (weather) {
    data["temp"] = weather.tempMin + "°C" + "-" + weather.tempMax + "°C" + " " + weather.tempSuitability
    data["fushe"] = "光照"+weather.vindexSuitability
    data["shidu"] = "湿度"+weather.humiditySuitability
  }
  // 设置文本样式
  ctx.font = "8px Arial";
  ctx.textAlign = "left"; // 设置为左对齐
  let imgRect = { x: 0, y: 0, width: imgWidth, height: imgHeight}
  // 绘制头部黑色半透明遮罩
  let topRect = drawRectInRect(ctx,imgRect, 0, 0, 70, 10,"rgba(0, 0, 0, 0.6)")
  // 绘制黑色半透明遮罩
  let bottomRect = drawRectInRect(ctx,imgRect, 0, 5/6 * 100, 100, 1/6 * 100,"rgba(0, 0, 0, 0.6)")

  drawHorizontalTextList(ctx, topRect, '#ffffff90',[data.treeCode, "蓬径:5m", "高度:3m", "高产树",data.pingzhong],
      40, 0,
      65 , 0,"|",0,
      30,"#ffffff50",1,2)
  ctx.fillStyle = "white"; // 文本颜色为白色
  // 绘制温度
  let startXPercent = 1;
  drawImageInRect(ctx, bottomRect, data.tempImg, startXPercent, 5+10, 5, 30)
  drawTextInRect(ctx, bottomRect,`${data.temp}`,startXPercent + 4, 28+10, 20)
  // 绘制湿度
  drawImageInRect(ctx, bottomRect, data.shiduImg, startXPercent+26, 7 + 10, 4, 30)
  drawTextInRect(ctx, bottomRect,`${data.shidu}`,startXPercent + 31, 28 + 10, 20)
  // 绘制辐射
  drawImageInRect(ctx, bottomRect, data.fusheImg, startXPercent+26 + 18, 7 + 10, 5, 30)
  drawTextInRect(ctx, bottomRect,`${data.fushe}`,startXPercent+31 + 18, 28 + 10, 20)
  //绘制日期信息
  ctx.fillStyle = "#FFFFFF";
  drawTextInRect(ctx, bottomRect,`${formatDate(new Date(data.uploadDate))}`,startXPercent +1.7, 75, 24)
  //绘制位置信息
  ctx.fillStyle = "#FFFFFF90";
  drawTextInRect(ctx, bottomRect,`${data.treeCode}_S3_SCS3-3_D0P0G1`,startXPercent +13, 75, 18)

  if(data.baseMap){
    drawBorderImageInRect(ctx, imgRect, data.baseMap, 2/3*100, 2/3*100,
        1/3*100, 1/3*100, 5, 5)
  }
}


const showTagBox = ref(true); // 控制 tag-box 的显示状态
const hideTagBox = (event) => {
  event.stopPropagation();
  showTagBox.value = false; // 隐藏 tag-box
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  return `${(year+"").substring(2)}${month}${day}`;
};




</script>

<style lang="scss" scoped>
.canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}
.carousel-item {
  min-width: 100%;
  flex-shrink: 0;
  width: 100%;
  pointer-events: auto;
  position: relative;
  .tag-box {
    position: absolute;
    bottom: 30%;
    left: 50%;
    transform: translate(-50%, 50%); // 确保在高二分之一的位置水平居中
    height: 18px;
    padding: 0 6px;
    background: rgba(108, 108, 108, 0.67);
    border-radius: 10px;
    display: flex;
    align-items: center;
    color: #FFFFFF;
    font-size: 12px;

    &.right {
      left: auto;
      right: 10px;
    }
    &.leftTop {
      height: 25px;
      line-height: 26px;
      padding: 0 8px;
      border-radius: 16px;
      background: rgba(0, 0, 0, 0.6);
      bottom: auto;
      top: 6px;
    }
  }
  .tag-text {
    position: absolute;
    bottom: 31%;
    left: 50%;
    width: 80%;
    transform: translate(-50%, 50%); // 确保在高二分之一的位置水平居中
    height: 24px;
    padding: 10px 0px 10px 0px;
    background: rgba(0, 0, 0, 0.67);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    color: #FFFFFF;
    font-size: 12px;
  }

  .center-mark {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    color: #36402c;
    font-size: rpx(24);
    font-weight: bold;
    padding: rpx(14) rpx(30);
    background: linear-gradient(
            90deg,
            rgba(255, 255, 255, 0) 0%,
            rgba(255, 255, 255, 0.6) 24%,
            rgba(255, 255, 255, 0.6) 76%,
            rgba(255, 255, 255, 0) 100%
    );
  }
}
.carousel-item img {
  width: 100%;
  display: block;
}
canvas {
  position: absolute;
}
.close-button {
  background: transparent;
  border: none;
  color: #FFFFFF;
  cursor: pointer;
  font-size: 10px; // 可以根据需求调整大小
  position: absolute;
  top: -1px;
  right: -9px; // 调整为合适的间距
  transform: translateY(-50%);
}

.floating-img {
  position: absolute;
  bottom: 0;
  right: 0;
  width: auto !important;
  height: 25% !important;
}
.floating-img-big {
  position: fixed !important;
  z-index: 99999 !important;
  top: 50% !important;
  left: 50% !important;
  width: auto !important;
  height: 100% !important;
  transform: translate(-50%, -50%) !important;
}




</style>
