<template>
  <div ref="mapRef" class="bottom-map"></div>
  <div ref="info" class="area-info"></div>
  <div ref="imgInfo" class="img-info" @mouseleave="hideImg"></div>
  <el-dialog
    class="v-dialog dialog-preview"
    v-model="dialogVisibleShow"
    width="1024"
    :show-close="false"
    top="5vh"
    @close="handleCloese"
  >
    <template #header>
      <div class="dialog-header">
        <div>果树编号:{{ imgObj.treeCode }}</div>
        <div class="right">
          <div class="switch" @click="handleSwitch">
            <el-icon color="#00FFF0" size="15"><Switch /></el-icon>
            <span>切换{{ switchValue ? "原图" : "指标图" }}</span>
          </div>
          <el-icon
            @click="handleCloese"
            class="close-icon"
            color="#00FFF0"
            size="20px"
            ><CircleCloseFilled
          /></el-icon>
        </div>
      </div>
    </template>
    <div class="dialog-body">
      <img
        @click="handleZoom"
        class="zoom yse-events"
        src="@/assets/img/znxy/zoom_btn.png"
        alt=""
      />
      <DrawBox
        v-if="switchValue && imgObj.markText"
        width="1002"
        :height="imgHeight"
        :sourceData="imgObj.markText"
      ></DrawBox>
      <img
        class="image no-events"
        :src="imgObj.filename + '?x-oss-process=image/resize,w_2000'"
        alt=""
        fit="cover"
        ref="imageRef"
      />
      <!-- <img
        class="image no-events"
        :src="imgObj.resFilename + '?x-oss-process=image/resize,w_2000'"
        alt=""
        fit="cover"
      /> -->
      <div class="watermark-style">
        <div class="left">
          <div class="region">2区</div>
          <div class="date">{{ imgObj.uploadDate }}</div>
          <div class="whq">
            {{ imgObj.bigPeriodName }}<span v-show="imgObj.bigPeriodName&&imgObj.smallPeriodName">-</span>{{ imgObj.smallPeriodName }}
          </div>
          <div class="code">
            <div class="code-txt">生长正常</div>
          </div>
          <div class="weather">
            <div class="temperature">
              <img src="@/assets/img/sun_icon.png" alt="" />
              <div class="num">
                <div>26-32℃</div>
              </div>
            </div>
            <div class="temperature">
              <img src="@/assets/img/rain_icon.png" alt="" />
              <div class="num">
                <div>60% 0.34ｍl</div>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="right">
          <div class="block mr">病虫害</div>
          <div class="block">二梢杀虫</div>
        </div> -->
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <Carousel
          :items="carouselImageList"
          @handleImage="handleImage"
        ></Carousel>
      </div>
    </template>
  </el-dialog>
  <PicturePreview
    v-if="zoomDisplay"
    :show="zoomShow"
    :switchValue="switchValue"
    :imageUrl="imgObj"
  ></PicturePreview>
</template>

<script setup>
import { useStore } from "vuex";
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import { base_img_url2 } from "@/api/config.js";
import ZnxyMap from "./znxy/ZnxyMap";
import { WKT } from "ol/format";
import Carousel from "@/components/carousel.vue";
import DrawBox from "@/components/drawBox.vue";
import { treeItem } from "./znxy/ZnxyMap.js";
import { ElMessage } from "element-plus";
import PicturePreview from "@/components/PicturePreview.vue";
import PlotLayer from "./znxy/znxyLayer/plotLayer";

const props = defineProps({
  tabValue:{
    type: Object,
    default: ()=>{},
  }
});

let resize = "?x-oss-process=image/resize,w_200";
let emit = defineEmits(["setHideZnxy"]);
let store = useStore();
const mapRef = ref("mapRef");
const info = ref(null);
const imgInfo = ref(null);
let curGardenId = ref(store.getters.userinfo.curGardenId);
let curArea = ref({});
let znxyMap = new ZnxyMap();
let plotLayer = null;
let curTree = null;
let curDate = new Date();
let curYear = curDate.getFullYear();
let curMonth = curDate.getMonth() + 1;
let curDay = curDate.getDate();

// 在组件或全局监听器中监听自定义事件
function handleStorageUpdate(e) {
  curGardenId.value = e.detail;
  initData();
}
// 在组件或全局监听器中监听自定义事件
window.addEventListener("storageChanged", handleStorageUpdate);

// 组件销毁前移除监听
onBeforeUnmount(() => {
  window.removeEventListener("storageChanged", handleStorageUpdate);
});

const imageRef = ref(null)
const imgHeight = ref('')

const dialogVisibleShow = ref(false);
const handleFeedback = () => {
  dialogVisibleShow.value = true;
};


// 缩放
const zoomShow = ref(false);
const zoomDisplay = ref(false);
const handleZoom = () => {
  zoomDisplay.value = true
  zoomShow.value = !zoomShow.value;
};

const imgObj = ref({ filename: "", resFilename: "" });
const handleImage = (v) => {
  imgObj.value = imageList.value.find((item) => item.id == v.id);
  curDate = new Date(imgObj.value.uploadDate);
  curYear = curDate.getFullYear();
  curMonth = curDate.getMonth() + 1;
  curDay = curDate.getDate();
  imgHeight.value = imageRef.value.offsetHeight
  console.log(imgHeight.value);
};

onMounted(() => {
  let location = store.getters.userinfo.location;
  znxyMap.initMap(location, mapRef.value);
  plotLayer = new PlotLayer(znxyMap.kmap);
  initGarden();
  initData();
});

watch(
  () => props.tabValue,
  (newValue, oldValue) => {
    if (newValue) {
      znxyMap.initTree(curGardenId.value,false);
      if(newValue.type===1){
        plotLayer.switchTreeLegend(curGardenId.value, newValue);
      }else if(newValue.type===2){
        plotLayer.addGargendImg(curGardenId.value, { key: newValue.key });
      }else{
        znxyMap.initTree(curGardenId.value,true);
        plotLayer.switchTreeLegend(curGardenId.value, newValue);
      }
    }
  }
);

const initGarden = () => {
  znxyMap.initGarden();
  znxyMap.addGardenClick(async function (f) {
    let user = JSON.parse(sessionStorage.getItem("userinfo"));
    // 更新果园信息
    const res = await VE_API.organ.updateGarden({
      gardenId: f.get("organId"),
      userId: user.userId,
    });
    if (res.code === 0) {
      const resData = res.data;
      user.curGardenId = resData.curGardenId;
      user.curGardenName = resData.curGardenName;
      user.location = resData.location;
      store.commit("app/SET_USER_INFO", JSON.stringify(user));
      // 添加自定义事件
      window.dispatchEvent(
        new CustomEvent("storageChanged", { detail: user.curGardenId })
      );
      emit("setHideZnxy", true);
    }
  });
};

const initData = () => {
  znxyMap.initArea(curGardenId.value);
  znxyMap.initSubArea(curGardenId.value);
  znxyMap.initTree(curGardenId.value,true);
  znxyMap.addHoverTooltips(info.value, imgInfo.value);
  znxyMap.addMapClick();
};

defineExpose({
  znxyMap,
});

// 隐藏图片
const hideImg = () => {
  imgInfo.value.style.visibility = "hidden";
};

const switchValue = ref(true);
const handleSwitch = () => {
  switchValue.value = !switchValue.value;
};

const handleCloese = () => {
  treeItem.treeId = 0;
  dialogVisibleShow.value = false;
};

const imageList = ref([]);
const carouselImageList = ref([]);

watch(
  () => treeItem.treeId,
  (newValue, oldValue) => {
    if (newValue > 0) {
      imageList.value = [];
      dialogVisibleShow.value = true;
      VE_API.tree_img
        .imagesByTreeId({ treeId: newValue, limit: 100 })
        .then(({ data }) => {
          let arr = new Array();
          for (let item of data) {
            item.filename = base_img_url2 + item.filename;
            arr.push({
              id: item.id,
              src: item.filename + resize,
              date: item.uploadDate,
            });
          }
          if (data.length > 0) {
            if (!data[0].resFilename) {
              switchValue.value = false;
            } else {
              switchValue.value = true;
            }
          }
          carouselImageList.value = arr;
          imageList.value = data;
          if (data.length > 0) {
            handleImage(data[0]);
          } else {
            ElMessage.warning("暂无数据");
          }
        });
    }
  }
);
</script>

<style scoped lang="scss">
// 弹窗样式
.v-dialog {
  .dialog-header {
    .right {
      display: flex;
      align-items: center;
      .switch {
        cursor: pointer;
        background: url("@/assets/img/tabs_btn3.png") no-repeat center center /
          100% 100%;
        width: 120px;
        text-align: center;
        padding: 5px 0;
        margin-right: 24px;
      }
    }
  }
  .dialog-body {
    padding: 10px;
    position: relative;
    height: 98%;
    box-sizing: border-box;
    .zoom {
      position: absolute;
      top: 15px;
      right: 15px;
      z-index: 9;
      cursor: pointer;
    }
    .image {
      width: 100%;
      height: 100%;
    }
    .watermark-style {
      width: 98%;
      bottom: 10px;
      .region {
        width: 38px;
        height: 38px;
        font-size: 12px;
        line-height: 38px;
        margin-right: 10px;
      }
      .date {
        font-size: 23px;
      }
      .whq{
        font-size: 18px;
      }
        .code {
          .code-txt {
            font-size: 18px;
            margin-left: 25px;
            &::before {
              content: "";
              top: 8px;
            }
          }
        }
        .weather {
          .temperature {
            font-size: 17px;
            img {
              width: 22px;
              height: 22px;
            }
          }
        }
      .right {
        font-size: 14px;
      }
    }
  }
  .dialog-footer {
    height: auto;
    display: flex;
    align-items: center;
    padding: 8px 10px 4px 10px;
    background: rgba(0, 246, 255, 0.14);
  }
}
.bottom-map {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
  background-color: #5f5d5d;
  overflow: hidden;
}
.area-info {
  position: absolute;
  display: inline-block;
  height: auto;
  width: auto;
  z-index: 100;
  color: #fff;
  border-radius: 4px;
  padding: 6px 8px;
  left: 50%;
  transform: translateX(3%);
  visibility: hidden;
  pointer-events: none;
  background: rgba(51, 11, 3, 0.7);
  border: 1px solid #f55a5a;
}
.img-info {
  position: absolute;
  display: inline-block;
  z-index: 3;
  color: #fff;
  visibility: hidden;
  pointer-events: none;
  background: #ffffff;
  border: 3px solid rgba(255, 157, 0, 0.75);
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: fit-content;
  height: calc(30vh - 6px);
  ::v-deep {
    img {
      width: fit-content;
      height: 100%;
      object-fit: scale-down;
    }
  }
}
</style>

<style lang="scss">
.dialog-preview {
  height: 89%;
  box-sizing: border-box;
  .el-dialog__body {
    height: 79.5%;
    box-sizing: border-box;
  }
  .el-dialog__footer{
    height: 13.5%;
    display: flex;
    align-items: center;
  }
}
</style>
