<template>
  <div class="phoneContent">
    <div class="demo-image__preview">
      <el-image-viewer
        hide-on-click-modal
        @close="
          () => {
            urlindex = -1;
          }
        "
        :initial-index="urlindex"
        show-progress
        v-if="urlindex != -1"
        :url-list="photos.map((item) => item.url)"
        fit="cover"
      />
    </div>
    <div class="header">
      <div class="header-left">
        <el-icon
          title="返回"
          style="margin-right: 10px; cursor: pointer"
          size="28px"
          @click="backPageHandler"
          ><ArrowLeft
        /></el-icon>
        <span>{{ title|| '照片制卷' }}</span>
      </div>
      <div class="header-main">
        <i
          class="iconfont icon-backout"
          :class="{ disable: currentIndex < 1 }"
          @click="undo(true)"
          title="撤销"
          style="margin-right: 24px"
        ></i>
        <i
          class="iconfont icon-redo"
          @click="undo(false)"
          :class="{ disable: historylength == currentIndex + 1 }"
          title="恢复"
          style="margin-right: 24px"
        ></i>

        <i
          class="iconfont icon-screen_f"
          @click="toggleFullScreen"
          title="适应视图"
          style="margin-right: 5px"
        ></i>
        <span>
          <div class="border-icon">
            <span :class="{ disable: indexing }">
              <i
                class="iconfont icon-new"
                title="加页"
                @click="() => insertBlankPage()"
                v-if="pages.length == 1 || selectedPageIndex === -1"
                style="margin-right: 24px"
              ></i>
              <el-dropdown
                :class="{ disable: indexing }"
                v-else
                trigger="click"
                @command="handleAddType"
              >
                <i class="iconfont icon-new" style="margin-right: 24px"></i>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="false">
                      <i class="iconfont icon-new_left"></i>
                      左侧新增</el-dropdown-item
                    >
                    <el-dropdown-item :command="true"
                      ><i class="iconfont icon-new_right"></i>
                      右侧新增</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            <el-dropdown trigger="click" @command="handleLayoutChange">
              <i class="iconfont icon-layout" title="模板"></i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="double">
                    <i class="iconfont icon-layout_two"></i>
                    一页两张</el-dropdown-item
                  >
                  <el-dropdown-item command="single">
                    <i class="iconfont icon-layout_h"></i>
                    一张横板
                  </el-dropdown-item>
                  <el-dropdown-item command="landscape">
                    <i class="iconfont icon-layout_one"></i
                    >一张竖版</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown></span
            >
            <i
              class="iconfont icon-indexes"
              title="标引"
              @click="changeIndexing"
              style="padding: 5px; margin-right: 24px"
              :class="{
                disable: pages.length == 1 && pages[0]?.layoutMode != 'double',
                avtive: indexing,
              }"
            ></i>
            <i
              class="iconfont icon-delete"
              style="margin-right: 0"
              title="删除"
              @click="deleteSelectedPage"
              :class="{
                disable: selectedPageIndex === -1,
              }"
            ></i>
          </div>
          <i
            @click="exportToPDF"
            title="导出"
            class="iconfont icon-download"
            style="margin-right: 24px"
          ></i>
        </span>
      </div>
      <div class="header-right" style="align-items: center">
        <div class="view" @click="handleSee">保存</div>
      </div>
    </div>
    <div class="photo-editor">
      <!-- 左侧：照片列表与排版设置 -->
      <div class="left-panel">
        <div class="left-panel-top">
          <div class="left-panel-title">现场照片</div>
          <div class="photo-list">
            <!-- :class="{ selected: selectedPhotos.includes(photo.id) }" -->
            <div
              v-for="(photo, index) in photos"
              :key="photo.id"
              class="photo-item"
              @click="
                () => {
                  urlindex = index;
                }
              "
              @dragstart="handleDragStart($event, photo)"
              draggable
            >
              <img
                :src="
                  photo.url + '?x-oss-process=image/resize,w_300/quality,q_80'
                "
                alt="现场照片"
              />
              <span class="used-tag" @click.stop="toggleSelect(photo.id)">
                <el-icon
                  color="#26559B"
                  v-if="selectedPhotos.includes(photo.id)"
                  ><Check
                /></el-icon>
              </span>
              <div class="selectImg" v-if="selectPhotos.includes(photo.id)">
                已导入
              </div>
            </div>
            <div v-if="photos.length == 0" class="zwsj">暂无现场照片</div>
          </div>
        </div>

        <div class="auto-layout-bar" v-if="selectedPhotos.length">
          <div>
            已选 <span>{{ selectedPhotos.length }}</span> 张照片
          </div>
          <div class="view" @click="autoLayouts">自动排版</div>
        </div>
      </div>

      <!-- 右侧：画布容器 -->
      <div class="right-panel">
        <!-- Canvas容器 -->
        <div class="canvas-container">
          <canvas
            ref="canvas"
            class="canvas-content"
            @click="handleCanvasClick"
            @contextmenu.prevent="handleContextMenu"
            @drop="handleDrop"
            @keydown="handleKeyDown"
            tabindex="0"
            @dragover="handleDragOver"
          ></canvas>
        </div>

        <!-- <div class="control-bar">
        <button @click="resetZoom">重置缩放 (100%)</button>
        <span>当前缩放：{{ Math.round(scale * 100) }}%</span>
      </div> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { throttle } from "@/util";
import {
  ref,
  onMounted,
  onBeforeUnmount,
  watch,
  nextTick,
  computed,
} from "vue";
import { router, RouteName } from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import { exportCasePhotos } from "@/view/material/quisk.ts";
import { CanvasPhotoEditor } from "./canvas-photo-editor.js";
import {
  CirclePlus,
  CircleClose,
  MagicStick,
  Plus,
  Check,
} from "@element-plus/icons-vue";
import {
  getAllPhotoList,
  casePhotoUpdate,
  getCasePhotoRollList,
  casePhotodel,
} from "@/store/case";
let oldCanvas = null;
const caseId = computed(() => router.currentRoute.value?.params?.caseId);
const title = ref("");
const pageCententList = ref([]);
const pageCount = ref(0);

// --- 响应式数据 ---
const canvas = ref(null);
const editor = ref(null);
const indexing = ref(false);
const selectedPageItem = ref({
  index: -1,
  pageIndex: -1,
});
const ImgsrcList = ref([]);
const urlindex = ref(-1);
const photos = ref([]);
const historyPhotos = ref([]);
const selectPhotos = computed(() => {
  if (editor.value) {
    let newlist = historyPhotos.value;
    editor.value.pages.map((ele) => {
      if (ele.list && ele.list.length > 0) {
        newlist = newlist.concat(ele.list);
      }
    });
    return newlist;
  } else {
    return [];
  }
});

const selectedPhotos = ref([]);
const selectedPhotosbf = ref([]);
const layoutMode = ref("double");
const pages = ref([
  {
    list: [null, null],
    layoutMode: layoutMode.value, //排版模式
    coordinate: [], //坐标信息
    item: [], //坐标信息
  },
  {
    list: [null, null],
    layoutMode: layoutMode.value, //排版模式
    coordinate: [], //坐标信息
    item: [], //坐标信息
  },
  {
    list: [null, null],
    layoutMode: layoutMode.value, //排版模式
    coordinate: [], //坐标信息
    item: [], //坐标信息
  },
  {
    list: [null, null],
    layoutMode: layoutMode.value, //排版模式
    coordinate: [], //坐标信息
    item: [], //坐标信息
  },
]);
const scale = ref(1.0);
const selectedPageIndex = ref(-1);
const draggedPhoto = ref(null);
const historylength = ref(0);
const currentIndex = ref(-1);
const getImgList = async () => {
  const { id, filesTypeId } = router.currentRoute.value.query;
  let imgList = await getAllPhotoList(filesTypeId);
  photos.value = imgList.map((ele) => ({
    ...ele,
    url: ele.filesUrl,
    id: ele.filesId,
    name: ele.filesTitle,
  }));
  let count = 0 
  let pageCentent = await getCasePhotoRollList(caseId.value);
  pageCentent.map((ele) => {
    if (ele.content && ele.content != "[]") {
    let content = JSON.parse(ele.content);
      if( ele.id != id){
        let listHiostry =
          content.pages?.flatMap((item) => item.list.filter((i) => i)) || [];
        historyPhotos.value.push(...listHiostry);
      }else{
        pageCount.value = count
      }
      count = count + content.pages?.length
    }
  });
  pageCententList.value = pageCentent;
  let item = pageCentent.find((ele) => ele.id == id);
  if(id && !item){//已删除
    ElMessage.error('当前照片卷已被删除')
    setTimeout(()=>{
      backPageHandler()
    }, 2000)
  }
  title.value = item?.name || "";
  let content = item && item.content && JSON.parse(item?.content);
  // editor.value.drawAllPages(photos.value);
  if (content) {
    // editor.value._layoutMode = content.pages.some(ele =>ele.layoutMode == 'double') ? "double" : "single";
    pages.value = content.pages;
    editor.value.pageCount = pageCount.value;
    editor.value.pages = pages.value;
    editor.value.indexingLineList = content.indexingLineList || [];
  }
};
const handleSee = async () => {
  const { id, filesTypeId } = router.currentRoute.value.query;
  const pages = editor.value?.pages;
  const indexingLineList = editor.value?.indexingLineList;
  const content = JSON.stringify({ pages, indexingLineList });
  if (indexing.value) {
    changeIndexing();
  }
  let { data } = await casePhotoUpdate({
    id,
    caseId: caseId.value,
    name: title.value || `段落` + (pageCententList.value.length + 1) || "",
    content: content,
  });
  ElMessage({
    type: "success",
    message: "保存成功",
  });
  if (!id) {
    router.replace({
      name: RouteName.drawCasePhotos,
      params: { caseId: caseId.value },
      query: {
        id: data.id,
        filesTypeId,
      },
    });
  }
};
const del2 = async () => {
  const { id } = router.currentRoute.value.query;
  ElMessageBox.confirm("当前段落为最后一页，是否删除当前段落？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await casePhotodel({ caseId: caseId.value, id });
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    backPageHandler();
  });
};
// --- 初始化 ---
onMounted(async () => {
  const { id } = router.currentRoute.value.query;
  if (canvas.value) {
    // 创建编辑器实例
    editor.value = new CanvasPhotoEditor(canvas.value, {
      pageWidth: 600,
      pageHeight: 840,
      canvasBgColor: "#efefef",
      pageBgColor: "#ffffff",
      photos: photos.value,
      updata: (value) => {
        selectedPageItem.value = value.selectedPageItem;
        selectedPageIndex.value = value.selectedPageIndex;
        historylength.value = value.historylength;
        currentIndex.value = value.currentIndex;
        console.log("updata", value);
      },
      clearIndexing: changeIndexing,
    });
    await getImgList();
    if (!id) {
      editor.value._pages = pages.value;
    }
    // 绑定容器（用于居中计算）
    editor.value.bindScrollWrapper(canvas.value.parentElement);

    // 初始化绘制
    editor.value.drawAllPages(photos.value);
    editor.value.resetPosition(); // 移除scrollToCenter，用resetPosition

    // 同步初始数据
    scale.value = editor.value.scale;
  }
  document.addEventListener("fullscreenchange", fullScreenChange);
  document.addEventListener("webkitfullscreenchange", fullScreenChange);
  document.addEventListener("MSFullscreenChange", fullScreenChange);
});

// 销毁
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
  }

  document.removeEventListener("fullscreenchange", fullScreenChange);
  document.removeEventListener("webkitfullscreenchange", fullScreenChange);
  document.removeEventListener("MSFullscreenChange", fullScreenChange);
});

// --- 监听数据变化 ---
// watch([pages, layoutMode, selectedPageIndex], () => {
//   if (editor.value) {
//     editor.value.pages = pages.value
//     editor.value.layoutMode = layoutMode.value
//     editor.value.selectedPageIndex = selectedPageIndex.value
//     editor.value.drawAllPages(photos.value)
//     // 移除错误的scrollToCenter调用
//   }
// }, { deep: true })

watch(
  () => editor.value?.scale,
  (newScale) => {
    scale.value = newScale;
  }
);
const backPageHandler = () => {
  router.back();
};
// 撤销
const undo = (type) => {
  //type = true 表示撤销，type = false 表示重做
  if (editor.value) {
    editor.value.indexingNum = 0;
    editor.value.undo(currentIndex.value, type);
  }
};

// 选择左侧照片
const toggleSelect = (photoId) => {
  const idx = selectedPhotos.value.indexOf(photoId);
  if (idx > -1) {
    selectedPhotos.value.splice(idx, 1);
  } else {
    selectedPhotos.value.push(photoId);
  }
};
// 切换全屏
const toggleFullScreen = async () => {
  const element = canvas.value.parentElement;
  oldCanvas = element;
  if (!element) return;

  try {
    if (element.requestFullscreen) {
      await element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) {
      await element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
      await element.msRequestFullscreen();
    }
    editor.value.scrollWrapper = canvas.value.parentElement;
    editor.value.resizeCanvas();
    editor.value.resetPosition();

    // }
  } catch (err) {
    console.warn("全屏操作失败：", err);
  }
};
// 监听用户按 ESC 退出全屏，同步状态
const fullScreenChange = () => {
  console.log("fullScreenChange", oldCanvas?.clientWidth);
  editor.value.bindScrollWrapper(oldCanvas);
};
// 切换排版模式
const handleLayoutChange = async (value) => {
  layoutMode.value = value;
  if (editor.value) {
    let isActiveItem = editor.value.isActiveImg();
    // selectedPageIndex.value = editor.value.selectedPageIndex
    const check = await editor.value.checkIndexing();
    console.log(
      "isActiveItem",
      editor.value.selectedPageIndex,
      check,
      isActiveItem,
      selectedPageIndex.value
    );
    if (selectedPageIndex.value == -1 || isActiveItem) {
      //未选中页面
      if(layoutMode.value != editor.value.layoutMode) editor.value.layoutMode = layoutMode.value;
      autoLayout();
    } else {
      //选中页面
      pages.value = editor.value.setPageType(value);
    }
  }
};
const autoLayouts = async () => {
  const check = await editor.value.checkIndexing();
  selectedPhotosbf.value = selectedPhotos.value;
  autoLayout();
};

// 自动排版
const autoLayout = () => {
  if (editor.value) {
    pages.value = editor.value.autoLayout(selectedPhotosbf.value);
    selectedPhotos.value = []; // 清空已选照片
    selectedPhotosbf.value = []; // 清空已选照片
    editor.value.selectedPageIndex = -1;
    editor.value.selectedPageItem = {
      index: -1,
      pageIndex: -1,
    };
  }
  // editor.value.drawAllPages()
};
const handleAddType = async (type) => {
  const check = await editor.value.checkIndexing();
  console.log("handleAddType", type, check);
  insertBlankPage(type);
};
// 插入空白页
// direction: true-右侧 false-左侧
const insertBlankPage = throttle((direction) => {
  if (editor.value) {
    pages.value = editor.value.insertBlankPage(direction);
  }
}, 500);

const changeIndexing = async () => {
  indexing.value = !indexing.value;
  await nextTick();
  if (editor.value) {
    editor.value.indexing = indexing.value;
    editor.value.selectedPageIndex = -1;
    editor.value.indexingNum = 0;
    editor.value.indexingList = [];
    editor.value.tempArrow = {
      start: null, // { x, y }
      end: null, // { x, y }
      drawing: false, // 是否正在绘制
    };
    editor.value.selectedPageItem = {
      index: -1,
      pageIndex: -1,
    };
    if (indexing.value == false) {
      editor.value.saveHistory();
    }
    editor.value.drawAllPages();
  }
};
// 删除选中页
const deleteSelectedPage = async () => {
  if (editor.value) {
    const check = await editor.value.checkIndexing();
    pages.value = editor.value.deleteSelectedPage(del2);
    // selectedPageIndex.value = editor.value.selectedPageIndex;
  }
};
const handleKeyDown = (e) => {
  console.log("handleKeyDown", e);

  if (e.key === "Delete" || e.key === "Backspace") {
    e.preventDefault();
    deleteSelectedPage();
  }
};
// 重置缩放
const resetZoom = () => {
  if (editor.value) {
    editor.value.resetZoom();
    scale.value = 1.0;
  }
};

// 点击Canvas选中页面
const handleCanvasClick = (e) => {
  if (editor.value) {
    editor.value.getPageIndexByClick(e);
  }
};

// 拖拽照片开始
const handleDragStart = (e, photo) => {
  draggedPhoto.value = photo; // 记录当前拖拽的照片
  e.dataTransfer.effectAllowed = "copy"; // 设置拖拽效果为复制
};

// 拖拽悬浮
const handleDragOver = (e) => {
  e.preventDefault();
  e.dataTransfer.dropEffect = "copy";
};

// 拖拽放下
const handleDrop = async (e) => {
  if (!draggedPhoto.value || !editor.value) return;
  const check = await editor.value.checkIndexing();
  // 获取拖拽到的页面和位置
  const position = editor.value.getPhotoPositionInPage(e);
  const { pageIndex, itemIndex } = position;
  console.log("getPhotoPositionInPage", position, );

  if (pageIndex === -1 || itemIndex === -1) return;
  
  console.log("handleDrop", pages);
  // 更新页面数据
  const newPages = [...pages.value];
  // 确保页面数组存在
  console.log("handleDrop", newPages);
  if (!newPages[pageIndex]) newPages[pageIndex] = [];
  // 确保位置足够
  console.log("handleDrop", newPages[pageIndex], itemIndex);
  while (newPages[pageIndex].list.length <= itemIndex) {
    newPages[pageIndex].list.push("");
  }
  if(newPages[pageIndex].item.length < itemIndex) {
    newPages[pageIndex].item.push(draggedPhoto.value);
  }
  // 放入照片ID
  newPages[pageIndex].list[itemIndex] = draggedPhoto.value.id;
  newPages[pageIndex].item[itemIndex] = draggedPhoto.value;
  console.log("handleDrop", position, newPages[pageIndex], draggedPhoto.value);

  // 同步数据
  pages.value = newPages;
  // selectedPageIndex.value = pageIndex;
  draggedPhoto.value = null;

  // 重新绘制
  editor.value.pages = pages.value;
  editor.value.drawAllPages(photos.value);
  e.preventDefault();
};

/**
 * 重置画布偏移，居中显示当前选中页
 */
const exportToPDF = (paperType) => {
  exportCasePhotos({ showPagesRef: editor.value, title: title.value + '照片卷'});
};
const handleContextMenu = (e) => {
  e.preventDefault();
};
</script>
<style lang="sass">
@import "./style.scss"
</style>