<template>
  <div class="template-textarea">
    <template v-if="isEdit == 1">
      <div class="editor-area">
        <ckeditor
          ref="editor"
          v-model="com.content"
          @focus="onFocus"
          @blur="onBlur"
          @input="onInputText"
          @ready="onEditorReady"
          :config="editorConfig"
          :editorUrl="editorUrl"
        ></ckeditor>
      </div>
    </template>

    <template v-else>
      <div class="rich-editor" v-html="content"></div>
    </template>
  </div>
</template>

<script>
// import CKEditor from "ckeditor4-vue";
import { findData } from "@/api/sourceData";
export default {
  name: "app",
  emits: ["onUpdate", "onUpdateAttr", "onUpdateProdAttr"],
  compnents: {
    // 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) {
        let _this = this;
        if (_this.com != null) return;
        _this.replaceData(_this.com.content).then((res) => {
          _this.content = res;
          _this.$nextTick(() => {
            _this.bindEvents();
          });
        });
      },
      immediate: true,
      deep: true,
    },
    com: {
      handler(val) {
        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.$nextTick(() => {
            _this.bindEvents();
          });
        });
      },
      immediate: true,
      deep: true,
    },
    insertCmd: {
      handler(val) {
        if (val == null || this.isEdit != 1) return;
        let data = this.$refs.editor.instance.getSelection().getSelectedText();
        if (val.content.indexOf("Directory", 0) >= 0) {
          //执行的是目录
          this.$emit(
            "onUpdateAttr",
            this.currentIndex,
            this.com.attrs.length - 1,
            data
          );
          this.$refs.editor.instance.execCommand("delete");
        }
        this.$refs.editor.instance.insertHtml(val.content);
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      editorUrl: "/ckeditor/ckeditor.js",
      editorConfig: {
        language: "zh-cn",
        height: "800px",
      },

      content: "",
      editor: null,
    };
  },
  mounted() {},
  methods: {
    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" id="' +
                attrId +
                '"  data-index="' +
                i +
                '" class="text-input-box" 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);

          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") {
          //处理目录
          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;
    },

    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 (item.attrs.type == 1) {
            input.addEventListener("blur", _this.handleInputProduct);
          } else {
            input.addEventListener("change", _this.handleChangeProduct);
          }
        }
      }
    },

    //分析公式
    async analysisFormual(attrs) {
      let _this = this;
      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];
        let data = await _this.getFormualData(itemName);
        formual = formual.replace(itemName, "(" + parseFloat(data) + ")");
      }
      return formual;
    },

    async getFormualData(formualItem) {
      let _this = this;
      var pattern = /\[(.*?)\]\[(.*?)\]\[(.*?)\]/;
      var reg = new RegExp(pattern);
      let items = formualItem.match(reg);
      let calResult = 0;
      if (items[1] == "T") {
        //表示本地模板数据
        calResult = await _this.getModuleData(items[2], items[3]);
      }
      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;
    },

    //获取远程数据
    async getRemoteData(code, sheet, row, col) {
      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("res:", res.data);
        return res.data.result;
      }
      return 0;
    },
    //获取本地文档模块数据
    async getModuleData(code, attrName) {
      let _this = this;
      let item = _this.coms.filter((o) => o.code == code);
      if (item.length > 0) {
        let attr = item[0].attrs.filter((o) => o.name == attrName);
        if (attr.length > 0) {
          return parseFloat(attr[0].content);
        }
      }
      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);
    },

    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);
    },
  },
};
</script>
<style lang="scss">
@import "./index.scss";
</style>
