<!--  -->
<template>
  <el-row :gutter="20" class="page">
    <el-col :span="12" class="place">
      <el-row class="small-title">
        <h2>通用文字识别</h2>
      </el-row>
      <el-row style="color: gray; font-size: small;">
        <p>支持识别图片/通过领先的深度学习技术，对各种表格，图片，文档、证件、面单等多种通用场景进行快速、精准的检测和识别，支持简体中文/繁体中文/英文/西欧主流语言等多种种语言，同时支持印刷体、手写体、倾斜、折叠、旋转等。</p>
      </el-row>
      <el-row style="color: gray; font-size: small;">
        <h4>支持jpg, png, bmp, pdf等文件格式,点击灰色区域或者直接拖拽文件至灰色区域上传文件</h4>
      </el-row>
      <el-row>
        <ShowImage :show-src-image=true />
      </el-row>
      <el-row style="height: 200px; width: 100%; position: relative;">
        <FileUpload />
      </el-row>
      <OcrLangList />
      <el-row style="position: absolute;">
        <PdfPreview />
        <el-button type="primary" @click="predict" :loading="loading">Predict</el-button>
      </el-row>
    </el-col>
    <el-col :span="12" class="place">
      <el-row class="small-title">
        <h2 style="margin-right: 0;">识别结果展示</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">
            <el-scrollbar height="600px">
              <pre>{{ json_result }}</pre>
            </el-scrollbar>
          </el-collapse-item>
          <el-collapse-item title="识别结果" name="2">
            <el-scrollbar height="600px">
              <ul>
                <li v-for="(item, index) in recArr" :key="index" @click="handleClick(index, item)"
                  :style="index == selectedItem ? 'color: blue' : ''">
                  {{ item }}
                </li>
              </ul>
            </el-scrollbar>
          </el-collapse-item>
        </el-collapse>
      </div>
      <el-row>
        <section> 耗时：{{ predictTime }} ms.</section>
      </el-row>
    </el-col>
  </el-row>
</template>

<script lang='ts' setup>
import { OcrRec, SubmitBug } from '../../../../api/api'
import { storeToRefs } from 'pinia'
import { fabric } from 'fabric';
import { reactive, ref, onMounted } from 'vue'
import { useOcrLangStore } from '../../../../store/OcrLang';
import { useServerStore } from '../../../../store/Server';
import { useCanvasImgStore } from '../../../../store/CanvasImg';


import OcrLangList from '../../../../components/OcrLangList.vue'
import FileUpload from '../../../../components/FileUpload.vue'
import ShowImage from '../../../../components/ShowImage.vue'
import PdfPreview from '../../../../components/PdfPreview.vue'

const si = useServerStore();
const { server_ip, server_port, api_ocr } = storeToRefs(si);
const my_canvas = useCanvasImgStore();
const { input_file, show_image, show_canvas, fabric_canvas } = storeToRefs(my_canvas);
const ol = useOcrLangStore();
const { ocr_lang } = storeToRefs(ol);

let loading = ref(false)
let show_predict = ref(false)
let predictTime = ref(0)
const fileName = ref(null as unknown as string);

let selectedItem = ref(-1)

let recArr: any = ref([])
const rec_result = ref("");
let bugId = ref("");
const activeName = ref('2')
const json_result = ref("");

interface iRect {
  left: number,
  top: number,
  width: number,
  height: number
}

let rects: any = []

type RectWithId = fabric.Rect & { id: number };

function CreateRect(canvas: any, i: number, left: number, top: number, width: number, height: number, highlight: boolean) {
  var rect = new fabric.Rect({
    left: left,
    top: top,
    width: width,
    height: height,
    fill: 'transparent',
    stroke: highlight ? 'blue' : 'green',
    strokeWidth: 2,
    opacity: 1.0,
    selectable: false,
    name: highlight ? 'high' : 'normal',
  }) as RectWithId;
  rect.set('id', i);
  rect.on('mouseup', function () {
    selectedItem.value = i;
    let objects = fabric_canvas.value.getObjects();
    for (let i = 0; i < objects.length; i++) {
      if (objects[i].name === 'high') {
        // 找到名为 rectName 的矩形元素，执行删除操作等
        fabric_canvas.value.remove(objects[i]);
        break;
      }
    }
    CreateRect(fabric_canvas.value, i, rects[i].left, rects[i].top, rects[i].width, rects[i].height, true);
  });
  canvas.add(rect);
}

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

  if (fabric_canvas.value != null) {
    fabric_canvas.value.dispose();
    fabric_canvas.value = null;
    fabric_canvas.value = new fabric.Canvas(show_canvas.value);
  }
  rects.splice(0)

  loading.value = !loading.value
  var data = new FormData();
  data.append('lang', ocr_lang.value);
  data.append('image', input_file.value);

  OcrRec(api_ocr.value, data).then(res => {
    // console.log(res.code)
    json_result.value = JSON.stringify(res.data, null, 4);
    rec_result.value = res.data.text.reduce((total: any, cur: any) => total + `<p>${cur}</p>`);
    recArr.value.splice(0);
    let tmp_text = res.data.text;
    if (tmp_text.length == 0) {
      alert('未检测到结果！');
    } else {
      for (let i = 0; i < tmp_text.length; i++) {
        recArr.value.push(tmp_text[i]);
      }
    }
    let tmp_boxes = res.data.boxes;
    const h_radio = show_image.value.height / show_image.value.naturalHeight;
    const w_radio = show_image.value.width / show_image.value.naturalWidth;
    for (let i = 0; i < tmp_boxes.length; i++) {
      let left = w_radio * tmp_boxes[i][0];
      let top = h_radio * tmp_boxes[i][1];
      let width = w_radio * (tmp_boxes[i][2] - tmp_boxes[i][0]);
      let height = h_radio * (tmp_boxes[i][5] - tmp_boxes[i][1]);
      const rect: iRect = { left, top, width, height };
      rects.push(rect);
      CreateRect(fabric_canvas.value, i, left, top, width, height, false);
    }
    predictTime.value = res.data.cost;
    loading.value = !loading.value;
    bugId.value = res.response_id;
    if (show_predict.value === false)
      show_predict.value = !show_predict.value;
  }).catch(function (err) {
    loading.value = !loading.value;
    bugId.value = ""
    predictTime.value = 0
  });
};

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


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

async function handleClick(index: any, item: any) {
  selectedItem.value = index;
  let objects = fabric_canvas.value.getObjects();
  for (let i = 0; i < objects.length; i++) {
    if (objects[i].name === 'high') {
      // 找到名为 rectName 的矩形元素，执行删除操作等
      fabric_canvas.value.remove(objects[i]);
      break;
    }
  }
  CreateRect(fabric_canvas.value, index, rects[index].left, rects[index].top, rects[index].width, rects[index].height, true);
}

onMounted(async () => {
  console.log('ocr mounted')
  input_file.value = undefined
})
</script>

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

.page {
  height: 100%;
  width: 100%;
}

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