<!--  -->
<template>
  <el-row :gutter="20">
    <el-col :span="8" class="place">
      <el-row class="small-title">
        <h2>通用表格识别</h2>
      </el-row>
      <el-row style="color: gray; font-size: small;">
        <p>支持识别图片/PDF格式文档中的表格内容，包括有线表格、无线表格、合并单元格表格，同时支持单张图片内的多个表格内容识别，返回各表格的表头表尾内容、单元格文字内容及其行列位置信息。</p>
      </el-row>
      <el-row style="color: gray; font-size: small;">
        <h4>支持jpg, png, bmp, pdf等文件格式</h4>
      </el-row>
      <div class="common-layout">
        <el-container>
          <el-input type="file" v-model="fileName" @change="uploadImg"></el-input>
          <OcrLangList />
          <el-button type="primary" @click="predict" :loading="loading">Predict</el-button>
        </el-container>
      </div>
      <div v-show="is_pdf">
        <el-row>
          <el-button-group>
            <el-button type="primary" :icon="ArrowLeft" @click="prePage">上一页</el-button>
            <el-button type="primary" @click="nextPage">
              下一页<el-icon class="el-icon--right">
                <ArrowRight />
              </el-icon>
            </el-button>
          </el-button-group>
          <div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
          <el-container>
            <el-input type="number" v-model="pdf_page"></el-input>
            <el-button type="primary" @click="SetPdfPage" plain>页面跳转</el-button>
          </el-container>
        </el-row>
      </div>
      <el-row>
        <!-- 用于展示图片 -->
        <img id="show-img" class="show-area" />
      </el-row>
      <canvas id="canvas" style="display: none;"></canvas>
    </el-col>
    <el-col :span="16" class="place">
      <el-row class="small-title">
        <h2 style="margin-right: 100;">识别结果展示</h2>
        <el-button type="danger" @click="submitBug" disabled>提交bug</el-button>
      </el-row>
      <div class="demo-collapse">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item title="JSON识别结果" name="1">
            <li v-for="(item, index) in jsonArr" :key="index">
              <el-scrollbar height="600px">
                {{ item }}
              </el-scrollbar>
            </li>
          </el-collapse-item>
          <el-collapse-item title="识别结果" name="2">
            <li v-for="(item, index) in htmlArr" :key="index">
              <el-scrollbar height="auto">
                <div style="display: flex;">
                  <span v-html="item"></span>
                </div>
              </el-scrollbar>
            </li>
          </el-collapse-item>
        </el-collapse>
      </div>
      <el-row>
        <section> 耗时：{{ predictTime }} ms.</section>
      </el-row>
    </el-col>
  </el-row>
</template>

<script lang='ts' setup>
import { reactive, ref } from 'vue'
import { onMounted } from "vue";
import { TableRec, SubmitBug } from '../../../../api/api'
import { createLoadingTask } from "vue3-pdfjs/esm"; // 获得总页数
import { storeToRefs } from 'pinia'
import OcrLangList from '../../../../components/OcrLangList.vue'
import { useOcrLangStore } from '../../../../store/OcrLang';
import { useBugIdStore } from '../../../../store/BugID';
import {
  ArrowLeft,
  ArrowRight,
} from '@element-plus/icons-vue'
import { useServerIpStore } from '../../../../store/ServerIp';
import { useServerPortStore } from '../../../../store/ServerPort';

const si = useServerIpStore();
const { server_ip } = storeToRefs(si);
const sp = useServerPortStore();
const { server_port } = storeToRefs(sp);

const api = "/v1/table_rec";

const ol = useOcrLangStore();
const { ocr_lang } = storeToRefs(ol);

const bi = useBugIdStore();
const { bug_id } = storeToRefs(bi);

// const si = useServerIpStore()
// const { server_ip } = storeToRefs(si);

const state = reactive({
  source: "", //预览pdf文件地址
  pageNum: 1, //当前页面
  numPages: 0, // 总页数
});

let loading = ref(false)
let predictTime = ref(0)
const fileName = ref(null);
const pdf_page = ref(1);

const is_pdf = ref(false);

const activeName = ref('2')

const pdf_img: any = ref("")

const canvas = ref(null as unknown as HTMLCanvasElement);

let jsonArr: any = ref([])
let htmlArr: any = ref([])

let loadingTask: any;

onMounted(async () => {
  canvas.value = document.getElementById("canvas") as HTMLCanvasElement;
});

const uploadImg = () => {
  /**
   * 这里由于操作是绑定在 el-input 上；因此需要在内部重新获取 input 再拿到 file
   */
  const reader = new FileReader();
  // 用于展示
  const showImg = document.getElementById("show-img") as HTMLImageElement;
  // 用于识别
  const rawImg = document.getElementById("raw-img") as HTMLImageElement;
  const inputElement = document
    .getElementsByClassName("el-input")[0]
    .getElementsByTagName("input")[0];

  try {
    const file = inputElement.files![0];
    reader.onload = () => {
      const post_ = file.name.substring(file.name.lastIndexOf("."), file.name.length).toLowerCase();
      if (post_ == ".pdf") {
        state.pageNum = 1;
        // state.scale = 4;
        state.source = URL.createObjectURL(file);
        is_pdf.value = true
        loadingTask = createLoadingTask(state.source);
        getPdfImage(state.pageNum);
      } else
        if (post_ == ".jpg" || post_ == ".png" || post_ == ".bmp" || post_ == ".jpeg") {
          showImg.src = URL.createObjectURL(file);
          rawImg.src = URL.createObjectURL(file);
          is_pdf.value = false
        } else {
          alert('不支持的文件格式！')
          fileName.value = null
        }
    };
    reader.readAsDataURL(file);
  } catch (err) {
    console.error(err);
  }
};

const predict = async () => {
  if (fileName.value == undefined) {
    alert('请上传图片！')
    return;
  }
  if (ocr_lang.value == undefined || ocr_lang.value == "") {
    alert('请先指定语言！')
    return;
  }

  const inputElement = document
    .getElementsByClassName("el-input")[0]
    .getElementsByTagName("input")[0];
  const file = inputElement.files![0];

  loading.value = true

  var data = new FormData();
  data.append('lang', ocr_lang.value);
  // console.log('is_pdf' + is_pdf.value)
  if (is_pdf.value) {
    const file: any = convertCanvasToFile(canvas.value, "pdf.png").then(result => {
      // console.log(result)
      data.append('image', result);
      TableRec(api, data).then(res => {
        console.log(api)
        bug_id.value = res.response_id;
        predictTime.value = res.data.cost;
        jsonArr.value.splice(0);
        let tmp_json = res.data.json_items;
        for (let i = 0; i < tmp_json.length; i++) {
          jsonArr.value.push(JSON.stringify(tmp_json[i], null, 4));
        }

        htmlArr.value.splice(0);
        let tmp_html = res.data.html_items;
        for (let i = 0; i < tmp_html.length; i++) {
          htmlArr.value.push(tmp_html[i]);
        }
        loading.value = false
      }).catch(function (err) {
        loading.value = false
        bug_id.value = ""
        predictTime.value = 0
      });
    })
  } else {
    // console.log(file)
    data.append('image', file);
    TableRec(api, data).then(res => {
      console.log(api)
      bug_id.value = res.response_id;
      predictTime.value = res.data.cost;
      jsonArr.value.splice(0);
      let tmp_json = res.data.json_items;
      for (let i = 0; i < tmp_json.length; i++) {
        jsonArr.value.push(JSON.stringify(tmp_json[i], null, 4));
      }

      htmlArr.value.splice(0);
      let tmp_html = res.data.html_items;
      for (let i = 0; i < tmp_html.length; i++) {
        htmlArr.value.push(tmp_html[i]);
      }
      loading.value = false
    }).catch(function (err) {
      loading.value = false
      bug_id.value = ""
      predictTime.value = 0
    });
  }
};

function SetPdfPage() {
  if (pdf_page.value >= 1 && pdf_page.value <= state.numPages) {
    console.log(pdf_page.value)
    state.pageNum = Number(pdf_page.value);
    getPdfImage(state.pageNum);
  } else {
    console.log(pdf_page.value)
    alert('输入的pdf页面无效！')
  }
}


const submitBug = async () => {
  if (bug_id.value == undefined || bug_id.value == "") {
    alert('请先预测结果！')
    return;
  }

  SubmitBug(api, bug_id.value).then(res => {
    console.log(res.code, res.data)
  }).catch(function (err) {
    console.log(err)
    // loading.value = !loading.value;
  });
};

async function convertCanvasToFile(canvas: HTMLCanvasElement, fileName: any) {
  // 将 Canvas 转为 Blob 对象
  const blob = await new Promise(resolve => canvas.toBlob(blob => {
    resolve(blob);
  }, pdf_img.value.type, 1.0));
  // 手动构造 File 对象
  let file = null;
  try {
    file = new File([pdf_img.value], fileName, { type: pdf_img.value.type });
  } catch (e) {
    // Safari 浏览器不支持直接通过 new File() 创建文件对象，需要手动构造
    const rawFile = blobToFile(blob, fileName);
    file = Object.assign(rawFile, { lastModifiedDate: new Date(), name: fileName });
  }
  return file;
}

// 构建 File 对象
function blobToFile(blob: any, fileName: any) {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
}

function dataURLtoBlob(dataURL: any) {
  var arr = dataURL.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

function getPdfImage(index: number) {
  // console.log(index, state.pageNum)
  loadingTask.promise.then((pdf: any) => {
    state.numPages = pdf.numPages;
    pdf.getPage(index).then((page: any) => {
      const viewport = page.getViewport({ scale: 4.0 })
      canvas.value.height = viewport.height;
      canvas.value.width = viewport.width;
      const destWidth = 398;
      canvas.value.style.width = destWidth + 'px';

      canvas.value.style.height = destWidth * (viewport.height / viewport.width) + 'px';
      const ctx = canvas.value.getContext('2d');
      page.render({
        canvasContext: ctx,
        viewport,
      });
      canvas.value.toBlob(function (blob) {
        pdf_img.value = dataURLtoBlob(canvas.value.toDataURL('images/png', 1.0))
        const showImg = document.getElementById("show-img") as HTMLImageElement;
        showImg.src = canvas.value.toDataURL('images/png', 1.0);
      });
    })
  });
}

function prePage() {
  if (state.pageNum > 1) {
    state.pageNum -= 1;
    getPdfImage(state.pageNum);
  }
}

function nextPage() {
  if (state.pageNum < state.numPages) {
    state.pageNum += 1;
    getPdfImage(state.pageNum);
  }
}

</script>

<style scoped lang="less">
.small-title {
  justify-content: space-between;
  align-items: center;
}

.show-area {
  width: 100%;
}

.place {
  margin-right: auto;
  margin-left: auto;
  border-right: solid 1px #ccc;
}

.page-tool-item {
  padding: 8px 15px;
  padding-left: 10px;
  cursor: pointer;
}

.input_text {
  background-color: #F5F5F5;
  border: 1px solid #CCCCCC;
  padding: 10px;
  margin: 10px;
  border-radius: 5px;
  font-size: 14px;
  color: #333333;
  text-align: left;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.25);
}
</style>