<template>
<div id='symbolbox' class="symbolbox" v-dialogDrag :style="cp_symbolboxStyle" v-show='show'>
  <el-container class='symbol-box'>
    <el-aside width='50px' class='toolsBox'>
      <div
        class='tools-item'
        v-for='item in toolsList'
        :key='item.key'
        :title="item.label"
        @click.stop='operateStyle(item.key,$event)'
        @mousemove.stop='mousemove(item.key,$event)'
      >{{item.label}}</div>
    </el-aside>
    <el-container class='symbol-main'>
      <el-header class='symbol-list' height='35px'>
        <el-radio-group v-model='selectedKey' @change='change' size='small' class='radio-box'>
          <el-radio-button
            v-for='(item, key) in symbolList'
            :key='key'
            :label='key'
            :value='key'
            :border='false'
            class='radio-box-item'
          >{{item.label}}</el-radio-button>
        </el-radio-group>
      </el-header>
      <el-main>
        <div v-if='selectedKey==="custom" && isAdmin' class='add-symbol-box'>
          <transition>
            <el-col class='symbol-form' v-if='showAddBox'>
              <el-input v-model='customValue'  type="textarea" :autosize="{ minRows: 2, maxRows: 16}" size='mini' class='symbol-input' clearable></el-input>
              <el-button @click='add' type='primary' class='symbol-btn' size='mini'>{{ t(`toolbar.save`) }}</el-button>
            </el-col>
          </transition>
          <div @click='showAddPage' class='tri-button' :title='t(`headerMent.symbolbox.add`)'>
            <span :class='[cStyle, styleName]'></span>
          </div>
        </div>
        <div
          class='symbol-item'
          v-for='(value,index) in selectedValue'
          :key='index'
          @click='addSymbol(value)'
          @mouseenter='displayDel($event,true)'
          @mouseleave='displayDel($event,false)'
        >
        <span @click='delSymbol($event,value)' v-if='selectedKey==="custom1"' :class='[delClass,"custom-delete", "el-icon-delete"]'></span>
        {{value}}</div>
      </el-main>
    </el-container>
  </el-container>
  <div class="symbolbox-resize-dot" ref="symbolbox-resize-dot"></div>
</div>
</template>

<script>
/* const keyFn = function(e) {
  if (this.show) {
    switch (e.keyCode) {
      case 9:
      case 13:
      case 38:
      case 40:
        this.show = false;
        break;
    }
  }
};*/

import Locale from 'element-ui-qz/src/mixins/locale';
import ElRadio from 'element-ui-qz/packages/radio';
import ElButton from 'element-ui-qz/packages/button';
import ElCol from 'element-ui-qz/packages/col';
import ElContainer from 'element-ui-qz/packages/container';
import ElAside from 'element-ui-qz/packages/aside';
import ElMain from 'element-ui-qz/packages/main';
import ElInput from 'element-ui-qz/packages/input';
import ElHeader from 'element-ui-qz/packages/header';
import ElRadioGroup from 'element-ui-qz/packages/radio-group';
import ElRadioButton from 'element-ui-qz/packages/radio-button';

export default {
  name: 'ElSymbolbox',
  mixins: [Locale],
  components: {
    ElCol,
    ElContainer,
    ElAside,
    ElMain,
    ElInput,
    ElHeader,
    ElRadioButton,
    ElButton,
    ElRadioGroup,
    ElRadio
  },
  data() {
    return {
      toolsList: [
        {
          key: 'sup',
          label: this.t(`headerMenu.symbolbox.sup`)
        },
        {
          key: 'sub',
          label: this.t(`headerMenu.symbolbox.sub`)
        },
        {
          key: 'i',
          label: this.t(`headerMenu.symbolbox.i`)
        }
      ],
      symbolList: {
        math: {
          label: this.t(`headerMenu.symbolbox.math`),
          value: [
            '≈',
            '≡',
            '≠',
            '＝',
            '≤',
            '≥',
            '≮',
            '≯',
            '∷',
            '±',
            '＋',
            '－',
            '×',
            '÷',
            '／',
            '∫',
            '∮',
            '∝',
            '∞',
            '∧',
            '∨',
            '∑',
            '∏',
            '∪',
            '∩',
            '∈',
            '∵',
            '∴',
            '⊥',
            '‖',
            '∠',
            '⌒',
            '⊙',
            '≌',
            '∽',
            '√'
          ]
        },
        unit: {
          label: this.t(`headerMenu.symbolbox.unit`),
          value: ['°', '′', '〃', '＄', '￡', '￥', '‰', '％', '℃', '¤', '￠']
        },
        special: {
          label: this.t(`headerMenu.symbolbox.special`),
          value: [
            '︻',
            '︼',
            '︽',
            '︾',
            '〒',
            '⊙',
            '●',
            '〇',
            '◎',
            '¤',
            '★',
            '☆',
            '■',
            '▓',
            '「',
            '」',
            '『',
            '』',
            '◆',
            '◇',
            '▲',
            '△',
            '▼',
            '▽',
            '◣',
            '◥',
            '◢',
            '◣',
            '◤',
            '◥',
            '№',
            '↑',
            '↓',
            '→',
            '←',
            '↘',
            '↙',
            'Ψ',
            '※',
            '㊣',
            '∑',
            '⌒',
            '∩',
            '【',
            '】',
            '〖',
            '〗',
            '＠',
            'ξ',
            'ζ',
            'ω',
            '□',
            '∮',
            '〓',
            '※',
            '》',
            '∏',
            '卐',
            '√',
            '╳',
            '々',
            '♀',
            '♂',
            '∞',
            '①',
            'ㄨ',
            '≡',
            '╬',
            '╭',
            '╮',
            '╰',
            '╯',
            '╱',
            '╲'
          ]
        },
        letter: {
          label: this.t(`headerMenu.symbolbox.letter`),
          value: [
            'Α',
            'Β',
            'Γ',
            'Δ',
            'Ε',
            'Ζ',
            'Η',
            'Θ',
            'Ι',
            'Κ',
            '∧',
            'Μ',
            'Ν',
            'Ξ',
            'Ο',
            '∏',
            'Ρ',
            '∑',
            'Τ',
            'Υ',
            'Φ',
            'Χ',
            'Ψ',
            'Ω',
            'α',
            'β',
            'γ',
            'δ',
            'ε',
            'ζ',
            'η',
            'θ',
            'ι',
            'κ',
            'λ',
            'μ',
            'ν',
            'ξ',
            'ο',
            'π',
            'ρ',
            'σ',
            'τ',
            'υ',
            'φ',
            'χ',
            'ψ',
            'ω'
          ]
        },
        custom: {
          label: this.t(`headerMenu.symbolbox.custom`),
          value: []
        }
      },
      show: false,
      selectedKey: 'math',
      selectedValue: [
        '≈',
        '≡',
        '≠',
        '＝',
        '≤',
        '≥',
        '≮',
        '≯',
        '∷',
        '±',
        '＋',
        '－',
        '×',
        '÷',
        '／',
        '∫',
        '∮',
        '∝',
        '∞',
        '∧',
        '∨',
        '∑',
        '∏',
        '∪',
        '∩',
        '∈',
        '∵',
        '∴',
        '⊥',
        '‖',
        '∠',
        '⌒',
        '⊙',
        '≌',
        '∽',
        '√'
      ],
      customValues: [
        '≈',
        '≡',
        '≠',
        '＝',
        '≤',
        '≥',
        '≮',
        '≯',
        '∷',
        '±',
        '＋',
        '－',
        '×',
        '÷',
        '／',
        '∫',
        '∮',
        '∝',
        '∞',
        '∧',
        '∨'
      ],
      customValue: '',
      selectedStatus: '',
      showAddBox: false,
      styleName: 'el-icon-caret-bottom',
      cStyle: 'expand',
      inputEl: '',
      baseUrl: '',
      customId: '',
      delClass: 'hide-delete',
      userInfo: JSON.parse(localStorage.getItem('userInfo') || null),
      isAdmin: false,
      opts: {
        maxWidth: 900,
        maxHeight: 600,
        minWidth: 404,
        minHeight: 200,
        width: 450,
        height: 235,
        resizeAble: true
      }
    };
  },
  computed: {
      cp_symbolboxStyle () {
          const { width, height } = this.opts
          return { width: `${width}px`, height: `${height}px` }
      }
  },
  mounted() {
    this.opts.resizeAble && this.initResize()
    this.$el.__vue__ = this;
    this.isAdmin = this.userInfo && this.userInfo.env$login_na === 'admin';
    this._addBehavior();
    this.$nextTick(() => {
      this.$el.setAttribute('QZ_VUE_WIDGET', '');
      this.$el.data && this.$el.data('QZ_VUE_WIDGET', this);
      this.$http
        .get(
          this.baseUrl + 'ks-prj/sys/config/getConf',
          {
            params: {
              JID: localStorage.getItem('__JID__'),
              conf_type: 'symbol'
            }
          },
          { emulateJSON: true }
        )
        .then(res => {
          if (res.body && res.body.status) {
            let data = res.body.obj || {};
            this.customId = data.id || '';
            this.selectedKey = data.conf_val ? 'custom' : this.selectedKey;
            this.symbolList.custom.value = data.conf_val
              ? data.conf_val.split(',')
              : [];
          }
        });
    });
    // /*输入问题处理*/
    window.selfEV = document.createEvent('HTMLEvents');
    window.selfEV.initEvent('input', false, true);

    // /*手动触发change*/
    window.selfEVC = document.createEvent('HTMLEvents');
    window.selfEVC.initEvent('change', false, true);
  },
  methods: {
    mousemove() {

    },
    // /*添加事件*/
    _addBehavior() {
      // document.addEventListener('keydown', keyFn.bind(this));
    },
    // /*获取当前触发的input框*/
    setOrignalDom(el) {
      this.inputEl = el;
      this.selectedKey = 'math';
      this.selectedValue = [
        '≈',
        '≡',
        '≠',
        '＝',
        '≤',
        '≥',
        '≮',
        '≯',
        '∷',
        '±',
        '＋',
        '－',
        '×',
        '÷',
        '／',
        '∫',
        '∮',
        '∝',
        '∞',
        '∧',
        '∨',
        '∑',
        '∏',
        '∪',
        '∩',
        '∈',
        '∵',
        '∴',
        '⊥',
        '‖',
        '∠',
        '⌒',
        '⊙',
        '≌',
        '∽',
        '√'
      ];
      if (this.symbolList.custom.value.length > 0) {
        this.selectedKey = 'custom';
        this.selectedValue = this.symbolList.custom.value;
      }
    },
    // /*设置接口url*/
    setBaseUrl(baseUrl) {
      this.baseUrl = baseUrl;
    },
    // /*添加特殊符号*/
    addSymbol(val) {
      let start = this.inputEl.selectionStart;
      let end = this.inputEl.selectionEnd;
      let value = this.inputEl.value;
      let val1 = '';
      let val2 = '';
      val1 = value.substring(0, start);
      val2 = value.substr(end);
      this.inputEl.value = val1 + val + val2;
      this.inputEl.focus();
      this.inputEl.selectionStart = start + val.length;
      this.inputEl.selectionEnd = start + val.length;
      this.fireEvent();
    },
    // /*//显隐*/
    hide(val) {
      this.show = !val;
      if (this.show) {
        this.userInfo = JSON.parse(localStorage.getItem('userInfo') || null);
        this.isAdmin = this.userInfo && this.userInfo.env$login_na === 'admin';
      }
      if (val && this.inputEl && this.inputEl.dispatchEvent) {
        this.inputEl.dispatchEvent(window.selfEVC);
      }
    },
    // /*/选中操作*/
    operateStyle(val, event) {
      let start = this.inputEl.selectionStart;
      let end = this.inputEl.selectionEnd;
      let value = this.inputEl.value;
      let val1, val2, val3;
      val1 = value.substring(0, start);
      val2 = value.substr(end);
      val3 = value.substring(start, end);
      this.inputEl.value = val3
        ? `${val1}<${val}>${val3}</${val}>${val2}`
        : `${val1}<${val}></${val}>${val2}`;
      this.inputEl.focus();
      this.fireEvent();
    },
    change(val) {
      this.selectedValue = this.symbolList[val].value;
      if (this.selectedKey === 'custom' && this.selectedValue.length === 0) {
        this.showAddBox = true;
      }
      this.inputEl.focus();
    },
    add() {
      if (this.selectedValue.length !== 0 && this.customValue === '') {
        this.$message.warning(this.t(`headerMenu.symbolbox.addTip`));
        return;
      }
      let newValues = this.customValue.replace(/\n/g, ',');
      this.$http
        .post(
          this.baseUrl + 'ks-prj/sys/config/save',
          {
            JID: localStorage.getItem('__JID__'),
            conf_val: newValues,
            conf_type: 'symbol',
            id: this.customId
          },
          { emulateJSON: true }
        )
        .then(res => {
          if (res.body.status) {
            this.selectedValue = res.body.obj.conf_val.split(',');
            this.symbolList.custom.value = res.body.obj.conf_val.split(',');
            this.customValue = '';
            this.showAddBox = false;
            this.$message.success(this.t(`message.addSuccess`));
          } else {
            this.$message.error(this.t(`message.addFail`));
          }
        });
    },
    showAddPage() {
      this.showAddBox = !this.showAddBox;
      if (this.styleName.includes('bottom')) {
        let values = this.selectedValue;
        let startIndex = 0;
        let parts = [];
        let length = values.length;
        let fn = (start) => {
          let s = start * 10;
          if (s < length) {
            parts.push(values.slice(startIndex, s));
            startIndex = s;
            start = start + 1;
            fn(start);
          } else {
            parts.push(values.slice(startIndex, length));
          }
        };
        fn(1);
        this.customValue = parts.join('\n');
        this.styleName = 'el-icon-caret-top';
      } else {
        this.styleName = 'el-icon-caret-bottom';
      }
    },
    fireEvent() {
      this.inputEl.dispatchEvent(window.selfEV);
    },
    displayDel(event, show) {
      if (this.selectedKey !== 'custom2') return;
      if (show) {

        event.target.querySelector('span').style.display = 'inline-block';
      } else {
        event.target.querySelector('span').style.display = 'none';

      }
    },
    delSymbol(event, str) {
      event.stopPropagation();
      let newArr = this.selectedValue.filter(v=>v !== str);
      this.$http
        .post(
          this.baseUrl + 'ks-prj/sys/config/save',
          {

            JID: localStorage.getItem('__JID__'),
            conf_val: newArr.join(','),
            conf_type: 'symbol',
            id: this.customId
          },
          { emulateJSON: true }
        )
        .then(res => {
          if (res.body.status) {
            if (res.body.obj.conf_val) {
              this.selectedValue = res.body.obj.conf_val.split(',');
              this.symbolList.custom.value = res.body.obj.conf_val.split(',');
            } else {
              this.selectedValue = [];
              this.symbolList.custom.value = [];
            }
            this.customValue = '';
            this.showAddBox = false;
            this.$message.success(this.t(`message.delSuccess`));
          } else {
            this.$message.error(this.t(`message.delFail`));
          }
        });
      this.fireEvent();
    },
    options (opts = {}) {
        Object.assign(this.opts, opts)
        if (!this.initResizeSign) {
            this.initResize()
        }
    },
    initResize () {
        this.initResizeSign = true
        const { maxWidth, maxHeight, minWidth, minHeight } = this.opts
        const resezeRef = this.$refs['symbolbox-resize-dot'];
        let [w, h] = [0, 0]
        let symbolboxRef = null
        const getLast = (ev) => {
            const el = symbolboxRef || (symbolboxRef = document.querySelector('#symbolbox'))
            const { width, height } = el && el.getBoundingClientRect() || {}
            w = width
            h = height
            return { width, height }
        }
        const handleMousedown = (ev) => {
            document.addEventListener('mousemove', handleMousemove)
            document.addEventListener('mouseup', handleMouseup)
            symbolboxRef.style.userSelect = `none`
            getLast()
        }
        const handleMousemove = (ev) => {
            getLast()
            const { movementX, movementY } = ev
            if (!symbolboxRef) return false
            if ((movementX > 0 && w < maxWidth) || (movementX < 0 && w > minWidth)) {
                symbolboxRef.style.width = w + movementX + 'px'
            }
            if ((movementY > 0 && h < maxHeight) || (movementY < 0 && h > minHeight)) {
                symbolboxRef.style.height = h + movementY + 'px'
            }
        }
        const handleMouseup = (ev) => {
            document.removeEventListener('mousemove', handleMousemove)
            document.removeEventListener('mouseup', handleMouseup)
            symbolboxRef.style.userSelect = `initial`
        }

        resezeRef.addEventListener('mousedown', handleMousedown)
    }
  },
  beforeDestroy() {
    this.inputEl = '';
    // document.removeEventListener('keydown', keyFn);
  },
  directives: {
    dialogDrag: {
      inserted(el, bindings, vnode) {
        const dialogEl = el;
        const headerEl = dialogEl.getElementsByClassName('symbol-list')[0];
        //
        dialogEl.style.top = '0';
        dialogEl.style.left = '0';
        headerEl.style.cursor = 'move';
        //
        const sty = dialogEl.currentStyle || window.getComputedStyle(dialogEl, null);
        headerEl.onmousedown = e => {
          // 计算当前元素距离可视区的距离
          const disX = e.clientX - headerEl.offsetLeft;
          const disY = e.clientY - headerEl.offsetTop;
          // 获取到的值带px 正则匹配替换
          let styL, styT;
          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes('%')) {
            styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
            styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
          } else {
            styL = +sty.left.replace(/\px/g, '');
            styT = +sty.top.replace(/\px/g, '');
          }
          const screenWidth = document.documentElement.clientWidth;
          const screenHeight = document.documentElement.clientHeight;
          const minLeft = dialogEl.offsetLeft;
          const maxLeft = screenWidth - dialogEl.offsetLeft - dialogEl.offsetWidth;
          const minTop = dialogEl.offsetTop;
          const maxTop = screenHeight - dialogEl.offsetTop - dialogEl.offsetHeight;
          //
          if (el.scrollHeight > screenHeight) {
            headerEl.style.cursor = '';
            return;
          }
          document.onmousemove = e => {
            // console.log(e, e.target);
            if (e.target.className === 'el-radio-button__inner') {
              return;
            }
            e.preventDefault();
            // 计算移动的距离
            let left = e.clientX - disX;
            let top = e.clientY - disY;
            // 距离(边界)控制
            if (-left > minLeft) {
              left = -minLeft;
            } else if (left > maxLeft) {
              left = maxLeft;
            }
            if (-top > minTop) {
              top = -minTop;
            } else if (top > maxTop) {
              top = maxTop;
            }
            // 移动当前元素
            dialogEl.style.left = `${left + styL}px`;
            dialogEl.style.top = `${top + styT}px`;
          };
          document.onmouseup = e => {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    }
  }
};
</script>
<style lang='scss' scoped>
.symbolbox{
  z-index: 999999999;
  position: absolute;
  left: 2px;
  top: 2px;
  .symbolbox-resize-dot{
    position: absolute;
    bottom: 0px;
    right: 0px;
    width: 12px;
    height: 12px;
    cursor: nw-resize;
    user-select: none;
  }
}
.symbol-box {
  left: 2px;
  top: 2px;
  // position: fixed;
  z-index: 9999;
  background-color: #fff;
//   width: 625px;
//   height: 300px;
    width: 100%;
    height: 100%;
  box-shadow: 1px 1px 8px 2px #868686;
  border: 2px solid #cccccc;
}
.toolsBox {
  width: 100px;
}
.symbol-box .el-radio-button__inner {
  line-height: 1.5 !important;
}
.symbol-box .el-radio-group {
  background-color: transparent;
  margin-top: 1px;
  margin-left: 2px;
}
.symbol-box .el-radio-button {
  border-width: 0px;
}
.tools-item {
  border-top-color: #a6a6a6;
  border-top-style: solid;
  border-top-width: 0px;
  border-bottom-color: #a6a6a6;
  border-bottom-style: solid;
  border-bottom-width: 0px;
  margin-top: 10px;
  box-sizing: border-box;
  color: #888888;
  cursor: pointer;
  display: inline-block;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', 'SimSun', 'sans-serif';
  font-size: 14px;
  font-weight: 500;
  height: 40px;
  line-height: 14px;
  padding: 12px 0px;
  position: relative;
  text-align: center;
  transition-duration: 0.3s;
  transition-property: all;
  transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);
  vertical-align: middle;
  white-space: nowrap;
  width: 48px;
  -webkit-font-smoothing: antialiased;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.tools-item:hover {
  border-left-style: solid;
  border-left-width: 5px;
  border-left-color: #409eff;
  color: #409eff;
  background-color: #cfcfcf;
}
.tools-item-selected {
  color: #409eff;
  background-color: #cfcfcf;
}
.tools-item:first-of-type {
  margin-top: 75px;
}
.add-symbol-box {
  .symbol-form {
    // border: 1px solid #eee;
    // line-height: 45px;
    margin: 2px;
    height: auto;
    .symbol-input {
      width: 85%;
    }
    .symbol-btn {
      margin-left: 2%;
    }
  }
  .tri-button {
    text-align: center;
    width: calc(100% - 2px);
    font-size: 22px;
    color: #409eff;
    cursor: pointer;
    border: 1px solid #eee;
    line-height: 25px;
    float: left;
    height: 25px;
  }
  .tri-button:hover {
    background-color: #efefef;
  }
}

.symbol-item {
  border-color: rgb(220, 223, 230);
  border-style: solid;
  border-width: 1px;
  box-sizing: border-box;
  color: rgb(96, 98, 102);
  cursor: pointer;
  display: inline-block;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', 'SimSun', 'sans-serif';
  font-size: 14px;
  font-weight: 500;
  height: 40px;
  line-height: 14px;
  outline-color: rgb(96, 98, 102);
  padding: 12px 20px;
  position: relative;
  text-align: center;
  transition-duration: 0.3s;
  transition-property: all;
  transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);
  vertical-align: middle;
  white-space: nowrap;
  width: 55px;
  -webkit-font-smoothing: antialiased;
}
.symbol-item:hover {
  color: #409eff;
  border-color: #409eff;
}
.symbol-box .custom-delete{
    width: 12px;
    margin-left: 18px;
    margin-top: -10px;
    position: absolute;
    font-size: 10px;
    height: 12px;
    display: inline-block;
    color: red;
}
.symbol-box .show-delete{
  display: inline-block
}
.symbol-box .hide-delete{
  display: none
}
.symbol-box .el-header {
  background: #f7f7f7 !important;
  position: relative;
  height: 35px !important;
}
.symbol-list {
  border-bottom: 1px solid #dcdfe6;
}
.symbol-box .el-aside {
  background-color: #f0f0f0;
  text-align: center;
  height: auto;
  top: 0px !important;
  width: 50px !important
}
.symbol-box .el-main {
  margin-top: 0px;
  padding: 0px;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>