<template>
  <div class="picker">
    <div class="code-edit">
      <div class="top-title">公式</div>
      <codemirror
        ref="codeEditor"
        v-model="formulaStr"
        :options="cmOptions"
        @input="codeMirrorChange"
      ></codemirror>
    </div>
    <div>
      变量(额定载重：2，额定速度：3)：
      <el-button v-for="(item) in paramsList" @click="insertContent(item.name, 'variable',item.value)"> {{
          item.name
        }}
      </el-button>
    </div>
    <div>
      方法：
      <el-button v-for="item in funList" @click="insertContent(item.name, 'func',item.value)"> {{
          item.name
        }}
      </el-button>
    </div>
    <textarea v-model="formulaStr2"></textarea>

    <Row>
      <Col>
        <CustomButton label="获取" @handleClick="getContent"/>

        <CustomButton label="创建聊天室" @handleClick="createChatRoom"/>
        <CustomButton label="获取聊天室" @handleClick="getChatRoom"/>



      </Col>
      <Col>{{value}}</Col>
    </Row>
  </div>

</template>

<script>
import {codemirror} from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/idea.css";
import {listForConfig} from "../../api/business/crm/paralibrary/library";
import Row from "../../components/CustomElement/layout/Row.vue";
import Col from "../../components/CustomElement/layout/Col.vue";
import CustomButton from "../../components/CustomElement/CustomButton.vue";
import {addRule} from "../../api/business/configRule/configRule";
import {createChatRoom} from "../../api/common/MessageChat";

export default {
  components: {CustomButton, Col, Row, codemirror},
  data() {
    return {
      cmOptions: {
        // 语言及语法模式
        mode: 'text/javascript',
        // 主题
        theme: "idea",
        // 显示函数
        line: true,
        lineNumbers: false,
        // 软换行
        lineWrapping: true,
        // tab宽度
        tabSize: 4,
      },
      lang: 'javascript',
      formulaStr: "",
      formulaValueStr: "",
      paramsList: [],
      value:"",
      funList: [
        {
          name: 'SUM',
        }, {
          name: 'IF',

        },
        {
          name: 'ROUND',
        }
      ],
      funKeyMap: {
        'SUM': 'SUM_FUNC',
        'IF': 'IF_FUNC',
        'ROUND': 'ROUND_FUNC'
      },
      formulaStr2:""
    };
  },
  computed: {
    editor() {
      return this.$refs.codeEditor?.codemirror;
    }
  },
  mounted() {
    this.focus(this.formulaStr)
    this.autoMarkText();
    this.queryParamsLibrary();
    console.log(this.editor)
  },
  methods: {
    queryParamsLibrary() {
      listForConfig({}).then(res => {
        if (res && res.data) {
          this.paramsList = res.data.map(item => {
            return {
              name: item.paraName,
              value: item.paraCode,
              key: item.id
            };
          })
        }
      })
    },
    createChatRoom(){
      console.log(this.$store.state.selections.SSEChatMessage)
      console.log(this.$store.state.selections.SSEChatMessageClientId)
      let row={
        //报价单id
        "quotationId": 2,
      }
      createChatRoom(row)

    },
    getChatRoom(){

    },


    getContent() {
      console.log(this.editor)

      let formula = this.formulaValueStr;
      // 变量CODE替换
      //公式code替换
      Object.keys(this.funKeyMap).forEach(key => {
        let value = this.funKeyMap[key];
        formula = formula.replaceAll(key, `$@$${value}$@$`);
      })
      // 变量CODE替换
      this.paramsList.forEach(item => {
        formula = formula.replaceAll(item.name,  '$_$'+ item.value + '$_$');
      })
      console.log(formula)
      addRule({formValueStr: formula}).then(res => {
        this.value=res.data;
        if(this.value=='NaN'||this.value=='nan'){
          this.$message.error("公式有误，请检查")
        }
      })
    },
    codeMirrorChange() {
      //获取 editor 的内容
      this.formulaValueStr = this.formulaStr;

    },
    addFormula(content, type) {
      this.insertContent(content, type)
    },
    /**
     * editor 中的对内容进行处理
     * @param label
     * @param value
     * @param type variable | func，variable为表单变量，需标记，func 为函数，也需要做标记
     */
    insertContent(label, type, value) {
      const from = this.editor.getCursor();
      if (type === 'variable') {
        this.editor.replaceSelection(label);
        const to = this.editor.getCursor();
        this.markText(from, to, label, 'cm-field', value);
      } else if (type === 'func') {
        this.editor.replaceSelection(`${label}()`);
        const to = this.editor.getCursor();
        this.markText(from, {line: to.line, ch: to.ch - 2}, label, 'cm-func', value);
        this.editor.setCursor({line: to.line, ch: to.ch - 1});
      } else if (typeof label === 'string') {
        this.editor.replaceSelection(label);
      }
      this.editor.focus();
    },

    autoMarkText() {
      if (this.formulaStr) {
        this.autoMark(this.formulaStr);
        this.focus(this.formulaStr);
      }
    },
    focus(value) {
      this.editor.setCursor({
        line: 0,
        ch: value ? value.length : 0
      });
      this.editor.focus()
    },
    markText(from, to, label, className) {
      if (className === void 0) {
        className = "cm-func";
      }
      let text = document.createElement("span");
      text.className = className;
      text.innerText = label;
      this.editor.markText(from, to, {
        atomic: true,
        replacedWith: text,
      });
    },
    /**
     * 解析 editor 的内容，分别对表单变量和函数进行标记
     */
    autoMark() {
      const editor = this.editor;
      const lines = editor.lineCount();
      for (let line = 0; line < lines; line++) {
        const content = editor.getLine(line);
        // 标记函数调用,匹配一个或多个连续的大写字母，后面可以有任意数量的空白字符，再紧跟一个左括号
        content.replace(/([A-Z]+)\s*\(/g, (_, func, pos) => {
          this.markText({line: line, ch: pos}, {line: line, ch: pos + func.length}, func, 'cm-func');
          return _;
        });
        // 标记表单变量,这应该是动态获取，自行替换即可
        let vars = ["载重", "速度"];
        vars.forEach(v => {
          let from = 0;
          let idx = -1;
          while (~(idx = content.indexOf(v, from))) {
            this.markText({line: line, ch: idx}, {line: line, ch: idx + v.length}, v, 'cm-field');
            from = idx + v.length;
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.picker {
  height: 525px;
  text-align: left;
  width: 50%;
  margin: 0 auto;

  .code-edit {
    height: 240px;
    border-radius: 6px;
    border: 1px solid #e8e9eb;
  }
}

.top-title {
  background-color: #fafafa;
  height: 30px;
  vertical-align: center;
  line-height: 30px;
  padding-left: 10px;
  border-radius: 4px 4px 0 0;
  border-bottom: none;
}

/deep/ .CodeMirror {
  height: 200px !important;
  /*表单变量样式*/

  .cm-field {
    background: #007bff;
    padding: 3px 5px;
    border-radius: 3px;
    color: #fff;
    margin: 0 1px;
  }

  /*函数样式*/

  .cm-func {
    font-weight: bold;
    color: #ae4597;
    line-height: 14px;
    margin: 0 1px;
    padding: 0 2px;
  }

  .CodeMirror-scroll {
    width: 100%;
  }
}

</style>
