<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">箭头</el-button>
        <el-button @click="handleLine">标引</el-button>
        <el-button @click="handleSymbol">符号</el-button>
        <el-button @click="handleText">文本</el-button>
        <el-button @click="handleSave" type="success">保存</el-button>

        <el-button @click="handleClear" v-if="hasDrawData" type="warning"
          >清空</el-button
        >
        <el-button @click="handleFree" v-if="isShowExitEdit" type="warning"
          >退出编辑</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 "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 { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({ caseId: Number });

const editing = ref({
  show: false,
  data: {},
});
const newlist = ref([]);
const fileList = ref([]);
const swiperRef = ref(null);
const childRef = ref(null);
const caseId = ref(props.caseId);
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);
  });
  scene.on("edit", (editData) => {
    console.log("editData", editData);
    editing.value.show = true;
    editing.value.data = editData;
    // debugger;
  });
  scene.on("autoSave", () => {
    console.log("autoSave");
    handleAutoSave();
  });
  scene.on("submitScreenshot", () => {
    if (window.scene) {
      // const data = new FormData();
      // window.scene.blobScreens.forEach((b, index) => {
      //   data.append("files", b, index);
      // });
      const data = {
        files: window.scene.blobScreens.map(
          (b, index) => new File([b], `${Date.now()}-${index}.jpg`)
        ),
        caseId: caseId.value,
      };

      setTimeout(() => {
        submitMergePhotos(data);
        window.scene.endScreenshot();
      }, 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 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,
    });
    ElMessage.success("保存成功！");
    console.log("res", res);
  }
};

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);
  }
};

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 0;
    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: calc(100% - 0px);
    position: relative;

    .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;
}
</style>
