<!-- 搜索表单 -->
<template>
  <div>
    <el-popover
      style="position: fixed; z-index: 2000"
      width="130"
      ref="popoverRef"
      v-model="rightClickShow"
      @click.native="rightClickShow = false"
    >
      <div>
        <el-button type="primary" @click="addHtml">插入输入框</el-button>
      </div>
    </el-popover>
    <div
      v-html="form"
      :contenteditable="edit"
      class="contenteditable"
      :ref="id"
      :id="id"
      @contextmenu.prevent="onRightClick($event)"
    >
    </div>
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import { generateRandomString } from '@/utils/util';

  export default {
    props: {},
    mixins: [dictMixins],
    props: {
      id: '',
      edit: {
        default: true,
        type: Boolean
      }
    },
    data() {
      return {
        form: null,
        valueObj: {},
        equation: {},
        domId: '',
        rightClickShow: false
      };
    },
    methods: {
      addHtml() {
        this.insertInput();
      },
      objInit() {
        if (Object.keys(this.valueObj).length) {
          for (let key in this.valueObj) {
            this.$nextTick(() => {
              let dom = document.getElementById(key);
              dom.value = this.valueObj[key];
            });
          }
        }
      },
      insertInput() {
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
          const range = selection.getRangeAt(0);

          this.getParentID(range.commonAncestorContainer);
          if (this.getParentID(range.commonAncestorContainer)) {
            range.setStart(selection.anchorNode, selection.anchorOffset);
            range.setEnd(selection.focusNode, selection.focusOffset);
            range.deleteContents(); // 删除选中的内容（如果需要）
            range.insertNode(this.getInput()); // 插入input元素
            // 可以设置光标位置在input之后
            range.selectNodeContents(this.getInput());
            range.collapse(false); // 光标放在input之后
            selection.removeAllRanges();
            selection.addRange(range);
          }

          // return
        }
      },
      getParentID(data) {
        if (data.id == this.id) {
          return true;
        }
        if (data.parentElement) {
          return this.getParentID(data.parentElement);
        }
      },

      getInput() {
        let id = generateRandomString();
        const inputElement = document.createElement('input');
        inputElement.setAttribute('type', 'text');
        inputElement.setAttribute('class', 'templateInput');
        inputElement.setAttribute('id', id);
        return inputElement;
      },
      getValue() {
        let inputs = document.querySelectorAll(
          '#' + this.id + ' .templateInput'
        );
        let data = {};
        if (inputs.length) {
          inputs.forEach((item) => {
            data[item.id] = item.value;
          });
        }
        return {
          form: this.$refs[this.id].innerHTML,
          valueObj: data,
          equation: this.equation
        };
      },
      equationValue({ domId, value }) {
        if (domId) {
          let dom = document.getElementById(domId);
          if (dom) {
            this.valueObj[domId] = value;
            dom.value = value;
          }
        }
      },
      init({ form, valueObj, equation }) {
        this.form = form;
        this.valueObj = valueObj;
        this.equation = equation || {};
        this.$nextTick(() => {
          if (!this.edit) {
            let inputs = document.querySelectorAll('.templateInput');
            inputs.forEach((item) => {
              item.setAttribute('readonly', 'readonly');
            });
          }
        });
        this.objInit();
      },
      editInputChange(domObj) {
        let dom = document.getElementById(this.domId);
        dom.style.width = domObj.width + 'px';
        if (domObj.readonly == 2) {
          dom.setAttribute('readonly', 'readonly');
        } else {
          dom.removeAttribute('readonly');
        }
        delete this.valueObj[dom.id];
        this.valueObj[domObj.id] = dom.value;
        if (domObj.equation) {
          this.equation[domObj.id] = domObj.equation;
        }
        dom.id = domObj.id;
      },
      onRightClick(PointerEvent) {
        this.rightClickShow = true;
        this.$nextTick(() => {
          let y = PointerEvent.pageY;
          let x = PointerEvent.pageX + 10;
          if (PointerEvent.screenY >= PointerEvent.view.innerHeight) {
            y -= 80;
          }
          this.$refs.popoverRef.$el.style.top = y + 'px';
          this.$refs.popoverRef.$el.style.left = x + 'px';
        });
      },
      inputChange(event) {
        if (event.target && event.target.className == 'templateInput') {
          this.valueObj[event.target.id] = event.target.value;

          this.$emit('calculation');
        }
      },
      inputClick(event) {
        if (!this.edit) {
          return;
        }
        if (event.target && event.target.className == 'templateInput') {
          this.domId = event.target.id;
          this.$emit('editShow', {
            templateDivRef: 'customTextRef' + this.id,
            domObj: {
              width: event.target.offsetWidth,
              id: event.target.id,
              readonly: event.target.readOnly ? 2 : 1,
              equation: this.equation[this.domId]
            }
          });
        }
      }
    },

    mounted() {
      this.$nextTick(() => {
        document
          .getElementById(this.id)
          .addEventListener('input', this.inputChange);

        document
          .getElementById(this.id)
          .addEventListener('click', this.inputClick);
      });
    }
  };
</script>
<style lang="scss" scoped>
  :deep(.templateInput) {
    width: 80px;
    border: solid 1px #bfbfbf;
    padding: 1px;
    margin: 1px;
    margin-left: 3px;
    text-align: center;
  }
  .contenteditable {
    // padding: 5px;
    width: 100%;
    min-height: 20px;
    padding-left: 10px;
    // border: solid 1px #b3b0b0;
  }
</style>
