\<template>
  <div class="photo">
    <div class="left">
      <div class="upload my-photo-upload">
        <!-- <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          multiple
          :show-file-list="false"
          :http-request="handleRequest"
          :on-change="handleChange"
          :before-upload="handleUpload"
          :limit="10"
        >
          <el-button type="primary">上传照片</el-button>
        </el-upload> -->
        <el-button type="primary" @click="addCaseFileHandlerAll">
          上传照片
        </el-button>
        <el-button
          type="primary"
          @click="handleSwitchGrid"
          :icon="sortType ? FullScreen : Menu"
          >{{ sortType ? "横排" : "竖排" }}</el-button
        >
      </div>
      <draggable
        ref="childRef"
        :caseId="caseId"
        :sortType="sortType"
        @changeList="changeList"
        @handleItem="handleItem"
        @delImage="handleImageDel"
      />
    </div>
    <div class="right">
      <div class="tools">
        <el-button @click="handleMark">
          <i class="iconfont icon-arrows1" />
          箭头
        </el-button>
        <el-button @click="handleLine">
          <i class="iconfont icon-index" />
          标引
        </el-button>
        <el-button @click="handleSymbol">
          <i class="iconfont icon-symbol" />
          符号
        </el-button>
        <el-button @click="handleText">
          <i class="iconfont icon-text1" />
          文本</el-button
        >
        <el-button @click="handleSave" class="save">保存</el-button>
        <el-button
          @click="handleExport"
          class="opt"
          :loading="!isSenseLoaded"
          :disabled="!isSenseLoaded"
          >导出</el-button
        >
        <el-button @click="backPageHandler" class="opt">返回</el-button>

        <el-button @click="handleClear" v-if="hasDrawData" class="opt"
          >清空</el-button
        >
        <el-button @click="handleFree" v-if="isShowExitEdit" class="opt"
          >退出编辑</el-button
        >
      </div>

      <canvas id="canvas" v-show="true"></canvas>
      <edit
        :show="editing.show"
        :data="editing.data"
        @update="handleEditingUpdate"
        @del="handleEditingDel"
        @close="handleEditingClose"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, onUnmounted, reactive } from "vue";
import { Menu, FullScreen } from "@element-plus/icons-vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import { router } from "@/router";
import "swiper/css";
// import { addCaseFile } from "@/store/caseFile";
import { addCaseImgFile, addCaseImgFileAll } from "../quisk";
import {
  saveCaseImgTagData,
  getCaseImgTagData,
  submitMergePhotos,
} from "@/store/case";
import Scene from "@/core/Scene.js";
import draggable from "./draggable.vue";
import edit from "./edit.vue";
import saveAs from "@/util/file-serve";
import { ElMessage, ElMessageBox } from "element-plus";

const caseId = computed(() => router.currentRoute.value?.params?.caseId);
const props = defineProps({ caseId: Number, title: String });

const editing = ref({
  show: false,
  data: {},
});
const newlist = ref([]);
const fileList = ref([]);
const swiperRef = ref(null);
const childRef = ref(null);
const isSenseLoaded = ref(false);
const sortType = ref(false);
const drawMode = ref(0);
const isShowExitEdit = computed(() => drawMode.value > 0);
const loadedDrawData = ref();
const hasDrawData = ref(false);
let scene = null;

const addCaseFileHandler = async () => {
  await addCaseImgFile({
    caseId: caseId.value,
    data: {
      imgUrl: "",
      imgInfo: "",
      id: "",
      sort: "",
    },
  });
  refresh();
};

const addCaseFileHandlerAll = async () => {
  await addCaseImgFileAll({
    caseId: caseId.value,
    data: {
      imgUrl: "",
      imgInfo: "",
      id: "",
      sort: "",
    },
  });
  refresh();
};

function refresh() {
  console.log("changeList", childRef.value);

  if (childRef.value) {
    childRef.value.getList();
  }
}
const changeList = async (list) => {
  //同步数据
  if (!loadedDrawData.value) {
    const res = await getCaseImgTagData(caseId.value);
    if (res.data) {
      if (res.data.data) {
        loadedDrawData.value = res.data.data;
      }
      if ("isHorizontal" in res.data) {
        // console.error("sortType.value", sortType.value, !res.data.isHorizontal);
        sortType.value = !res.data.isHorizontal;
      }
    } else {
      loadedDrawData.value = [];
    }
  }

  let newList = [];
  list.map((item, index) => {
    if (sortType.value) {
      newList.push([item]);
    } else {
      if (index % 2 == 0) {
        let newItem = list[index + 1] ? [item, list[index + 1]] : [item];
        newList.push(newItem);
      }
    }
  });
  newlist.value = newList;
  const arr = [];
  newList.map((i) => arr.push(JSON.parse(JSON.stringify(i))));

  const type = sortType.value ? 2 : 1;

  if (scene) {
    scene.load(arr, type, loadedDrawData.value || []);
    console.log("changeList", arr, type, loadedDrawData.value);
  }
};
const renderCanvas = () => {
  const canvas = document.getElementById("canvas");

  scene = new Scene(canvas);
  scene.init();
  window.scene = scene;
  scene.on("mode", (mode) => {
    console.warn("mode", mode);
    drawMode.value = mode;
  });
  scene.on("markerExist", () => {
    ElMessage.error("该案件已有方向标注！");
  });
  scene.on("confirmDelete", async ({ id, type }) => {
    const res = await ElMessageBox.confirm("是否删除该部件?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "default",
    });
    if (res) {
      window.scene.deleteItemById(id, type);
    }
  });
  scene.on("data", (data) => {
    let hasData = false;
    Object.keys(data).forEach((key) => {
      if (Array.isArray(data[key])) {
        if (data[key].length > 0) {
          hasData = true;
        }
      }
    });
    hasDrawData.value = hasData;
    console.log("sync", data, hasData);
    // editing.value.data = data;
    loadedDrawData.value = data;
  });
  scene.on("edit", (editData) => {
    console.log("editData", editData);
    editing.value.show = true;
    editing.value.data = editData;
  });
  scene.on("devicePixelRatio", () => {
    ElMessage.error(
      `当前浏览器缩放${Math.floor(
        window.devicePixelRatio * 100
      )}%比例,请设置缩放比例为100%,方可正常导出`
    );
  });
  scene.on("loaded", () => {
    isSenseLoaded.value = true;
  });
  scene.on("autoSave", () => {
    console.log("autoSave");
    handleAutoSave();
  });
  scene.on("submitScreenshot", (save) => {
    if (window.scene) {
      const params = {
        files: window.scene.blobScreens.map(
          (b, index) => new File([b], `${Date.now()}-${index}.jpg`)
        ),
        caseId: caseId.value,
      };

      setTimeout(async () => {
        try {
          const res = await submitMergePhotos(params);
          console.log("res", res);
          const { data, code } = res;
          const title = `${props.title}-照片卷.jpg`;
          if (data && data.imgUrl) {
            if (save) {
              // debugger;
              saveAs(data.imgUrl, title);
            }
          }
          window.scene.endScreenshot();
          isSenseLoaded.value = true;
        } catch (error) {
          window.scene.endScreenshot();
          isSenseLoaded.value = true;
        }
      }, 500);
    }
  });
};
const onSwiper = (swiper) => {
  console.log("onSwiper");
  swiperRef.value = swiper;
};
const onSlideChange = (swiper) => {
  console.log(swiper);
};
const handleChange = (val, list) => {
  fileList.value = list;
  console.log("handleChange", val, list, fileList.value);
};
const handleRequest = (val, list) => {
  console.log("handleRequest", val, list);
};
const handleUpload = (val) => {
  console.log("handleUpload", val);
};
const handleItem = (item) => {
  let active = sortType.value ? item : Math.floor(item / 2);
  // swiperRef.value.slideTo(active);
  console.log("handleItem", item, active);
};
const handleDetele = async (item) => {
  if (
    await confirm("删除该场景，将同时从案件和融合模型中移除，确定要删除吗？")
  ) {
    const scenes = getCaseScenes(list.value.filter((item) => item !== scene));
    await replaceCaseScenes(props.caseId, scenes);
    refresh();
  }
};
const handleSwitchGrid = async () => {
  const res = await ElMessageBox.confirm(
    "切换模版不包括标注内容，确定要切换吗？",
    "温馨提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "default",
    }
  );
  if (res) {
    sortType.value = !sortType.value;
    window.scene.setMode(0);
    window.scene.clearScene();
    handleClear();
  }
};

const handleLine = () => {
  if (window.scene) {
    window.scene.setMode(1);
  }
};
const handleMark = () => {
  if (window.scene) {
    window.scene.setMode(2);
  }
};

const backPageHandler = () => {
  router.back();
};

const handleSymbol = () => {
  if (window.scene) {
    window.scene.setMode(3);
  }
};
const handleText = () => {
  if (window.scene) {
    window.scene.setMode(4);
  }
};
const handleSave = async () => {
  if (window.scene) {
    const data = scene.player.getDrawData();
    scene.player.syncDrawData();
    console.log("data", data);
    const res = await saveCaseImgTagData({
      caseId: caseId.value,
      data: data,
      isHorizontal: !sortType.value,
    });

    console.log("res", res);
    //TODO bugID: 48011 2024-11-13 17:59:15 隐藏自动导出
    // if (newlist.value.length > 0) {
    //   window.scene.exportScreenshot(false);
    // }
    ElMessage.success("保存成功！");
  }
};

const handleAutoSave = async () => {
  if (window.scene) {
    const data = scene.player.getDrawData();
    scene.player.syncDrawData();
    await saveCaseImgTagData({
      caseId: caseId.value,
      data: data,
      isHorizontal: !sortType.value,
    });
  }
};
const handleFree = () => {
  if (window.scene) {
    window.scene.setMode(0);
  }
};
const handleClear = () => {
  if (window.scene) {
    window.scene.player.clear();
  }
};

const handleEditingUpdate = (data) => {
  // console.log("update", data);
  if (window.scene) {
    window.scene.editing(data);
  }
};
const handleEditingDel = (form) => {
  if (window.scene) {
    const { id, type } = form;
    console.log("handleEditingDel", form);
    window.scene.deleteItemById(id, type);
    window.scene.setMode(0);
  }
};
const handleEditingClose = () => {
  window.scene.setMode(0);
};

const handleImageDel = (ids) => {
  console.log("handleImageDel", ids);
  if (window.scene) {
    window.scene.deleteImageDataByIds(ids);
  }
};
const handleExport = () => {
  if (window.scene) {
    if (!window.isExportScreenshot) {
      isSenseLoaded.value = false;
      window.scene.exportScreenshot();
    }
  }
};

onMounted(() => {
  renderCanvas();
  console.warn("renderCanvas");
});
</script>
<style lang="scss">
.my-photo-upload {
  .upload-demo {
    display: inline-block;
    margin-right: 20px;
    position: relative;
    bottom: -1px;
    .el-upload-list {
      display: none;
    }
  }
}
</style>
<style lang="scss" scoped>
#canvas {
  width: 100%;
  height: 100%;
}

.photo {
  display: flex;
  height: 100%;

  .left {
    width: 260px;
    padding: 16px 24px 30px 16px;
    height: calc(100% - 46.16px);
    overflow-y: auto;
    background: #ffffff;
    box-shadow: 10px 0 10px -10px rgba(0, 0, 0, 0.15);
    // box-shadow: 0px 2px 8px 0px rgba(0,0,0,0.15);
  }

  .right {
    width: calc(100% - 260px);
    background-color: var(--bgColor);
    padding-left: 24px;
    height: 100%;
    position: relative;
    display: block;

    .tools {
      position: absolute;
      top: 15px;
      left: 30px;
    }

    .swiperItem {
      height: calc(100vh - 155.16px);
      width: calc((100vh - 156.16px) * 0.707);
      background: #ffffff;

      .swiperList {
        padding: 0 60px;
        height: 100%;

        .page {
          font-weight: 400;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.85);
          line-height: 22px;
          text-align: right;
          margin-top: 30px;
        }

        .itemper {
          height: calc(50% - 100px);
          padding: 60px 0 0 0;

          .text {
            margin-top: 16px;
            border-radius: 0px 0px 0px 0px;
            border: 1px dotted #cccccc;
            text-align: center;
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            line-height: 30px;
            color: rgba(0, 0, 0, 0.85);
          }

          .itemImg {
            width: 100%;
            height: calc(100% - 48px);
            display: block;
            object-fit: cover;
          }
        }

        .oneItemper {
          height: calc(100% - 120px);

          .itemImg {
          }
        }
      }
    }
  }
}
</style>
<style scoped>
:global(.body-layer) {
  padding-right: 0 !important;
  overflow: hidden;
}
.save {
  background-color: #24569e;
  color: white;
  &:hover {
    background-color: #14396c;
    color: white;
    border-color: #14396c;
  }
}
.opt {
  background-color: #deeafe;
  color: #24569e;
  border: #24569e 1px solid;
  &:hover {
    background-color: #bdcce6;
    color: #14396c;
    border-color: #14396c;
  }
}
.tools {
  i {
    margin-right: 4px;
  }
}
</style>
