import CodeMirror from "codemirror";

import "../../../style/less/code.less";
import "codemirror/theme/material-darker.css";

const codeEditorTpl = `
  <div class="code-editor">
    <div class="code-editor-body"></div>
    <div class="code-editor-footer">
      <button class="op-btn js-cancel">取消</button>
      <button class="op-btn js-confirm">确定</button>
    </div>
  </div>
`;

export default (editor, opt = {}) => {
  const tm = editor.TraitManager;
  tm.addType("code", {
    createLabel() {
      return "自定义脚本";
    },
    getInputEl: function () {
      if (!this.inputEl) {
        const button = document.createElement("button");
        button.innerText = "编辑";
        button.setAttribute('class', 'traits-btn');
        button.onclick = this.handleEditCode.bind(this);
        this.inputEl = button;
      }

      if (!this.$codeEditor) {
        const currentComponent = editor.getSelected();
        this.$codeEditor = $(codeEditorTpl);
        const $codeEditorBody = this.$codeEditor.find(".code-editor-body");
        const $confirmBtn = this.$codeEditor.find('.js-confirm');
        const $cancelBtn = this.$codeEditor.find('.js-cancel');

        this.codeMirror = CodeMirror($codeEditorBody[0], {
          lineWrapping: true,
          lineNumbers: false,
          theme: "material-darker",
          mode: "javascript",
          value: currentComponent.get("script").toString(),
        });

        this.codeMirror.execCommand("selectAll");
        this.codeMirror.execCommand("indentAuto");
        this.codeMirror.setCursor(0);

        $confirmBtn.on('click', () => {
          currentComponent.set('script', this.codeMirror.getValue());
          editor.store(function() {
            editor.Modal.close();
          });
        });

        $cancelBtn.on('click', () => {
          editor.Modal.close();
        })
      }

      return this.inputEl;
    },

    handleCancel: function() {
      editor.Modal.close();
    },

    handleEditCode: function () {
      const modal = editor.Modal;

      modal.setTitle("自定义脚本");

      modal.setContent(this.$codeEditor);

      modal.open();
    },
  });
};
