<template>
  <div>
    <div style="width: 100%; display: inline-block; vertical-align: top; height: calc(100vh - 50px - 34px)">
      <umo-editor v-bind="options" ref="editorRef" />
    </div>
  </div>
</template>

<script setup>
import { UmoEditor } from '@umoteam/editor';
import { getPrintTemplate, updatePrintTemplate } from '@/api/oa/base/printTemplate';
import router from '@/router/index.js';
import { useRoute } from 'vue-router';
import { getBaseTemplateVariableList, templateAssign } from '@/api/oa/base/templateVariable/index.js';

const route = useRoute();

const template = ref({});

const editorRef = ref();

let templateData = {};
const options = ref({
  document: {
    title: '',
    content: {
      type: 'doc',
      content: []
    },
    placeholder: {
      en_US: 'Please enter the document content...',
      zh_CN: '请输入文档内容...'
    },
    enableSpellcheck: true,
    enableMarkdown: false,
    enableBubbleMenu: true,
    enableBlockMenu: true,
    readOnly: false,
    autofocus: true,
    characterLimit: 0,
    typographyRules: {
      emDash: false
    },
    editorProps: {},
    parseOptions: {
      preserveWhitespace: 'full'
    },
    autoSave: {
      enabled: true,
      interval: 1000 * 60 * 5
    }
  },
  toolbar: {
    menus: ['base', 'export']
  },
  disableExtensions: [
    'ordered-list',
    'quote',
    'code',
    'select-all',
    'import-word',
    'viewer',
    'print',
    'export-image',
    'export-text',
    'share',
    'embed'
  ],
  page: {
    showBreakMarks: false
  },
  onSave: async (e) => {
    return true;
  },
  onFileUpload: async (e) => {
    console.log(e);
    return e;
  }
});
// 常量赋值
const renderTemplate = (str, data) => {
  return str.replace(/#\{(.*?)\}/g, (_, path) => {
    const arr = path.split('.');
    if (arr.length > 0) {
      arr[0] = `#{${arr[0]}}`;
    }
    return arr.reduce((o, k) => o?.[k], data) ?? ' ';
  });
};
// 数组赋值
const rowRenderTemplate = (str, index) => {
  let res = str;
  res = res.replace(/\^\{(.*?)\}/g, (_, path) => {
    return templateData[`^{${path}}`][index] || ' ';
  });
  res = res.replace(/#\{(.*?)\}/g, (_, path) => {
    const arr = path.split('.');
    if (arr.length > 0) {
      arr[0] = `#{${arr[0]}}`;
    }
    return arr.reduce((o, k) => o?.[k], templateData) || ' ';
  });
  return res;
};
// 是否进行数组赋值
const hasCaretPattern = (arr) => {
  // 正则匹配 ^{xxx}
  const regex = /\^\{.*?\}/;
  let length = 0;
  let res = false;

  function traverse(items) {
    for (const item of items) {
      if (item.text && regex.test(item.text)) {
        // length = Math.max(length, templateData[extractPlaceholders(item.text)].length || 0);
        length = Math.max(length, templateData[item.text].length || 0);
        res = true; // 找到匹配
      }
      if (item.content && Array.isArray(item.content)) {
        traverse(item.content);
      }
    }
  }

  traverse(arr);

  return [res, length];
};

// 数据填充;
const fillRowData = (e, index) => {
  if (Array.isArray(e.content)) {
    e.content.map((item) => {
      return fillRowData(item, index);
    });
  } else {
    e.text = rowRenderTemplate(e.text || ' ', index);
  }
  return e;
};

// 表格处理
const tableTemplate = (table) => {
  const data = JSON.parse(JSON.stringify(table));
  const arr = [];
  data.forEach((item) => {
    const [bol, length] = hasCaretPattern(JSON.parse(JSON.stringify(item.content)));
    if (bol) {
      const obj = JSON.parse(JSON.stringify(item));
      Array(length)
        .fill(0)
        .forEach((_, index) => {
          arr.push(fillRowData(JSON.parse(JSON.stringify(obj)), index));
        });
      // arr.push(fillRowData(JSON.parse(JSON.stringify({ ...item, content: row })), requestData[key]));
    } else {
      arr.push(fillData(item));
    }
  });
  return arr.filter((item) => item);
};

// 根据变量赋值
const fillData = (e) => {
  if (e.type === 'table') {
    e.content = tableTemplate(e.content);
  } else {
    if (Array.isArray(e.content)) {
      e.content.map((item) => {
        return fillData(item);
      });
    } else {
      e.text = renderTemplate(e.text || ' ', templateData);
    }
  }
  return e;
};

const insertText = (e) => {
  const editor = editorRef.value;
  editor.insertContent(
    {
      type: 'text',
      text: e.varName
    },
    {
      updateSelection: false
    }
  );
};

function extractPlaceholders(str) {
  const regex = /[#\^]\{([^}]+)\}/g;
  const result = [];
  let match;
  while ((match = regex.exec(str)) !== null) {
    result.push(match[1]);
  }
  return result;
}

onMounted(async () => {
  const { data: assignData } = await templateAssign({ templateType: 1, contractId: route.query.contractId });
  templateData = {};
  assignData.forEach((item) => {
    // templateData[extractPlaceholders(item.varName)] = item.varValue;
    templateData[item.varName] = item.varValue || ' ';
  });
  // console.log(templateData);
  getPrintTemplate(route.query.templateId).then((e) => {
    template.value = e.data;
    const editor = editorRef.value;
    let margin = JSON.parse(e.data.pageConfig || '{}').pageMargin || { left: 2.1, right: 2.1, top: 2.2, bottom: 2.2 };
    delete margin.layout;
    options.value.page.defaultMargin =margin
    const docData = JSON.parse(e.data.templateData || '{}');
    const data = fillData(docData);
    editor.setContent(data);
    });
});
</script>

<style scoped>
/deep/ .umo-toolbar-actions.ribbon {
  display: none !important;
}

/deep/ .umo-status-bar-left .umo-button:nth-child(4) {
  display: none;
}

/deep/ .umo-status-bar-left .umo-button:nth-child(5) {
  display: none;
}

/deep/ .t-button--theme-warning {
  border-color: var(--td-warning-color-hover);
  background-color: var(--td-warning-color-hover);
}
</style>
<style>
.umo-footer {
  position: sticky;
  bottom: 0px;
}
</style>
