<template>
  <div class="template-textarea">
    <template v-if="isEdit == 1">
      <div class="editor-area sticky-editor">
        <!-- <ckeditor
          ref="editor"
          v-model="com.content"
          @focus="onFocus"
          @blur="onBlur"
          @input="onInputText"
          @ready="onEditorReady"
          :config="editorConfig"
          :editorUrl="editorUrl"
        ></ckeditor> -->
        <CanvasEditor
          ref="wordEditor"
          :edit-mode="Modetype"
          :html-data="com.content"
          :doc-json="docJson"
          :key="keys"
          @save="save"
          @is-save="getSave"
        ></CanvasEditor>
      </div>
    </template>

    <template v-else>
      <div
        class="rich-editor"
        ref="richEditor"
        v-html="content"
        @click="handleImageClick"
        :class="{ 'view-mode': isEdit == 2 }"
      ></div>
    </template>
    <div v-if="loading" class="overlay">
      <el-progress
        :percentage="progress"
        class="full-width-progress"
      ></el-progress>
    </div>
  </div>
</template>

<script>
// import CKEditor from "ckeditor4-vue";
import { findData, uploadImage } from "@/api/sourceData";
import axios from "axios"; // 确保导入 axios
import { data } from "jquery";
import CanvasEditor from "@/components/CanvasEditor/index.vue"; // 确保路径正确
export default {
  name: "app",
  emits: ["onUpdate", "onUpdateAttr", "onUpdateProdAttr"],
  components: {
    CanvasEditor, // 使用驼峰式注册
    // ckeditor: CKEditor.component
  },
  props: {
    coms: {
      type: Array,
      default: () => {
        return [];
      },
    },
    isEdit: {
      type: Number,
      default: 2,
    },
    isAdmin: {
      type: Number,
      default: 2,
    },
    currentIndex: {
      type: Number,
      default: 0,
    },
    com: {
      type: Object,
      default: null,
    },
    insertCmd: {
      type: Object,
      default: null,
    },
  },
  watch: {
    isEdit: {
      handler(val) {
        console.log("isEdit:", val);
        let _this = this;
        if (val == "2") {
          _this.save();
          /* if (_this.com && _this.com.content) {
            _this.replaceData(_this.com.content).then((res) => {
              _this.content = res;
              _this.htmlData = res;
              _this.$nextTick(() => {
                _this.bindEvents();
                _this.initializeInputWidths();
              });
            });
          } */
        } else if (_this.com != null) {
          _this.replaceData(_this.com.content).then((res) => {
            _this.content = res;
            _this.$nextTick(() => {
              _this.bindEvents();
            });
          });
        }
      },
      immediate: true,
      deep: true,
    },
    com: {
      async handler(val) {
        let _this = this;
        if (val == null) return;
        if (val.content == undefined || val.content == null) return;
        try {
          let res = await _this.replaceData(val.content);
          _this.htmlData = res;
          _this.content = res;
          _this.$nextTick(() => {
            _this.bindEvents();
            _this.initializeInputWidths();
          });
        } catch (error) {
          console.error("处理 com 时出错:", error);
        }
      },
      immediate: true,
      deep: true,
    },
    insertCmd: {
      handler(val) {
        if (val == null || this.isEdit != 1) return;

        this.$nextTick(async () => {
          try {
            if (!this.$refs.wordEditor) {
              console.warn("编辑器未就绪");
              return;
            }

            const editor = this.$refs.wordEditor;

            // 获取当前内容和新内容
            let currentContent = this.com.content || "";
            let insertContent = val.content;

            // 如果是规格属性，先进行预处理
            if (val.type === "ProductAttr") {
              // 构建规格HTML
              const specs = val.attrs?.specifications?.[0];
              if (specs) {
                const prodAttrId = `${val.id}_${this.com.attrs?.length || 0}`;

                let specHtml = `
                  <div class="product-attr-container">
                    <div class="spec-label">${specs.psp_name || "规格"}：</div>
                    <div class="spec-input">
                `;

                switch (specs.psp_type) {
                  case "单选":
                    const options = specs.psp_value
                      ? specs.psp_value.split(",")
                      : [];
                    specHtml += `
                      <select 
                        id="${prodAttrId}" 
                        data-index="${this.com.attrs?.length || 0}"
                        class="text-input-box product-select"
                        style="min-width: 120px;"
                      >
                        <option value="">请选择</option>
                        ${options
                          .map(
                            (opt) => `<option value="${opt}">${opt}</option>`
                          )
                          .join("")}
                      </select>
                    `;
                    break;

                  case "多选":
                    const multiOptions = specs.psp_value ? specs.psp_value.split(",") : [];
                    specHtml += `
                      <div class="checkbox-group" id="${prodAttrId}" data-index="${this.com.attrs?.length || 0}">
                        ${multiOptions.map(opt => `
                          <label class="checkbox-item">
                            <input 
                              type="checkbox" 
                              value="${opt.trim()}"
                              ${item.content?.includes(opt.trim()) ? 'checked' : ''}
                              class="product-checkbox"
                            >
                            <span class="checkbox-label">${opt.trim()}</span>
                          </label>
                        `).join('')}
                      </div>
                    `;
                    break;

                  default:
                    specHtml += `
                      <input 
                        type="text" 
                        id="${prodAttrId}" 
                        data-index="${this.com.attrs?.length || 0}"
                        class="text-input-box auto-width" 
                        value="${specs.ps_name || ""}"
                        placeholder="请输入${specs.psp_name || ""}"
                        style="min-width: 120px;"
                      >
                    `;
                }

                specHtml += `
                    </div>
                  </div>
                `;

                insertContent = specHtml;
              }
            }

            // 确保变量两侧有空格
            if (insertContent.includes("{{") && insertContent.includes("}}")) {
              insertContent = ` ${insertContent} `;
            }

            // 构建新内容
            let newContent;
            if (editor.getSelection) {
              const selection = editor.getSelection();
              if (selection) {
                newContent =
                  currentContent.substring(0, selection.start) +
                  insertContent +
                  currentContent.substring(selection.end);
              } else {
                newContent = currentContent + insertContent;
              }
            } else {
              newContent = currentContent + insertContent;
            }

            // 更新内容
            this.com.content = newContent;

            // 更新编辑器显示
            if (editor.setHtmlData) {
              editor.setHtmlData(newContent);
            }

            // 强制重新渲染
            this.keys = new Date().getTime();

            // 保存更新
            await this.save({
              main: newContent,
            });

            // 确保视图更新并绑定事件
            this.$nextTick(() => {
              this.bindProductAttrEvents();
              this.$forceUpdate();
            });
          } catch (error) {
            console.error("插入内容时出错:", error);
          }
        });
      },
      deep: true,
    },
  },
  data() {
    return {
      editorUrl: "/ckeditor/ckeditor.js",
      editorConfig: {
        language: "zh-cn",
        height: "650px",
      },

      content: "",
      editor: null,
      loading: false,
      progress: 0,
      isEditing: false,
      focusedInputId: null,
      variableNullInputs: {},

      Modetype: "edit",
      htmlData: "", // 编辑器html数据
      docJson: null, // 编辑器getValue数据
      keys: new Date().getTime(), // 给编辑器赋值不刷新的时候，改变key
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initializeInputWidths();
      this.syncContent();
      this.bindProductAttrEvents();
    });
  },
  updated() {
    this.$nextTick(() => {
      if (this.isEdit == "2") {
        this.syncContent();
      } else {
        this.bindProductAttrEvents();
      }
    });
  },
  // 记得在组件销毁时移除事件监听器
  beforeDestroy() {
    this.$el.removeEventListener("input", this.handleInputChange);
    this.$el.removeEventListener("input", this.handleVariableNullInput);
    this.$el.removeEventListener("blur", this.handleVariableNullBlur, true);
    const inputs = this.$el.querySelectorAll(".text-input-box");
    inputs.forEach((input) => {
      input.removeEventListener("change", this.handleProductAttrChange);
    });
  },
  methods: {
    /*canvas 添加 */
    save(data) {
      return new Promise(async (resolve, reject) => {
        try {
          // 如果没有传入data参数，使用当前编辑器的内容
          const content = data ? data.main : this.com.content;
          
          // 更新内容
          this.com.content = content;
          
          // 等待同步完成
          await this.$nextTick();
          await this.syncContent(); 

          // 触发更新事件并等待完成
          this.$emit("onUpdate", this.currentIndex, this.com.content);
          await this.$nextTick();

          // 返回保存成功
          resolve(true);
        } catch (error) {
          console.error('保存失败:', error);
          reject(error);
        }
      });
    },
    getSave(isSaved) {
      // 处理保存状态
      console.log("是否已保存:", isSaved);
      // 这里可以添加保存状态的处理逻辑
    },

    async replaceData(data) {
      let _this = this;
      // 定义数学函数和 IF 函数
      const mathFunctions = {
        abs: Math.abs,
        ceil: Math.ceil,
        floor: Math.floor,
        max: Math.max,
        min: Math.min,
        round: Math.round,
        sqrt: Math.sqrt,
        IF: (condition, trueValue, falseValue) =>
          condition ? trueValue : falseValue,
        // 添加其他需要的数学函数
      };
      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 auto-width" value="' +
                _this.com.attrs[i].content +
                '">'
            );
          }
        } else if (_this.com.attrs[i].type == "variableNull") {
          let item = _this.com.attrs[i];
          // 使用唯一的标识符来初始化每个输入框的值
          this.variableNullInputs[attrId] = item.content;
          data = data.replace(
            "{{" + attrId + "}}",
            '<input type="text" ' +
              'ref="input_' +
              attrId +
              '" ' +
              'name="' +
              item.name +
              '" ' +
              'id="' +
              attrId +
              '" ' +
              'data-index="' +
              i +
              '" ' +
              'data-attr-id="' +
              attrId +
              '" ' +
              'class="text-input-boxs auto-width" ' +
              'value="' +
              item.content +
              '">'
          );
        } else if (_this.com.attrs[i].type == "ProductAttr") {
          let item = _this.com.attrs[i];
          let prodAttrId = item.id + "_" + i;

          // 添加调试日志
          console.log("ProductAttr item:", item);
          console.log(
            "ProductAttr specifications:",
            item.attrs?.specifications
          );

          // 获取规格信息
          const specs = item.attrs?.specifications?.[0];
          if (!specs) {
            console.warn("No specifications found for ProductAttr:", item);
            continue;
          }

          // 添加规格名称显示
          let specHtml = `
            <div class="product-attr-container">
              <div class="spec-label">${specs.psp_name || "规格"}：</div>
              <div class="spec-input">
          `;

          // 根据psp_type决定渲染什么类型的输入控件
          if (this.isEdit == "1") {
            // 预览模式直接显示内容
            specHtml += `<span class="preview-content">${
              item.content || ""
            }</span>`;
          } else {
            console.log(specs.psp_type);
            switch (specs.psp_type) {
              /* case '2': // 单选 */
              case "单选":
                // 处理单选下拉框
                const options = specs.ps_name ? specs.ps_name.split(",") : [];
                specHtml += `
                  <select 
                    id="${prodAttrId}" 
                    data-index="${i}" 
                    class="text-input-box product-select"
                    style="min-width: 120px;"
                  >
                    <option value="">请选择</option>
                    ${options
                      .map(
                        (opt) => `
                      <option 
                        value="${opt}" 
                        ${item.content === opt ? "selected" : ""}
                      >${opt}</option>
                    `
                      )
                      .join("")}
                  </select>
                `;
                break;

              /*  case '3': // 多选  */
              case "多选":
                // 处理多选下拉框
                const selectedValues = specs.ps_name ? specs.ps_name.split(",") : [];
                specHtml += `
                  <div class="checkbox-group" id="${prodAttrId}" data-index="${i}">
                    ${selectedValues.map(opt => `
                      <label class="checkbox-item">
                        <input 
                          type="checkbox" 
                          value="${opt.trim()}"
                          ${item.content?.includes(opt.trim()) ? 'checked' : ''}
                          class="product-checkbox"
                        >
                        <span class="checkbox-label">${opt.trim()}</span>
                      </label>
                    `).join('')}
                  </div>
                `;
                break;

              default: // 输入框
                specHtml += `
                  <input  
                    id="${prodAttrId}" 
                    data-index="${i}" 
                    class="text-input-box auto-width" 
                    value="${item.content || 0}"
                    placeholder="请输入${specs.psp_name || ""}"
                    style="min-width: 120px;"
                  >
                `;
            }
          }

          specHtml += `
              </div>
            </div>
          `;

          // 替换标记
          data = data.replace("{{" + item.id + "}}", specHtml);
        } else if (_this.com.attrs[i].type == "formual") {
          //处理计算公式 不处理
          let formual = await _this.analysisFormual(_this.com.attrs[i]);
          let point = _this.com.attrs[i].data.point;
          formual = await _this.getRemote(formual);

          /* console.log("处理的公式:", formual); // 添加日志 */

          // 收集公式中使用的变量
          const variables = {};
          const variableRegex = /\b[a-zA-Z_][a-zA-Z0-9_]*\b/g;
          const matches = formual.match(variableRegex);
          if (matches) {
            for (const varName of matches) {
              if (
                varName !== "IF" &&
                !Object.keys(mathFunctions).includes(varName)
              ) {
                variables[varName] = `${varName}`; // 默认值设为0，您可以根据需要修改
              }
            }
          }

          /*   console.log("识别的变量:", variables); // 添加日志 */

          // 定义一个安全的评估函数
          const safeEval = (formula, variables) => {
            // 创建一个新的函数，将数学函数和变量作为参数传入
            const func = new Function(
              ...Object.keys(mathFunctions),
              ...Object.keys(variables),
              `return ${formula}`
            );

            // 执行函数，传入数学函数和变量作为参数
            return func(
              ...Object.values(mathFunctions),
              ...Object.values(variables)
            );
          };

          try {
            const result = safeEval(formual, variables);
            /*  console.log("计算结果:", result); // 添加日志 */

            let formattedResult;
            if (typeof result === "number" && !isNaN(result)) {
              formattedResult = result.toFixed(point);
            } else if (typeof result === "boolean") {
              formattedResult = result ? "1" : "0";
            } else {
              formattedResult = String(result);
            }

            _this.com.attrs[i].content = formattedResult;
            data = data.replace(
              "{{" + _this.com.attrs[i].id + "}}",
              formattedResult
            );
          } catch (error) {
            console.error("处理公式时出错:", error);
            console.error("错误的公式:", formual);
            _this.com.attrs[i].content = "计算错误";
            data = data.replace(
              "{{" + _this.com.attrs[i].id + "}}",
              "计算错误"
            );
          }

          /* let formual = await _this.analysisFormual(_this.com.attrs[i]);
          formual = await _this.getRemote(formual);
          // 使用 try-catch 来处理可能的计算错误
          try {
            let result = eval(formual);
            data = data.replace("{{" + attrId + "}}", result);
          } catch (error) {
            data = data.replace("{{" + attrId + "}}", "计算错误");
          } */
        } 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;

          // 创建一个更灵活的正则表达式模式，匹配可能存在的div包裹
          const directoryRegex = new RegExp(
            `<div[^>]*>\\s*{{\\s*${attrId}\\s*}}\\s*</div>|{{\\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}>`;
          });
          //处理目录
          /* 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>"
          ); */
          //处理目录
          /*  const directoryContent = _this.com.attrs[i].content;
          const directoryRegex = new RegExp(
            `<(p|div|span)>{{${attrId}}}</(p|div|span)>`,
            "g"
          );
          data = data.replace(directoryRegex, `<h1>${directoryContent}</h1>`); */
          // 在处理目录内容的地方添加编号显示
          data = data.replace(/{{([\w-]+)}}/g, (match, attrId) => {
            const attr = _this.com.attrs.find(a => a.id === attrId);
            if (attr && attr.type === 'Directory') {
              const level = attr.level;
              const tag = `h${Math.min(level, 6)}`;
              const className = `directory-level-${level}`;
              // 添加编号到内容前
              const content = `${attr.number} ${attr.content}`;
              return `<${tag} class="${className}">${content}</${tag}>`;
            }
            return match;
          });
        } else {
          //处理常量及其它
          data = data.replace("{{" + attrId + "}}", _this.com.attrs[i].content);
        }
      }
      this.$nextTick(() => {
        this.addInputListeners();
        this.initializeInputWidths();
        this.addVariableNullListeners();
      });
      return data;
    },
    // 新增方法：为 variableNull 类型的输入框添加事件监听器
    addVariableNullListeners() {
      this.$el.addEventListener("input", this.handleVariableNullInput);
      this.$el.addEventListener("blur", this.handleVariableNullBlur, true);
    },

    handleVariableNullInput(event) {
      if (event.target.classList.contains("text-input-boxs")) {
        const attrId = event.target.dataset.attrId;
        const newValue = event.target.value;
        // 只更新特定输入框的值
        this.$set(this.variableNullInputs, attrId, newValue);
      }
    },

    handleVariableNullBlur(event) {
      if (event.target.classList.contains("text-input-boxs")) {
        const index = parseInt(event.target.dataset.index, 10);
        const attrId = event.target.dataset.attrId;
        const newValue = this.variableNullInputs[attrId];
        // 只更新特定属性的内容
        this.updateVariableNullContent(index, attrId, newValue, true);
      }
    },

    updateVariableNullContent(index, attrId, newValue, emitEvent = false) {
      if (this.com && this.com.attrs && this.com.attrs[index]) {
        if (this.com.attrs[index].id === attrId) {
          // 只更新特定属性的内容
          this.$set(this.com.attrs[index], "content", newValue);

          // 更新输入框的值
          this.$nextTick(() => {
            const input = this.$el.querySelector(`#${attrId}`);
            if (input) {
              input.value = newValue;
            }
          });

          // 触发事件
          if (emitEvent) {
            this.$emit("onUpdata", this.currentIndex, index, attrId, newValue);
          }
        }
      }
    },
    addInputListeners() {
      // 使用事件委托来处理所有的 .text-input-box 元素
      this.$el.addEventListener("blur", this.handleInputChange, true);
      this.$el.addEventListener("input", this.adjustInputWidth, true);
    },
    initializeInputWidths() {
      const inputs = this.$el.querySelectorAll(
        ".text-input-box, .text-input-boxs"
      );
      inputs.forEach((input) => this.adjustInputWidth({ target: input }));
    },

    // 修改这个方法，使其同时处理 variableNull 类型的输入框
    adjustInputWidth(event) {
      if (
        event.target.classList.contains("text-input-box") ||
        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);
      }
    },

    // 修改这个方法，使其同时处理 variableNull 类型的输入框
    handleInputChange(event) {
      if (
        event.target.classList.contains("text-input-box") ||
        event.target.classList.contains("text-input-boxs")
      ) {
        const attrId = event.target.id;
        const attrName = event.target.name;
        const dataIndex = parseInt(event.target.dataset.index, 10);
        const newValue = event.target.value;
        // 更新数据
        if (this.com && this.com.attrs && this.com.attrs[dataIndex]) {
          this.$set(this.com.attrs[dataIndex], "content", newValue);

          this.com.attrs.forEach((el) => {
            if (el.name === attrName) {
              this.$set(el, "content", newValue);
            }
          });
          this.$emit("onUpdateAttr", this.currentIndex, dataIndex, newValue);
        } else {
          console.warn(`Unable to find attribute at index ${dataIndex}`);
        }
      }
    },

    bindEvents() {
      let _this = this;
      for (var i = 0; i < _this.com.attrs.length; i++) {
        let attrId = _this.com.attrs[i].id;
        let item = _this.com.attrs[i];
        if (_this.com.attrs[i].type == "variable") {
          //变量事件
          let input = _this.$el.querySelector("#" + attrId);
          if (input) {
            if (item.data.value_type == 2) {
              //下拉选择
              input.addEventListener("change", _this.handleInput);
            } else {
              //文本输入
              input.addEventListener("blur", _this.handleInput);
            }
          }
        } else if (_this.com.attrs[i].type == "ProductAttr") {
          //绑定产品属性事件
          let prodAttrId = item.id + "_" + i;
          let input = _this.$el.querySelector("#" + prodAttrId);
          if (input) {
            if (item.attrs.type == 1) {
              input.addEventListener("blur", _this.handleInputProduct);
            } else {
              input.addEventListener("change", _this.handleChangeProduct);
            }
          }
        }
      }
    },

    //分析公式
    async analysisFormual(attrs) {
      let _this = this;
      /*  console.log("开始分析公式:", attrs.formula); */
      let formual = attrs.formula;

      // 处理 [T][...][...] 引用
      const tPattern = /\[T\]\[(.*?)\]\[(.*?)\]/g;
      formual = await this.replaceAsync(
        formual,
        tPattern,
        async (match, p1, p2) => {
          try {
            let data = await _this.getModuleData(p1, p2);
            /*   console.log(`获取到的数据: ${match} = ${data}`); */
            if (data === null || data === undefined) {
              console.warn(`获取到的数据无效: ${match}`);
              return "''"; // 返回空字符串而不是 0
            } else {
              return typeof data === "string" ? `${data}` : data;
            }
          } catch (error) {
            console.error(`处理 ${match} 时出错:`, error);
            return "''";
          }
        }
      );

      // 处理嵌套的 IF 语句
      const ifPattern = /IF\s*\((.*?),(.*?),(.*?)\)/gi;
      let depth = 0;
      while (formual.match(ifPattern) && depth < 10) {
        formual = formual.replace(
          ifPattern,
          (match, condition, trueValue, falseValue) => {
            // 递归处理嵌套的 IF 语句
            if (
              trueValue.includes("IF(") ||
              falseValue.includes("IF(") ||
              trueValue.includes("if(") ||
              falseValue.includes("if(")
            ) {
              return `(${condition} ? (${trueValue}) : (${falseValue}))`;
            }
            return `(${condition} ? ${trueValue} : ${falseValue})`;
          }
        );
        depth++;
      }

      /* console.log("分析后的公式:", formual); */
      return formual;
    },

    // 辅助方法：异步替换
    async replaceAsync(str, regex, asyncFn) {
      const promises = [];
      str.replace(regex, (match, ...args) => {
        const promise = asyncFn(match, ...args);
        promises.push(promise);
      });
      const data = await Promise.all(promises);
      return str.replace(regex, () => data.shift());
    },

    // 辅助方法：异步替换
    async replaceAsync(str, regex, asyncFn) {
      const promises = [];
      str.replace(regex, (match, ...args) => {
        const promise = asyncFn(match, ...args);
        promises.push(promise);
      });
      const data = await Promise.all(promises);
      return str.replace(regex, () => data.shift());
    },

    async getFormualData(formualItem, data) {
      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("计算结果:", formualItem,data); */
      return calResult;
    },

    async getRemote(formual) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      while (true) {
        let items = formual.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];
          // 检查calResult是否为数字
          if (!isNaN(calResult)) {
            formual = formual.replace(
              itemName,
              "(" + parseFloat(calResult) + ")"
            );
          } else {
            formual = formual.replace(itemName, `"${calResult}"`);
          }
          formual = formual.replace(
            itemName,
            "(" + parseFloat(calResult) + ")"
          );
        }
      }
      return formual;
    },

    async getRemote1(formual) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      while (true) {
        let items = formual.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];
          // 检查calResult是否为数字
          if (!isNaN(calResult)) {
            formual = formual.replace(
              itemName,
              "(" + parseFloat(calResult) + ")"
            );
          } else {
            formual = formual.replace(itemName, `"${calResult}"`);
          }
          /* formual=formual.replace(itemName,parseFloat(calResult)); */
        }
      }
      return formual;
    },
    onFocus() {
      this.isEditing = true;
    },

    onBlur() {
      this.isEditing = false;
    },

    async getRemoteData(code, sheet, row, col) {
      let _this = this;
      let result = 0;
      let par = {
        code: code,
        sheetName: sheet,
        row: row,
        col: col,
      };

      /*  if (!this.isEditing) {
        this.loading = true;
        this.progress = 0;

        try {
          const updateProgress = setInterval(() => {
            if (this.progress < 90) {
              this.progress += 10;
            }
          }, 100);

          let res = await findData(par);
          if (res.status == 200) {
            result = res.data.result;
          }

          this.progress = 100;
          clearInterval(updateProgress);
        } catch (error) {
          console.error("Error fetching remote data:", error);
        } finally {
          setTimeout(() => {
            this.loading = false;
            this.progress = 0;
          }, 1000);
        }
      } else { */
      // 如果正在编辑，直接获取数据而不显示进度条
      try {
        let res = await findData(par);
        // 添加响应检查
        if (!res) {
          console.warn("No response received from findData");
          return result;
        }

        // 检查响应格式
        if (res.status === 200 && res.data) {
          result = res.data.result;
          // 添加数据类型检查和转换
          if (typeof result === "string" && !isNaN(result)) {
            result = parseFloat(result);
          }
        } else {
          console.warn("Invalid response format:", res);
        }
      } catch (error) {
        console.error("获取远程数据错误:", error);
        // 可以在这里添加错误通知
        this.$message && this.$message.error("获取远程数据失败");
      }

      return result;
    },
    //获取本地文档模块数据
    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 attr[0].content; // 返回原始值，不进行转换
        }
      }
      /*  console.log("未找到匹配的模块或属性，返回空字符串"); */
      return ""; // 返回空字符串而不是 0
    },

    handleChangeProduct(e) {
      let dataIndex = e.target.dataset.index;
      this.$emit(
        "onUpdateProdAttr",
        this.currentIndex,
        dataIndex,
        e.target.value
      );
    },

    handleInputProduct(e) {
      let dataIndex = e.target.dataset.index;
      this.$emit(
        "onUpdateProdAttr",
        this.currentIndex,
        dataIndex,
        e.target.value
      );
    },
    handleInput(e) {
      let dataIndex = e.target.dataset.index;
      this.$emit("onUpdateAttr", this.currentIndex, dataIndex, e.target.value);
    },

    onEditorReady(editor) {},

    onInputText(e) {
      this.$emit("onUpdate", this.currentIndex, e);
    },

    /* 点击替换图片 */
    handleImageClick(event) {
      if (event.target.tagName === "IMG") {
        this.replaceImage(event.target);
      }
    },
    selectImage() {
      return new Promise((resolve) => {
        const input = document.createElement("input");
        input.type = "file";
        input.accept = "image/*";
        input.onchange = (e) => resolve(e.target.files[0]);
        input.click();
      });
    },

    async uploadImage(formData) {
      try {
        const response = await axios.post(
          "http://58.246.234.210:8084/upload/image",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );
        console.log("Upload response:", response);
        if (response.status === 200 && response.data && response.data.url) {
          return response.data.url;
        } else {
          throw new Error("Invalid upload response");
        }
      } catch (error) {
        console.error("Error uploading image:", error);
        throw error;
      }
    },
    /* updateContentWithNewImage(imgElement) {
      // 更新 content 中的图片 URL
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = this.content;
      const images = tempDiv.getElementsByTagName('img');
      for (let img of images) {
        if (img.src === imgElement.src) {
          img.src = imgElement.src;
          break;
        }
      }
      this.content = tempDiv.innerHTML;
      this.$emit('onUpdate', this.currentIndex, this.content);
    }, */

    async replaceImage(imgElement) {
      try {
        const file = await this.selectImage();
        if (file) {
          const formData = new FormData();
          formData.append("upload", file);
          const uploadedUrl = await this.uploadImage(formData);

          // Update the image element in the DOM
          imgElement.src = uploadedUrl;

          // Update the content and notify parent component
          this.$nextTick(() => {
            this.updateContentWithNewImage(imgElement, uploadedUrl);
          });
        }
      } catch (error) {
        console.error("Error replacing image:", error);
      }
    },

    updateContentWithNewImage(imgElement, newImageUrl) {
      // Get the rich-editor div
      const richEditor = this.$refs.richEditor;

      // Create a new Image element with the new URL
      const newImg = document.createElement("img");
      newImg.src = newImageUrl;

      // Copy attributes from the old image to the new one
      for (let attr of imgElement.attributes) {
        if (attr.name !== "src") {
          newImg.setAttribute(attr.name, attr.value);
        }
      }

      // Replace the old image with the new one
      imgElement.parentNode.replaceChild(newImg, imgElement);

      // Update this.content with the latest DOM content
      this.content = richEditor.innerHTML;

      // Update the com object
      this.com.content = this.content;

      // Emit an event to update the parent component
      this.$emit("updateComContent", this.currentIndex, this.com);
    },

    /*  updateComsData(newImageUrl) {
      // 找到当前组件在 coms 数组中的索引
      const comIndex = this.coms.findIndex((com) => com.name === this.com.name);
      if (comIndex !== -1) {
        // 创建 coms 的深拷贝
        const updatedComs = JSON.parse(JSON.stringify(this.coms));

        // 更新特定组件的 content
        updatedComs[comIndex].content = this.content;

        // 如果有特定的图片属性，也更新它
        const imgAttr = updatedComs[comIndex].attrs.find(
          (attr) => attr.type === "image"
        );
        if (imgAttr) {
          imgAttr.content = newImageUrl;
        }

        // 更新 coms
        this.$emit("update:coms", updatedComs);
      }
    }, */
    /* onFocus(e) {
      // var range = e.editor.getSelection().getRanges()[0];
      // range.collapse( true );
      // range.setStartAt( e.editor.editable(), CKEDITOR.POSITION_AFTER_START );
      // e.editor.insertText("AAA");
    },
    onBlur(e) {
      //// console.log(' onBlur e',e);
      // this.$emit("onUploadAttr",this.dataIndex,this.dataAttr);
    }, */

    async syncContent() {
      if (this.isEdit == "2" && this.com && this.com.content) {
        const formattedContent = this.formatContent(this.com.content);
        const res = await this.replaceData(formattedContent);
        this.content = res;
        
        await this.$nextTick();
        
        this.bindEvents();
        this.initializeInputWidths();

        if (this.com.attrs) {
          this.com.attrs.forEach((attr, index) => {
            const element = this.$el.querySelector(`#${attr.id}`);
            if (element) {
              element.value = attr.content || "";
              this.adjustInputWidth({ target: element });
            }
          });
        }
      }
    },

    getCursorPosition() {
      const editor = this.$refs.wordEditor;
      if (!editor) return 0;

      // 尝试不同的方法获取光标位置
      if (editor.getCursorPosition) {
        return editor.getCursorPosition();
      } else if (editor.getSelection) {
        const selection = editor.getSelection();
        return selection ? selection.start || 0 : 0;
      }
      return 0;
    },

    formatContent(content) {
      // 保留空格和换行
      return content.replace(/\s+/g, " ").replace(/\n/g, "<br>");
    },

    handleProductAttrChange(event) {
      const target = event.target;
      const container = target.closest('.checkbox-group, .product-select, .product-input');
      if (!container) return;

      const index = parseInt(container.dataset.index);
      const item = this.com.attrs[index];

      if (!item || item.type !== "ProductAttr") return;

      let newValue;
      if (container.classList.contains('checkbox-group')) {
        // 处理checkbox组
        const checkboxes = container.querySelectorAll('input[type="checkbox"]:checked');
        newValue = Array.from(checkboxes)
          .map(cb => cb.value)
          .filter(Boolean)
          .join(",");
      } else if (target.multiple) {
        // 处理多选select（保留原有逻辑）
        newValue = Array.from(target.selectedOptions)
          .map(opt => opt.value)
          .filter(Boolean)
          .join(",");
      } else {
        newValue = target.value;
      }

      // 更新内容
      this.$set(item, "content", newValue);

      // 触发更新事件
      this.$emit("onUpdateProdAttr", this.currentIndex, index, newValue);
    },

    handleProductAttrInput(event) {
      // 处理输入框实时输入
      const target = event.target;
      if (target.classList.contains("product-input")) {
        this.adjustInputWidth({ target });
      }
    },

    bindProductAttrEvents() {
      this.$nextTick(() => {
        const inputs = this.$el.querySelectorAll(
          '.product-input, .product-select, .product-checkbox'
        );
        console.log("Found product inputs:", inputs.length);

        inputs.forEach((input) => {
          input.removeEventListener("change", this.handleProductAttrChange);
          input.removeEventListener("input", this.handleProductAttrInput);
          input.removeEventListener("blur", this.handleProductAttrChange);

          input.removeAttribute("readonly");
          input.removeAttribute("disabled");

          if (input.type === 'checkbox') {
            input.addEventListener("change", this.handleProductAttrChange);
          } else if (input.tagName.toLowerCase() === "select") {
            input.addEventListener("change", this.handleProductAttrChange);
          } else {
            input.addEventListener("input", this.handleProductAttrInput);
            input.addEventListener("blur", this.handleProductAttrChange);
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
.template-textarea {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); // Semi-transparent background
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10; // Ensure it is above other content
}

.full-width-progress {
  width: 80%; // Adjust as needed
  color: inherit; // Ensure the color remains unchanged
}
.auto-width-wrapper {
  display: inline-block;
  position: relative;
}

.size-calculator {
  position: absolute;
  top: -9999px;
  left: -9999px;
  white-space: pre;
  font-family: inherit;
  font-size: inherit;
  font-weight: inherit;
  padding: 2px 4px;
}
.editor-wrapper {
  position: relative;
}

.sticky-toolbar {
  position: sticky;
  top: 0;
  z-index: 1000;
  background-color: #fff;
  border-bottom: 1px solid #d1d1d1;
}

.editor-area {
  ::v-deep .cke_top {
    display: block; // Hide the original toolbar
  }
}
::v-deep .directory-level-1 {
  font-size: 24px;
  font-weight: bold;
  margin-left: 0;
}

::v-deep .directory-level-2 {
  font-size: 20px;
  font-weight: bold;
  margin-left: 20px;
}

::v-deep .directory-level-3 {
  font-size: 18px;
  font-weight: bold;
  margin-left: 40px;
}

::v-deep .directory-level-4 {
  font-size: 16px;
  font-weight: bold;
  margin-left: 60px;
}

::v-deep .directory-level-5 {
  font-size: 14px;
  font-weight: bold;
  margin-left: 80px;
}

::v-deep .directory-level-6 {
  font-size: 12px;
  font-weight: normal;
  margin-left: 100px;
}

.rich-editor.view-mode {
  // 添加与编辑模式一致的样式
  ::v-deep {
    // 继承编辑器的基本样式
    font-family: inherit;
    line-height: 1.6;
    color: inherit;

    // 标题样式
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
      margin: 1em 0 0.5em;
      font-weight: bold;
    }

    // 段落样式
    p {
      margin: 1em 0;
    }

    // 列表样式
    ul,
    ol {
      padding-left: 2em;
      margin: 1em 0;
    }

    // 表格样式
    table {
      border-collapse: collapse;
      width: 100%;
      margin: 1em 0;

      td,
      th {
        border: 1px solid #ddd;
        padding: 8px;
      }
    }

    // 图片样式
    img {
      max-width: 100%;
      height: auto;
    }

    // 保持输入框样式一致
    .text-input-box,
    .text-input-boxs {
      display: inline-block;
      border: 1px solid transparent;
      background: transparent;
      padding: 2px 4px;
      min-width: 20px;
      outline: none;

      &:hover {
        border-color: #ddd;
      }
    }
  }
}

::v-deep {
  .product-attr-container {
    display: inline-flex;
    align-items: center;
    // 调整容器高度和间距
    min-height: 28px;
    margin: 2px 4px;
    vertical-align: middle;

    .spec-label {
      margin-right: 8px;
      white-space: nowrap;
      font-size: 14px;
      line-height: 1.4;
    }

    .spec-input {
      flex: 1;
      min-width: 120px;
      display: inline-flex;
      align-items: center;
    }
  }

  .product-input,
  .product-select {
    // 调整输入框和选择框的尺寸
    height: 28px;
    line-height: 26px;
    padding: 0 8px;
    margin: 0;
    font-size: 14px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #606266;
    background-color: #fff;
    transition: all 0.2s;

    &:hover {
      border-color: #c0c4cc;
    }

    &:focus {
      border-color: #409eff;
      outline: none;
    }
  }

  .product-select {
    padding-right: 25px;

    &[multiple] {
      // 调整多选下拉框的高度
      height: auto;
      min-height: 28px;
      max-height: 120px;
      padding: 2px;

      option {
        padding: 4px 8px;
        line-height: 20px;

        &:checked {
          background-color: #409eff;
          color: #fff;
        }
      }
    }
  }

  // 预览模式样式优化
  .view-mode {
    .product-attr-container {
      margin: 0 2px;
    }

    .product-input,
    .product-select {
      background-color: transparent;
      min-width: 80px;

      &:not(:focus) {
        border-color: transparent;
      }

      &:hover {
        border-color: #dcdfe6;
      }

      &:focus {
        background-color: #fff;
        border-color: #409eff;
      }
    }
  }

  .checkbox-group {
    display: inline-flex;
    flex-wrap: wrap;
    gap: 8px;
    min-width: 120px;
    padding: 4px 0;
  }

  .checkbox-item {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
    user-select: none;
    margin-right: 12px;

    &:hover {
      .checkbox-label {
        color: #409eff;
      }
    }
  }

  .product-checkbox {
    margin-right: 4px;
    cursor: pointer;

    &:checked + .checkbox-label {
      color: #409eff;
    }
  }

  .checkbox-label {
    font-size: 14px;
    color: #606266;
    transition: color 0.2s;
  }

  // 预览模式样式优化
  .view-mode {
    .checkbox-group {
      margin: 0 2px;
    }

    .checkbox-item {
      opacity: 0.9;
    }

    .product-checkbox {
      &:not(:checked) {
        opacity: 0.7;
      }
    }
  }
}
</style>
