<template>
  <div class="template-textarea">
    <div class="rich-editor" v-html="processedContent"></div>
  </div>
</template>

<script>
import CKEditor from "ckeditor4-vue"; //@input="handleInput"
import { findData } from "@/api/sourceData";
export default {
  name: "app",
  emits: ["onUpdateData"],
  compnents: {
    // ckeditor: CKEditor.component
  },
  props: {
    coms: {
      type: Array,
      default: () => {
        return [];
      },
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
    com: {
      type: Object,
      default: null,
    },
  },
  watch: {
    com: {
      handler(val) {
        if (val && val.content) {
          this.updateProcessedContent();
        }
        /*  let _this = this;
        if (val == null) return;
        if (val.content == undefined || val.content == null) return;
        _this.replaceData(val.content).then((res) => {
          _this.content = res;
          _this.$emit("onUpdateData", this.currentIndex, res);
        }); */
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      content: "",
      processedContent: "",
    };
  },
  methods: {
    async updateProcessedContent() {
      this.processedContent = await this.replaceData(this.com.content);
    },
    async replaceData(data) {
      let _this = this;
      for (var i = 0; i < _this.com.attrs.length; i++) {
        let attrId = _this.com.attrs[i].id;
        if (_this.com.attrs[i].type == "variable") {
          let item = _this.com.attrs[i];
          if (item.data.value_type == 2) {
            //多选
            let dataItem = item.data.value_item.split(",");
            let selectHtml =
              '<select id="' +
              attrId +
              '"  data-index="' +
              i +
              '" class="text-input-box">';
            for (var l = 0; l < dataItem.length; l++) {
              if (item.content == dataItem[l]) {
                selectHtml +=
                  '<option value="' +
                  dataItem[l] +
                  '" selected>' +
                  dataItem[l] +
                  "</option>";
              } else {
                selectHtml +=
                  '<option value="' +
                  dataItem[l] +
                  '">' +
                  dataItem[l] +
                  "</option>";
              }
            }
            selectHtml += "</select>";
            data = data.replace("{{" + item.id + "}}", selectHtml);
          } else {
            //文本
            data = data.replace(
              "{{" + attrId + "}}",
              /* `<input type="text" class="text-input-box"  data-index="${i}" value="${_this.com.attrs[i].content}" @input="updateContent('${_this.com.attrs[i].id}', $event)" id="${attrId}">`, */
              '<input type="text" ref="input_' +
                attrId +
                '" name="' +
                _this.com.attrs[i].name +
                '" id="' +
                attrId +
                '"  data-index="' +
                i +
                '" class="text-input-box" value="' +
                _this.com.attrs[i].content +
                '">'
            );
          }
        }else if(_this.com.attrs[i].type == "variableNull"){
          let item = _this.com.attrs[i];
          data = data.replace(
              "{{" + attrId + "}}",
              '<input type="text" ref="input_' +
                attrId +
                '" name="' +
                _this.com.attrs[i].name +
                '" id="' +
                attrId +
                '"  data-index="' +
                i +
                '" class="text-input-boxs auto-width" value="' +
                _this.com.attrs[i].content +
                '">'
            );

        }  else if (_this.com.attrs[i].type == "ProductAttr") {
          //处理产品属性值
          let item = _this.com.attrs[i];
          let prodAttrId = item.id + "_" + i;
          if (item.content == "") {
            item.content = item.attrs.value;
          }
          if (item.attrs.type == 1) {
            //输入框
            data = data.replace(
              "{{" + item.id + "}}",
              '<input type="text" id="' +
                prodAttrId +
                '"  data-index="' +
                i +
                '" class="text-input-box" value="' +
                item.content +
                '">'
            );
          } else {
            //选择框
            let dataItem = item.attrs.valueItems.split(",");
            let selectHtml =
              '<select id="' +
              prodAttrId +
              '"  data-index="' +
              i +
              '" class="text-input-box">';
            for (var l = 0; l < dataItem.length; l++) {
              if (item.content == dataItem[l]) {
                selectHtml +=
                  '<option value="' +
                  dataItem[l] +
                  '" selected>' +
                  dataItem[l] +
                  "</option>";
              } else {
                selectHtml +=
                  '<option value="' +
                  dataItem[l] +
                  '">' +
                  dataItem[l] +
                  "</option>";
              }
            }
            selectHtml += "</select>";
            data = data.replace("{{" + item.id + "}}", selectHtml);
          }
        } else if (_this.com.attrs[i].type == "formual") {
          //// console.log('attrs',_this.com.attrs[i]);
          //处理计算公式 不处理
          let formual = await _this.analysisFormual(_this.com.attrs[i]);

          formual = await _this.getRemote(formual);
          _this.com.attrs[i].content = eval(formual);
          data = data.replace("{{" + attrId + "}}", eval(formual));
        } else if (_this.com.attrs[i].type == "sourceData") {
          let result = await _this.getRemote1(_this.com.attrs[i].formula);
          data = data.replace("{{" + attrId + "}}", result);
        } else if (_this.com.attrs[i].type == "Directory") {
          const directoryContent = _this.com.attrs[i].number+'. '+_this.com.attrs[i].content;;
          const level = _this.com.attrs[i].level || 1; // 默认为1级目录
          const attrId = _this.com.attrs[i].id;

          // 创建一个更灵活的正则表达式模式
          const directoryRegex = new RegExp(`{{\\s*${attrId}\\s*}}`, "g");

          // 替换内容，直接在标题标签上应用类名
          data = data.replace(directoryRegex, (match, offset, string) => {
            // 根据级别创建适当的HTML标签
            const tag = `h${Math.min(level, 6)}`; // 限制最大级别为h6
            const className = `directory-level-${level}`;
            return `<${tag} class="${className}">${directoryContent}</${tag}>`;
          });
          /* const directoryContent = _this.com.attrs[i].content;
          const attrId = _this.com.attrs[i].id;

          // Create a more flexible regex pattern
          const directoryRegex = new RegExp(`{{\\s*${attrId}\\s*}}`, "g");

          // Replace the content, preserving surrounding HTML tags
          data = data.replace(directoryRegex, (match, offset, string) => {
            // Check if the match is inside a tag
            const precedingText = string.substring(0, offset);
            const followingText = string.substring(offset + match.length);
            const precedingTag = precedingText.match(/<([^>]+)>$/);
            const followingCloseTag = followingText.match(/^<\/([^>]+)>/);

            if (
              precedingTag &&
              followingCloseTag &&
              precedingTag[1] === followingCloseTag[1]
            ) {
              // If it's inside matching tags, replace the entire element
              return `<h1>${directoryContent}</h1>`;
            } else {
              // Otherwise, just replace the placeholder
              return directoryContent;
            }
          }); */
        } else {
          //处理常量及其它
          data = data.replace("{{" + attrId + "}}", _this.com.attrs[i].content);
        }
      }
      this.$nextTick(() => {
        this.addInputListeners()
        this.autoWidths()
      });
      return data;
    },
    addInputListeners() {
      // 使用事件委托来处理所有的 .text-input-box 元素
      this.$el.addEventListener("input", this.adjustAutoWidth, true);
    },
    autoWidths(){
      const inputs = this.$el.querySelectorAll(".text-input-boxs");
      inputs.forEach((input) => this.adjustAutoWidth({ target: input }));
    },
    adjustAutoWidth(event){
      if (event.target.classList.contains("text-input-boxs")) {
        const input = event.target;
        const sizeCalculator = document.createElement("span");
        sizeCalculator.className = "size-calculator";
        sizeCalculator.textContent = input.value || input.placeholder || "0";
        document.body.appendChild(sizeCalculator);

        const styles = window.getComputedStyle(input);
        sizeCalculator.style.font = styles.font;
        sizeCalculator.style.fontSize = styles.fontSize;
        sizeCalculator.style.fontWeight = styles.fontWeight;
        sizeCalculator.style.letterSpacing = styles.letterSpacing;

        const width = sizeCalculator.offsetWidth;
        input.style.width = `${width + 10}px`; // Add some padding

        document.body.removeChild(sizeCalculator);
      }
    },
    async analysisFormual(attrs) {
      let _this = this;
      // console.log("开始分析公式:", attrs.formula);
      var pattern = /(\[.*?\]){3}/;
      var formual = attrs.formula;
      var reg = new RegExp(pattern);
      while (true) {
        var items = formual.match(reg);
        if (items == null) break;
        let itemName = items[0];
        // console.log("处理项:", itemName);
        try {
          let data = await _this.getFormualData(itemName);
          // console.log(`获取到的数据: ${itemName} = ${data}`);
          if (data === null || data === undefined || isNaN(data)) {
            console.warn(`获取到的数据无效: ${itemName}`);
            formual = formual.replace(itemName, "(0)");
          } else {
            formual = formual.replace(itemName, `(${parseFloat(data)})`);
          }
        } catch (error) {
          console.error(`处理 ${itemName} 时出错:`, error);
          formual = formual.replace(itemName, "(0)");
        }
      }
      return formual;
    },
    async getFormualData(formualItem) {
      let _this = this;
      // console.log("开始获取公式数据:", formualItem);
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      let items = formualItem.match(reg);
      // console.log("解析结果:", items);
      let calResult = 0;
      if (items && items[1] == "T") {
        calResult = await _this.getModuleData(items[2], items[3]);
      } else {
        console.warn("无法解析公式项:", formualItem);
      }
      // console.log("计算结果:", calResult);
      return calResult;
    },
    updateContent(id, event) {
      const attr = this.com.attrs.find((attr) => attr.id === id);
      if (attr) {
        attr.content = event.target.value;
      }
    },
    /* async replaceData(data) {
      let _this = this;
      for (var i = 0; i < _this.com.attrs.length; i++) {
        let attrId = _this.com.attrs[i].id;
        if (_this.com.attrs[i].type == "formula") {
          let formula = await _this.analysisformula(_this.com.attrs[i]);
          formula = await _this.getRemote(formula);
          let evalResult = eval(formula);
          if (!isNaN(evalResult)) {
            data = data.replace("{{" + attrId + "}}", evalResult);
          }
        } else if (_this.com.attrs[i].type == "sourceData") {
          let result = await _this.getRemote1(_this.com.attrs[i].formula);
          if (!isNaN(result)) {
            data = data.replace("{{" + attrId + "}}", result);
          }
        } else if (_this.com.attrs[i].type == "Directory") {
          //处理目录
          data = data.replace(
            "<p>{{" + attrId + "}}</p>",
            "<h1>" + _this.com.attrs[i].content + "</h1>"
          );
          data = data.replace(
            "<div>{{" + attrId + "}}</div>",
            "<h1>" + _this.com.attrs[i].content + "</h1>"
          );
          data = data.replace(
            "<span>{{" + attrId + "}}</span>",
            "<h1>" + _this.com.attrs[i].content + "</h1>"
          );
        } else {
          data = data.replace("{{" + attrId + "}}", _this.com.attrs[i].content);
        }
      }
      return data;
    }, */

    //分析公式
    async analysisformula(attrs) {
      let _this = this;
      var pattern = /(\[.*?\]){3}/;
      var formula = attrs.formula;
      var reg = new RegExp(pattern);
      while (true) {
        var items = formula.match(reg);
        if (items == null) break;
        let itemName = items[0];
        let data = await _this.getformulaData(itemName);
        data = await _this.getRemote(data);
        formula = formula.replace(itemName, "(" + parseFloat(data) + ")");
      }
      return formula;
    },
    async getformulaData(formulaItem) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      let items = formulaItem.match(reg);
      let calResult = 0;
      if (items[1] == "T") {
        //表示本地模板数据
        calResult = await _this.getModuleData(items[2], items[3]);
      }
      return calResult;
    },
    async getRemote(formula) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      while (true) {
        let items = formula.match(reg);
        if (items == null) break;
        if (items[1] == "R") {
          //表示获取远程数据
          var dataIndex = items[4];
          dataIndex = items[4].split(",");
          let calResult = await _this.getRemoteData(
            items[2],
            items[3],
            dataIndex[0],
            dataIndex[1]
          );
          let itemName = items[0];
          formula = formula.replace(
            itemName,
            "(" + parseFloat(calResult) + ")"
          );
        }
      }
      return formula;
    },
    async getRemote1(formula) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      while (true) {
        let items = formula.match(reg);
        if (items == null) break;
        if (items[1] == "R") {
          //表示获取远程数据
          var dataIndex = items[4];
          dataIndex = items[4].split(",");
          let calResult = await _this.getRemoteData(
            items[2],
            items[3],
            dataIndex[0],
            dataIndex[1]
          );
          let itemName = items[0];
          formula = formula.replace(itemName, parseFloat(calResult));
        }
      }
      return formula;
    },

    //获取远程数据
    async getRemoteData(code, sheet, row, col) {
      debugger;
      let _this = this;
      let result = 0;
      let par = {
        code: code,
        sheetName: sheet,
        row: row,
        col: col,
      };
      let res = await findData(par);
      if (res.status == 200) {
        console.log("result:", res.data);
        let dataResult = parseFloat(res.data.result);
        if (!isNaN(dataResult)) {
          return dataResult;
        }
      }
      return 0;
    },

    //获取本地文档模块数据
    async getModuleData(code, attrName) {
      let _this = this;
      // console.log(`尝试获取模块数据: code=${code}, attrName=${attrName}`);
      // console.log("当前 coms:", _this.coms);

      let item = _this.coms.filter((o) => o.name == code);
      // console.log(`找到的模块:`, item);

      if (item.length > 0) {
        let attr = item[0].attrs.filter((o) => o.name == attrName);
        // console.log(`找到的属性:`, attr);

        if (attr.length > 0) {
          // console.log(`返回的值:`, attr[0].content);
          return parseFloat(attr[0].content);
        }
      }
      // console.log("未找到匹配的模块或属性，返回 0");
      return 0;
    },
  },
};
</script>
<style lang="scss">
@import "./index.scss";
</style>
