<template>
  <div class="app-container">
    <el-form label-position="left" label-width="100px">
      <div class="itemGroup">
        <el-divider content-position="left">公式设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公式名称：">
              <el-input />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="算法说明：">
              <el-input type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22" :xs="20">
            <el-form-item label="计算公式："><div id="container" ref="container" contenteditable="true" class="container" />
            </el-form-item>
          </el-col>
          <el-col :span="2" :xs="4">
            <div style="text-align:center;v">
              <el-button @click="clearFormula">清除</el-button>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" :align="bottom">

          <el-col :span="4" :xs="12">
            <BaseTag v-for="x in innerModel.keys.filter(y=>y.type=='funs')" :key="x" :name="x.name" :detail="x.detail" :val="x.val" :type="x.type" @push="push" />
          </el-col>
          <el-col :span="4" :xs="12">
            <BaseTag v-for="x in innerModel.keys.filter(y=>y.type=='args')" :key="x" :name="x.name" :detail="x.detail" :val="x.val" :type="x.type" @push="push" />
          </el-col>
          <el-col :span="4" :xs="12">
            <BaseTag v-for="x in innerModel.keys.filter(y=>y.type=='jsf1')" :key="x" :name="x.name" :detail="x.detail" :val="x.val" :type="x.type" @push="push" />
          </el-col>
          <el-col :span="4" :xs="12">
            <BaseTag v-for="x in innerModel.keys.filter(y=>y.type=='jsf2')" :key="x" :name="x.name" :detail="x.detail" :val="x.val" :type="x.type" @push="push" />
          </el-col>

          <el-col :span="4" :xs="12">
            <div style="width:140px">
              <el-tag data-value="Round" type="info" class="tags">
                7
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                8
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                9
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                4
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                5
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                6
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                1
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                2
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                3
              </el-tag>
              <el-tag data-value="Round" type="info" class="tags">
                0
              </el-tag>
            </div>
          </el-col>
          <el-col :span="4" style="vertical-align: bottom;    text-align: right;">
            <el-button type="primary">保存</el-button>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
<script>
import BaseTag from '@/views/smp/components/baseTag'
export default {
  name: 'FormulaEdit',
  components: { BaseTag },
  data() {
    return {
      self: { select: {}, lastRange: {}},
      innerModel: {
        formula: '是否（最大值（体重,称重）》首重,首重价格+向上取整（（最大值（称重,体重）-首重）÷续重）×续重价格,首重价格）',
        keys: [
          { name: '是否', detail: '是否', val: '是否(,,)', type: 'funs' },
          { name: '最大值', detail: '最两值最大值 最大值(1,2)=2', val: '最大值(,)', type: 'funs' },
          { name: '向上取整', detail: '向上取整 取整(0.5)=1', val: '取整()', type: 'funs' },
          { name: '四舍五入', detail: '四舍五入', val: '四舍五入()', type: 'funs' },

          { name: '称重', detail: '实际称重重量', val: '称重', type: 'args' },
          { name: '体重', detail: '长*宽*高/体重系数', val: '体重', type: 'args' },
          { name: '首重', detail: '多少克起算', val: '首重', type: 'args' },
          { name: '续重', detail: '多少克为一个计算单位', val: '续重', type: 'args' },
          { name: '首重价格', detail: '首重价格', val: '首重价格', type: 'args' },
          { name: '续重价格', detail: '续重价格', val: '续重价格', type: 'args' },

          { name: '&', detail: '两个条件都满足', val: '&', type: 'jsf1' },
          { name: '|', detail: '两个条件满足一个', val: '|', type: 'jsf1' },
          { name: '》', detail: '大于', val: '>', type: 'jsf1' },
          { name: '《', detail: '小于', val: '<', type: 'jsf1' },
          { name: '==', detail: '等于', val: '==', type: 'jsf1' },
          { name: '≥', detail: '大于等于', val: '≥', type: 'jsf1' },
          { name: '≤', detail: '小于等于', val: '≤', type: 'jsf1' },

          { name: '+', detail: '加法运算', val: '+', type: 'jsf2' },
          { name: '-', detail: '减法运算', val: '-', type: 'jsf2' },
          { name: '×', detail: '乘法运算', val: '×', type: 'jsf2' },
          { name: '÷', detail: '除法运算', val: '÷', type: 'jsf2' },
          { name: '（', detail: '除法运算', val: '(', type: 'jsf2' },
          { name: '）', detail: '除法运算', val: ')', type: 'jsf2' }
        ],
        key: [',', '(', ')'],
        jsf: ['&gt;', '&#47;', '&#43', '&#45', '&#42;', '&lt;', '×', '÷', '&amp;', '&#166', '==', '≥', '≤']
        /*
        < &lt;
        > &gt;
        / &#47;
         + &#43;
         - &#45;
         * &#42;
         */
      }
    }
  },
  mounted() {
    var s = this.self
    document.addEventListener('selectionchange', function() {
      var sel = getSelection()
      if (!sel) {
        return
      }
      var node = sel.anchorNode
      var isIn = false
      while (node && node.nodeType != node.DOCUMENT_NODE) {
        var cls = node.classList
        if (cls && cls.contains('container')) {
          isIn = true
          break
        }
        node = node.parentNode
      }
      if (!isIn) return
      console.log('getCursor')
      s.select = sel
      s.lastRange = sel.getRangeAt(0)
    })
    this.initDisplay()
  },
  methods: {
    htmlEncode(html) {
      // 1.首先动态创建一个容器标签元素，如DIV
      var temp = document.createElement('div');
      // 2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐，google支持)
      (temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html)
      // 3.最后返回这个元素的innerHTML，即得到经过HTML编码转换的字符串了
      var output = temp.innerHTML
      temp = null
      return output
    },
    clearFormula() {
      this.$refs.container.innerHTML = ''
      this.$refs.container.focus()
    },
    htmlEncodeByRegExp(str) {
      var temp = ''
      if (str.length == 0) return ''
      temp = str.replace(/&/g, '&amp;')
      temp = temp.replace(/</g, '&lt;')
      temp = temp.replace(/\//g, '&#47;')
      temp = temp.replace(/>/g, '&gt;')
      temp = temp.replace(/\s/g, '&nbsp;')
      temp = temp.replace(/\'/g, '&#39;')
      temp = temp.replace(/\"/g, '&quot;')
      return temp
    },
    push(val, type, title) {
      this.copy(val, type, title)
    },
    copy(val, type, title) {
      var sel = this.self.select
      var range = this.self.lastRange
      if (!sel || !range) return
      var el
      el = document.createElement('div')
      el.innerHTML = val
      el.className = type
      el.setAttribute('title', title)
      range.insertNode(el)
      this.moveRange(this.self, el, range)
    },
    moveRange(self, el, range) {
      var sel = self.select
      if (!sel) {
        console.log(sel)
        return
      }
      range = (range || self.lastRange).cloneRange()
      if (el) {
        debugger
        if (el.className == 'funs' && el.innerHTML.indexOf('(') > -1) {
          var indexOf = el.innerHTML.indexOf('(')
          range.setStart(el, 0)
        }
        if (!el.nextSibling && el.nodeName == 'P') {
          range.setStart(el, 0)
        } else if (el.nextSibling) {
          range.setStart(el.nextSibling, 0)
        } else {
          range.setStartAfter(el)
        }
      }
      range.collapse(true)
      sel.removeAllRanges()
      sel.addRange(range)
    },
    initDisplay() {
      const { keys, formula } = this.innerModel
      const result = formula
      var ks = keys.sort((x, y) => {
        if (x.name.length > y.name.length) {
          return -1
        } else {
          return 1
        }
      })
      for (let i = 0; i < ks.length; i++) {
        var key = ks[i].name
        var title = ks[i].detail
        var type = ks[i].type
        var mk = key
          .replace('&', '\\&')
          .replace('|', '\\|')
          .replace('>', '\\>')
          .replace('<', '\\<')
          .replace('+', '\\+')
          .replace('-', '\\-')
        var html = this.htmlEncode(key)
          .replace('》', '&gt;')
          .replace('《', '&lt;')
          .replace('（', '(')
          .replace('）', ')')
        var end = ''
        if (type != 'jsf1' && type != 'jsf2') {
          end = '(?![\u4E00-\u9FFF])'
        }
        const name = `<div  class='${type}' title='${title}'>${html}</div>`
        var js = `result=result.replace(/${mk}${end}/g,name)`
        eval(js)
        console.info(result)
      }

      this.$refs.container.innerHTML = result
    }
  }
}
</script>
<style>
#container{font-size: 18px;border:1px solid #ebebeb;padding:10px;border-radius: 5px;}
.itemGroup {
  margin: 10px;
  border: 1px solid #ebebeb;
  padding: 30px;
}

.tags{
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;
}

.args{
    color:#4878fb;
    display: inline;
}
.funs{
    color: #ad0396;
    display: inline;
}
.jsf1,.jsf2{
    color: #ad0303;
    display: inline;
    margin:0 5px;
}

</style>
