<template>
  <div class="df-layout">
    <Header
      class="df-header"
      :type="props.type"
      @back-page="backPageHandler"
      @back="board.back()"
      @forward="board.forward()"
      @view-init="board.viewInit()"
      @save="saveHandler"
      @export="exportHandler"
      :back-disabled="state.backDisabled"
      :forward-disabled="state.forwardDisabled"
      v-if="props && board"
    />

    <div class="df-layout-child">
      <!-- <Eshape v-model:shape="state.selectShape" v-if="state.selectShape" /> -->
      <div class="df-sider">
        <Slider
          :type="props.type"
          :add-shape="state.addShape"
          :exists-bg-image="state.exixtsBgImage"
          @update:add-shape="updateAddShape"
          @track-image="trackImage"
          @selectImage="setBackImage"
          v-if="props"
        />
      </div>
      <div class="df-content">
        <div class="df-content-layout">
          <div class="df-board">
            <canvas ref="dom" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Header from "./header.vue";
import Slider from "./slider.vue";
import Eshape from "./eshape.vue";
import { computed, nextTick, ref } from "vue";
import { RouteName, router } from "@/router";
import { useBoard, title } from "./board/useBoard";
import { selectFuseImage, selectMapImage } from "@/view/case/quisk";
import { CaseTagging } from "@/store/caseTagging";
import saveAs from "@/util/file-serve";
import { BoardTypeDesc } from "@/constant/caseFile";
import { addByMediaLiBrary, updateByTreeFileLists, uploadNewFile } from "@/store/case";
import {
  BoardType,
  SaveCaseFileImageInfo,
  TitleShapeData,
  saveCaseFileImageInfo,
} from "@/store/caseFile";
import { uploadFile } from "@/store/system";

const dom = ref<HTMLCanvasElement>();

const fmtId = ref(0);
const pmtId = ref(0);
const props = computed(() => {
  const route = router.currentRoute.value;
  if (route.name !== RouteName.drawCaseFile || !dom.value) {
    return null;
  } else {
    const params = route.params;
    const fileId = Number(params.id);
    return {
      caseId: Number(params.caseId),
      inAdd: fileId === -1,
      fileId,
      type: params.type.toString() as BoardType,
      dom: dom.value!,
    };
  }
});

const backPageHandler = () => {
  board.value && board.value.clear();
  router.back();
};

const setBackImage = (blob: Blob) => {
  board.value!.setImage(URL.createObjectURL(blob));
};

const updateAddShape = async (s, d) => {
  if (d) {
    state.value.addData = await uploadFile(d);
  }
  state.value.addShape = s;
};

const trackImage = async () => {
  const data =
    props.value!.type === BoardType.scene
      ? await selectFuseImage(props.value!)
      : await selectMapImage({});

  if (data?.blob) {
    setBackImage(data.blob);
    if ("taggings" in data) {
      const tags = data.taggings as CaseTagging[];
      const table = await board.value!.calcTableShape([
        ["序号", "标注"],
        ...tags.map((tag, index) => [`序号${index + 1}`, tag.tagTitle]),
      ]);
      board.value!.setDefaultTable(null, table.content);
    }
  }
};

const { board, state } = useBoard(props);

// 获取通用数据
const getStore = async () => {
  const store = await board.value!.getStore();
  const titleShape = store.shapes.find(
    (shape: any) => shape.type === title
  ) as TitleShapeData;
  return { store, titleShape };
};
function getList() {
  let caseId = props.value?.caseId;
  updateByTreeFileLists(caseId).then(res => {
    let newlist =  res.find(ele => ele.filesTypeName == '三录材料')?.childrenList || [];
    let slclList = newlist.find(ele => ele.filesTypeName == '现场图')?.childrenList || [];
    fmtId.value = slclList.find(ele => ele.filesTypeName == '平面图').filesTypeId
    pmtId.value = slclList.find(ele => ele.filesTypeName == '方位图').filesTypeId
  })
}
getList();
// 保存数据
const saveHandler = async () => {
  const { store, titleShape } = await getStore();
  const args = props.value!;

  const blob = await board.value!.export();
  const body: SaveCaseFileImageInfo = {
    caseId: args.caseId,
    imgType: args.type,
    file: new File([blob], `${args.type}_${args.fileId}.jpg`),
    filesTitle: titleShape?.text || `${args.caseId}_${BoardTypeDesc[args.type]}`,
    content: store && JSON.stringify(store),
  };
  args.inAdd || (body.filesId = props.value!.fileId);
  console.log('args1', args, body);
  const { data } = await uploadNewFile(body);
  const rse = await addByMediaLiBrary({ ...body, caseId: args.caseId,filesTypeId: args.type == 1 ? pmtId.value:fmtId.value, uploadId: data.id });
  console.log('args2',rse, { ...body,caseId: args.caseId, type: args.type, id: data.id });
  if (args.inAdd) {
    router.replace({
      name: RouteName.drawCaseFile,
      params: { caseId: args.caseId, type: args.type, id: rse.filesId },
    });
  }
  await nextTick();
  setTimeout(() => {
    // location.reload();
  }, 100);
};

// 导出图片
const exportHandler = async () => {
  const { titleShape } = await getStore();
  const blob = await board.value!.export();
  saveAs(blob, `${titleShape.text}.jpg`);
};
</script>

<style lang="scss" scoped>
.df-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f0f2f5;
}

.df-header {
  flex: none;
}

.df-layout-child {
  width: 100%;
  height: calc(100% - 5.4rem);
  display: flex;
  position: relative;
}

.df-sider {
  flex: 0 0 340px;
  overflow-y: auto;
  box-sizing: border-box;
  background: #fff;
}

.df-content {
  flex: 1;
  display: grid;
  align-items: center;
  justify-content: center;
  height: 100%;
  overflow: auto;
}

.df-content-layout {
  --w: 297px;
  --h: 210px;
  --padding: 0;
  --calc: 3.5;
  border: calc(var(--padding) * var(--calc)) solid #fff;
}

.df-board {
  // border: 1px solid #000;
  width: calc(var(--w) * var(--calc));
  height: calc(var(--h) * var(--calc));
  box-sizing: border-box;
  canvas {
    background: #fff;
    width: 100%;
    height: 100%;
  }
}
</style>
