<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>
          <ShowImage :show-src-image=true   />
        </el-row>
        <el-row style="height: 200px; width: 100%; position: relative;">
          <FileUpload />
        </el-row>
        <el-row style="color: gray; font-size: small;">
          <h4>支持jpg, png, bmp, pdf等文件格式,点击灰色区域或者直接拖拽文件至灰色区域上传文件</h4>
        </el-row>
        <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>
          <h2>印章</h2>
          <el-scrollbar height="auto">
            <ul>
              <li v-for="(item, index) in stampArr" :key="index" @click="figureHandleClick(index, item, stamp_rects)"
                :style="index == stampSelectedItem ? 'color: blue' : ''">
                {{ item }}
              </li>
            </ul>
          </el-scrollbar>
        </div>
        <el-row>
          <section> 耗时：{{ predictTime }} ms.</section>
        </el-row>
      </el-col>
    </el-row>
  </template>
  
  <script lang="ts" setup>
  import { Detection, SubmitBug } from '../../../../api/api'
  import { fabric } from 'fabric';
  import { reactive, ref, onMounted } from 'vue'
  
  import { storeToRefs } from 'pinia'
  import { useServerStore } from '../../../../store/Server';
  import { useCanvasImgStore } from '../../../../store/CanvasImg';
  
  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_stamp_detection } = storeToRefs(si);
  const my_canvas = useCanvasImgStore();
  const { input_file, fabric_canvas, show_canvas, show_image } = storeToRefs(my_canvas);
  
  
  let loading = ref(false)
  let show_predict = ref(false)
  let predictTime = ref(0)
  const fileName = ref(null as unknown as string);
  let stampSelectedItem = ref(-1)
  
  let stampArr: any = ref([])
  
  let bugId = ref("");
  const json_result = ref("");
  
  interface iRect {
    left: number,
    top: number,
    width: number,
    height: number
  }
  
  let stamp_rects: any = []
  
  type RectWithId = fabric.Rect & { id: number };
  
  function CreateRect(canvas: any, i: number, left: number, top: number, width: number, height: number, highlight: boolean, label: number) {
    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);
    canvas.add(rect);
  }
  
  const predict = async () => {
    fileName.value = ''
    fileName.value = input_file.value?.name
    if (fileName.value == undefined || fileName.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);
      fabric_canvas.value.clear()
    }
    stamp_rects.splice(0)
  
    loading.value = !loading.value
    var data = new FormData();
    data.append('image', input_file.value);
  
    Detection(api_stamp_detection.value, data).then(res => {
      // console.log(res.code)
      json_result.value = JSON.stringify(res.data, null, 4);
      console.log(res.data);
      // rec_result.value = res.data.text.reduce((total: any, cur: any) => total + `<p>${cur}</p>`);
      stampArr.value.splice(0);
      let tmp_labels = res.data.labels;
      if (tmp_labels.length == 0) {
        alert("no result!");
      } else {
        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_labels.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][3] - tmp_boxes[i][1]);
          const rect: iRect = { left, top, width, height };
          if (tmp_labels[i] == "Seal") {
            stampArr.value.push("印章");
            stamp_rects.push(rect);
            CreateRect(fabric_canvas.value, i, left, top, width, height, false, 1);
          }
        }
        stampArr.value.reverse();
        for (let i = 0; i < stampArr.value.length; i++) {
          stampArr.value[i] = stampArr.value[i] + " -- " + String(i + 1);
        }
      }
      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_stamp_detection.value, bugId.value).then(res => {
//       console.log(res.code, res.data)
//     }).catch(function (err) {
//       console.log(err)
//       // loading.value = !loading.value;
//     });
//   };
  
  onMounted(async () => {
    console.log('layout analysis mounted')
    input_file.value = undefined
  })
  
  async function figureHandleClick(index: any, item: any, rects: any) {
    stampSelectedItem.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, 1);
  }
  </script>
  
  <style scoped>
  .page {
    width: 100%;
    height: 100%;
  }
  
  .place {
    margin-right: auto;
    margin-left: auto;
    border-right: solid 1px #ccc;
  }
  
  .small-title {
    justify-content: space-between;
    align-items: center;
  }
  </style>
  