<!--  -->
<template>
  <MainPanel>
    <template v-slot:header>
      <Header :title="headerTitle" :on-back="onBack" type="return">
        <ui-button v-if="!isWrite" style="margin-right: 16px" class="download-btn" type="null" width="96px" @click="downloadHandler"> 下载 </ui-button>
        <ui-button v-if="tableType != 'law'" type="primary" width="96px" @click="saveHandler"> {{ isWrite ? "确定" : "保存" }} </ui-button>
      </Header>
    </template>

    <div v-show="!isWrite" class="mySwiper" v-if="loaded">
      <div class="swiper-wrapper">
        <div class="swiper-slide tables-item" :class="{ show: downMode }" v-for="(i, index) in eleList">
          <div class="warpper" :class="{ downMode, 'no-padding': tableType == 'law' }" :id="`layoutRef${index}`">
            <component
              ref="content"
              :page="askPage"
              :pageIndex="index"
              :text="text"
              @onTextChange="onTextChange"
              @onTextConfirm="onTextConfirm"
              @goWrite="goWrite"
              :downMode="downMode"
              :is="i"
            ></component>
          </div>

          <div class="warpper" v-if="downMode" :class="{ show: downMode, 'no-padding': tableType == 'law' }">
            <component :isDownloadShow="true" :page="askPage" :pageIndex="index" :text="text" @onTextChange="onTextChange" @onTextConfirm="onTextConfirm" @goWrite="goWrite" :is="i"></component>
          </div>
        </div>
      </div>
    </div>
    <Write ref="com" v-if="isWrite" :text="text" :textIndex="textIndex" @onTextConfirm="onTextConfirm"> </Write>
  </MainPanel>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted, nextTick, onActivated, onDeactivated, provide } from "vue";
import { router } from "@/router";
import Swiper from "swiper";
import html2canvas from "html2canvas";
import { downloadImage, uploadImage } from "@/store/sync";
import { genUseLoading } from "@/hook";
import { tables } from "@/store/tables";
import { resetData } from "./data";

import Write from "./write/index.vue";
import Message from "@/components/base/components/message/message.vue";
import Header from "@/components/photos/header.vue";
import MainPanel from "@/components/main-panel/index.vue";
import one from "./explorate-one.vue";
import two from "./explorate-two.vue";
import three from "./explorate-three.vue";
import four from "./explorate-four.vue";
import identification from "./identification.vue";

//授权委托书
import authorOne from "./author/author-one.vue";
import authorTwo from "./author/author-two.vue";

// 血样提取
import extract from "./extract.vue";

//遗留物品
import legacy from "./legacy.vue";
//询问、讯问
import ask from "./ask.vue";
import doc from "./write/doc.vue";

//法规
import law from "./law.vue";
// const eleList = ref([one, two, three, four]);
// const eleList = ref([authorOne, authorTwo]);
const com = ref(null); // 通过 模板ref 绑定子组件
const content = ref(null); // 通过 模板ref 绑定子组件
const eleList = ref([]);
const headerTitle = ref("");
const tableType = ref<string | string[]>();
const downMode = ref(false);
const askPage = ref(1);
const askText = ref("");

const isWrite = ref(false);
const text = ref("");
const textIndex = ref(0);

const setAskPage = () => {
  loaded.value = false;
  eleList.value = [ask];
  if (askPage.value > 1) {
    for (let i = 0; i < askPage.value - 1; i++) {
      eleList.value.push(doc);
    }
  }
  initSwiper();
};
const goWrite = (data) => {
  isWrite.value = true;
  textIndex.value = data.textIndex;
};
const onTextConfirm = (data) => {
  askPage.value = data.page;
  text.value = data.text;
  isWrite.value = false;
  setAskPage();
};
const onTextChange = (data) => {
  text.value = data.text;
};
const downloadHandler = genUseLoading(async () => {
  // if (isWrite.value) {
  //   com.value.onConfirm();
  //   return;
  // }
  await getLayoutImage();
});
const saveHandler = genUseLoading(async () => {
  if (isWrite.value) {
    com.value.onConfirm();
    return;
  }

  saveStore();
  router.replace("/scene");
});

const saveStore = () => {
  let reportData = initData();
  console.error(reportData);
  const origin = tables.value;
  let newData = Object.assign(origin, reportData);
};
const initData = () => {
  let dataList = content.value;

  let obj = {};
  dataList.forEach((item) => {
    if (item.saveHandler) {
      let data = item.saveHandler();

      obj[data.type] = data.data;
    }
  });
  return obj;
};
let slideIndex = 0;
const slideFunc = () => {
  let eles = document.querySelectorAll(".tables-item");
  eles.forEach((item) => {
    item.scrollTo(0, 0);
  });
  return new Promise((res, rej) => {
    if (eleList.value.length == 1) {
      res(true);
    } else {
      mySwiper.value.slideTo(0);
      let t = setInterval(() => {
        if (slideIndex < eleList.value.length - 1) {
          mySwiper.value.slideNext();
        } else {
          clearInterval(t);
          t = null;
          res(true);
        }
      }, 1000);
    }
  });
};
const getLayoutImage = async () => {
  downMode.value = true;
  await nextTick();
  let num = 0;
  await slideFunc();
  return new Promise((res, rej) => {
    eleList.value.forEach(async (element, index) => {
      let ele = document.getElementById(`layoutRef${index}`);
      const canvas = await html2canvas(ele);

      const blob = await new Promise<Blob>((resolve) => {
        return canvas.toBlob(resolve, "image/jpeg", 0.95);
      });
      await downloadImage(blob, `tables_${index}.jpg`);
            Message.success({ msg: "已保存至相册", time: 2000 });
      num++;

      if (num == eleList.value.length) {
        downMode.value = false;
        // router.replace("/scene");
        res(true);
      }
    });
  });

  // return await uploadImage(blob);
};
const initTables = () => {
  tableType.value = router.currentRoute.value.params.name;
  switch (tableType.value) {
    case "explorate":
      eleList.value = [one, two, three, four];
      headerTitle.value = "道路交通事故现场勘查笔录";
      break;
    case "ask":
      eleList.value = [ask];
      if (router.currentRoute.value.query.type == "1") {
        headerTitle.value = "询问笔录";
        if (tables.value.askOne) {
          text.value = tables.value.askOne.text;
          askPage.value = tables.value.askOne.page;
        }
      } else {
        headerTitle.value = "讯问笔录";
        if (tables.value.askTwo) {
          text.value = tables.value.askTwo.text;
          askPage.value = tables.value.askTwo.page;
        }
      }

      isWrite.value = false;
      setAskPage();

      break;
    case "author":
      eleList.value = [authorOne, authorTwo];
      headerTitle.value = "授权委托书";
      break;
    case "legacy":
      eleList.value = [legacy];
      headerTitle.value = "道路交通事故现场遗留物品清单";
      break;
    case "extract":
      eleList.value = [extract];
      headerTitle.value = "当事人血样（尿样）提取登记表";
      break;
    case "identification":
      eleList.value = [identification];
      headerTitle.value = "道路交通事故认定书（简易程序）";
      break;

    case "law":
      eleList.value = [law];
      headerTitle.value = "法律法规";
      break;
  }
};
const mySwiper = ref(null);
const loaded = ref(false);
const initSwiper = () => {
  if (mySwiper.value) {
    mySwiper.value.destroy(true);
  }
  loaded.value = true;
  mySwiper.value = null;
  nextTick(() => {
    if (loaded.value) {
      mySwiper.value = new Swiper(".mySwiper", {
        on: {
          init: function (swiper) {
            // initPage();
            // console.error(swiper);
          },
          transitionStart: function (swiper) {
            slideIndex = swiper.activeIndex;
          },
          touchStart: function (swiper, event) {},
        },
      });
    }
  });
};
const onBack = () => {
  if (isWrite.value) {
    isWrite.value = false;
    return;
  }
  router.back();
};
onActivated(() => {
  initTables();
  initSwiper();
});
const scale = ref("1");
const initPage = () => {
  let parent = document.getElementById("layoutRef0");
  let children = parent.children[0];
  // console.error(768 / children.offsetHeight);
  scale.value = ((768 - 100) / children.clientHeight).toFixed(2);
};
onMounted(() => {});
onDeactivated(() => {
  isWrite.value = false;
  text.value = "";
  loaded.value = false;

  resetData();
});
</script>
<style></style>
<style lang="scss" scoped>
.download-btn {
  border-color: #3a3d3d;
  background-color: #3a3d3d !important;
  color: #fff;
}
.mySwiper {
  height: 100%;
  width: 100%;
  color: #000;
  padding-top: 50px;
  font-size: 20px;

  font-family: sr, st;
  .swiper-wrapper {
    height: 100%;
    width: 100%;
    .swiper-slide {
      height: 100%;
      width: 100%;
      overflow: auto;
      &.show {
        overflow: hidden;
      }

      > .warpper {
        padding: 20px 50px 30px;
        &.no-padding {
          padding: 0;
        }
        &.downMode {
          padding: 125px 100px 75px;
          width: 1050px;
          height: 1485px;
          box-sizing: border-box;

          // transform: scale(.5) translateY(-52%);
          transform: translateY(-100%);
          position: absolute;
        }
        &.show {
          padding: 125px 100px 75px;
          width: 1050px;
          height: 1485px;
          box-sizing: border-box;

          transform: scale(0.5) translateY(-52%);
        }
        // height: 100%;
        // width: 100%;
        // line-height: 100px;
        // text-align: center;
      }
    }
  }
}
</style>
