<template>
  <div class="edito_youmei">
    <header_local />
    <div class="onlineTextMain">
      <div class="flex1">
        <div class="btn-grounp">
          文章内容
          <el-button
            type="primary"
            style="margin-top: 0.3em; margin-right: 0.5em"
            @click="clearError"
            :icon="Delete"
          >
            清空
          </el-button>
          <el-button
            type="primary"
            style="float: right; margin-top: 0.3em; margin-right: 0.5em"
            class="jiaoyan"
            @click="exportFun"
          >
            导 出
          </el-button>
          <el-button
            type="primary"
            style="float: right; margin-top: 0.3em; margin-right: 0.5em"
            class="jiaoyan"
            @click="getServer"
          >
            校 验
          </el-button>
        </div>
        <div class="Fle">
          <Editor v-model:rawText="rawText" />
        </div>
      </div>
      <div class="flex2">
        <div class="btn-grounp">
          校对结果
          <div class="errTypes">
            <div
              @click="tabSelect[0] = !tabSelect[0]"
              :class="{ errType: true, checkboxLabel0: tabSelect[0] }"
            >
              严重错误 {{ errorTotle.serious }}
            </div>
            <div
              @click="tabSelect[1] = !tabSelect[1]"
              :class="{ errType: true, checkboxLabel1: tabSelect[1] }"
            >
              一般错误 {{ errorTotle.same }}
            </div>
            <div
              @click="tabSelect[2] = !tabSelect[2]"
              :class="{ errType: true, checkboxLabel2: tabSelect[2] }"
            >
              疑错 {{ errorTotle.distrust }}
            </div>
            <div
              @click="tabSelect[3] = !tabSelect[3]"
              :class="{ errType: true, checkboxLabel3: tabSelect[3] }"
            >
              自定义错误 {{ errorTotle.custom }}
            </div>
          </div>
        </div>
        <el-tabs tab-position="top" v-model="tabAct">
          <el-tab-pane :label="'未处理:' + untreatedError.length" :name="0">
            <proofread-errors
              listName="untreatedError"
              :lastAtom="lastAtom"
              :list="untreatedError"
              :tabSelect="tabSelect"
              @selectErrorFunc="selectErrorFunc"
              @replaceText="replaceText"
              @ignoreText="ignoreText"
              @deleteText="deleteText"
            ></proofread-errors>
          </el-tab-pane>
          <el-tab-pane :label="'已忽略:' + ignoreError.length" :name="1">
            <proofread-errors
              listName="ignoreError"
              :list="ignoreError"
              :tabSelect="tabSelect"
              @resumeText="resumeText"
            ></proofread-errors>
          </el-tab-pane>
          <el-tab-pane :label="'已替换:' + replaceError.length" :name="2">
            <proofread-errors
              listName="replaceError"
              :list="replaceError"
              :tabSelect="tabSelect"
              @resumeText="resumeText"
            ></proofread-errors>
          </el-tab-pane>
          <el-tab-pane :label="'已删除:' + deleteError.length" :name="3">
            <proofread-errors
              listName="deleteError"
              :list="deleteError"
              :tabSelect="tabSelect"
              @resumeText="resumeText"
            ></proofread-errors>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import config from '@/config/index';
import header_local from './components/header.vue';
import Editor from '@/components/editor.vue';
import { Delete } from '@element-plus/icons-vue';
import { ref } from 'vue';
import errType from '../../../config/errtype';
import { check } from '../../api/index';
import proofreadErrors from './components/proofread_errors.vue';

const rawText = ref('');
const tabSelect = ref([true, true, true, true]);
const untreatedError = ref([]);
const ignoreError = ref([]);
const replaceError = ref([]);
const deleteError = ref([]);
const errorTotle = ref({
  serious: 0,
  same: 0,
  distrust: 0,
  custom: 0,
});
const tabAct = ref(0);

let lastAtom = ref(-1);

// 清理数据
function clearError() {
  rawText.value = '';
  untreatedError.value = [];
  ignoreError.value = [];
  replaceError.value = [];
  deleteError.value = [];
}

// 获取数据
function getServer() {
  if (!window.fetch) return;
  errorTotle.value = {
    serious: 0,
    same: 0,
    distrust: 0,
    custom: 0,
  };

  untreatedError.value = [];
  ignoreError.value = [];
  replaceError.value = [];
  deleteError.value = [];
  check({
    data: {
      text: rawText.value || config.base.default_text || '',
    },
  }).then(res => {
    const list = res.checklist || [];
    let rawTextF = res.rawText || '';
    for (let i = 0; i < list.length; i++) {
      const v = list[i];
      const r = new RegExp(`data-umpos="${v.colorPosition}"`, 'g');
      let rText = `data-umpos="${
        v.colorPosition
      }" style="border-bottom: 3px solid rgb(${errType[v.um_error_level]});`;
      if (i == 0) {
        rText += `background-color: rgba(${errType[v.um_error_level]}, 0.5)`;
        lastAtom.value = v.colorPosition;
      }
      rText += `"`;
      rawTextF = rawTextF.replace(r, rText);

      if (v.um_error_level == 1) errorTotle.value.serious++;
      if (v.um_error_level == 2) errorTotle.value.same++;
      if (v.um_error_level == 3) errorTotle.value.distrust++;
      if (v.um_error_level == 4) errorTotle.value.custom++;
    }
    rawText.value = rawTextF;
    untreatedError.value = list;
    ignoreError.value = [];
    replaceError.value = [];
    deleteError.value = [];
  });
}

// 选中的文案
function selectErrorFunc(data) {
  const newele = getEle(data.colorPosition);
  if (newele === null) return;
  let oldele = null;
  if (lastAtom.value != -1) {
    oldele = document.querySelector(`[data-umpos='${lastAtom.value}']`);
    oldele.style.backgroundColor = '';
  }
  newele.style.backgroundColor = `rgba(${errType[data.um_error_level]}, 0.5)`;
  lastAtom.value = data.colorPosition;
}

// 替换文案
function replaceText(data) {
  const newele = getEle(data.item.colorPosition);
  if (newele === null) return;
  const fDoc = document.querySelector('.Fle .text');
  const outerHTML = newele.outerHTML || '';
  newele.outerHTML = `<span data-umpos="${data.item.colorPosition}">${
    data.item.suggest[data.index]
  }</span>`;
  rawText.value = fDoc.innerHTML;
  removeList(data.name, data.pindex, data.item);
  replaceError.value.push({ ...data.item, outerHTML });
}

// 忽略
function ignoreText(data) {
  const newele = getEle(data.item.colorPosition);
  if (newele === null) return;
  const fDoc = document.querySelector('.Fle .text');
  const outerHTML = newele.outerHTML || '';
  newele.outerHTML = `<span data-umpos="${data.item.colorPosition}">${newele.innerHTML}</span>`;
  rawText.value = fDoc.innerHTML;
  removeList(data.name, data.pindex, data.item);
  ignoreError.value.push({ ...data.item, outerHTML });
}

// 删除
function deleteText(data) {
  const newele = getEle(data.item.colorPosition);
  if (newele === null) return;
  const fDoc = document.querySelector('.Fle .text');
  const outerHTML = newele.outerHTML || '';
  newele.outerHTML = `<span data-umpos="${data.item.colorPosition}"></span>`;
  rawText.value = fDoc.innerHTML;
  removeList(data.name, data.pindex, data.item);
  deleteError.value.push({ ...data.item, outerHTML });
}

// 恢复
function resumeText(data) {
  const newele = getEle(data.item.colorPosition);
  if (newele === null) return;
  const fDoc = document.querySelector('.Fle .text');
  newele.outerHTML = data.item.outerHTML;
  rawText.value = fDoc.innerHTML;
  removeList(data.name, data.pindex, data.item);
  untreatedError.value.push(data.item);
}

// remove list
function removeList(key, index, item) {
  const C = lastAtom.value !== item.colorPosition;
  if (key === 'deleteError') {
    deleteError.value.splice(index, 1);
    if (C) return;
    deleteError.value[0] && selectErrorFunc(deleteError.value[0]);
    return;
  }
  if (key === 'ignoreError') {
    ignoreError.value.splice(index, 1);
    if (C) return;
    ignoreError.value[0] && selectErrorFunc(ignoreError.value[0]);
    return;
  }
  if (key === 'replaceError') {
    replaceError.value.splice(index, 1);
    if (C) return;
    replaceError.value[0] && selectErrorFunc(replaceError.value[0]);
    return;
  }
  if (key === 'untreatedError') {
    untreatedError.value.splice(index, 1);
    if (C) return;
    untreatedError.value[0] && selectErrorFunc(untreatedError.value[0]);
    return;
  }
}
// 获得选中的元素
function getEle(colorPosition) {
  const newele = document.querySelector(`[data-umpos='${colorPosition}']`);
  if (!newele) return null;
  return newele;
}

// 导出word
function exportFun() {
  /**
   * wps: kswps
   * docx: msword
   */
  let blob = new Blob([`<body>${rawText.value}</body>`], {
    type: 'application/kswps',
  });
  let url = URL.createObjectURL(blob);
  let link = document.createElement('a');
  link.setAttribute('href', url);
  link.setAttribute('download', `智能校对.docx`);
  link.click();
}
</script>

<style scoped>
.onlineTextMain {
  padding: 1em;
  display: flex;
}

.onlineTextMain > div {
  flex: 3;
  margin-right: 0.5em;
  border: 1px solid #eee;
  height: calc(100vh - 106px);
}
.onlineTextMain .flex2 {
  flex: 2;
  overflow: hidden;
}
.onlineTextMain > div:last-child {
  margin-right: 0;
}
.btn-grounp {
  color: #666;
  background-color: #f9fafc;
  line-height: 2.8em;
  padding-left: 0.5em;
  border-bottom: 1px solid #eee;
}

.flex1 {
  line-height: 1.5em;
  min-height: 1.5em;
}
.flex1 span {
  display: inline-block;
}
.Fle {
  height: calc(100vh-226px);
}

.errTypes {
  display: flex;
  padding: 0 0 1em 0;
}
.errType {
  flex: 1;
  font-size: 12px;
  margin-right: 3px;
  border: 1px solid;
  padding: 0 0.5em;
  text-align: center;
  border-radius: 5px;
  line-height: 2.5em;
  cursor: pointer;
  color: #909090;
  background-color: hsla(0, 0%, 56.5%, 0.1);
}
.errTypes .checkboxLabel0 {
  color: rgb(255, 68, 99);
  border-color: rgb(255, 68, 99);
  background-color: rgba(255, 68, 99, 0.1);
}
.errTypes .checkboxLabel1 {
  color: rgb(145, 155, 218);
  border-color: rgb(145, 155, 218);
  background-color: rgba(145, 155, 218, 0.1);
}
.errTypes .checkboxLabel2 {
  color: rgb(255, 152, 0);
  border-color: rgb(255, 152, 0);
  background-color: rgba(255, 152, 0, 0.1);
}
.errTypes .checkboxLabel3 {
  color: rgb(156, 133, 255);
  border-color: rgb(156, 133, 255);
  background-color: rgba(156, 133, 255, 0.1);
}
</style>

<style>
.edito_youmei .el-popper.is-light,
.edito_youmei .el-popper .el-popper__arrow::before {
  background-color: #2974ff !important;
  color: #fff;
  border-color: #2974ff !important;
}

.el-poper .selectSpan {
  border-bottom: 3px solid #fff;
}
</style>
