"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /**
 * Created by S.C. on 2019/11/16.
 */
var TextArea = _antd.Input.TextArea;
var isIE = !!document.all;
var VarTemplate = /*#__PURE__*/function (_Component) {
  _inherits(VarTemplate, _Component);
  var _super = _createSuper(VarTemplate);
  function VarTemplate(props) {
    var _this;
    _classCallCheck(this, VarTemplate);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "handleBlur", function (e) {
      _this.getCurrentCursor();
    });
    _defineProperty(_assertThisInitialized(_this), "handleFocus", function (e) {
      // console.log('获取焦点')
      // this.$emit('focus', event)
    });
    _defineProperty(_assertThisInitialized(_this), "handleInputChange", function (e) {
      var onChange = _this.props.onChange;
      _this.getCurrentCursor();
      _this.setState({
        currentContent: e.target.value,
        startNum: e.target.value.length,
        endNum: e.target.value.length,
        wordCount: e.target.value.length
      });
      if (onChange) onChange(e.target.value);
    });
    _defineProperty(_assertThisInitialized(_this), "setTagWords", function (key) {
      var onChange = _this.props.onChange;
      var _this$state = _this.state,
        currentContent = _this$state.currentContent,
        startNum = _this$state.startNum,
        endNum = _this$state.endNum;
      _this.setState({
        currentContent: _this.insertContent(currentContent, key, startNum, endNum),
        startNum: startNum + key.length,
        // 光标起始位置累加
        endNum: endNum + key.length,
        // 光标起始位置累加
        wordCount: _this.insertContent(currentContent, key, startNum, endNum).length
      });
      if (onChange) onChange(_this.insertContent(currentContent, key, startNum, endNum));
      setTimeout(function () {
        _this.moveToCursor(); // 重新定位光标
      });
    });
    /**
     * 指定位置插入标签占位符字符串，当光标有选中一段字符时，会将直接将其替换
     * @param {str}       需要做插入的字符串
     * @param {insertStr} 需要插入的字符串
     * @param {start}     指定开始位置
     * @param {end}       指定结束位置
     * */
    _defineProperty(_assertThisInitialized(_this), "insertContent", function (str, insertStr, start, end) {
      if (start !== end) {
        var _prevStr = str.substring(0, start);
        var _nextStr = str.substring(end, str.length);
        return _prevStr + insertStr + _nextStr;
      }
      var prevStr = str.substring(0, start);
      var nextStr = str.substring(start, str.length);
      return prevStr + insertStr + nextStr;
    });
    /**
     * 获取当前（上一次）光标的位置
     * @参考 http://blog.csdn.net/chadcao/article/details/6575927
     * @TODO IE、火狐浏览器下未验证
     */
    _defineProperty(_assertThisInitialized(_this), "getCurrentCursor", function () {
      var start = 0;
      var end = 0;
      var oTextarea = _this.content.querySelector('textarea'); // 获取textarea标签
      if (isIE) {
        // selection 当前激活选中区，即高亮文本块，和/或文当中用户可执行某些操作的其它元素。
        // createRange 从当前文本选中区中创建 TextRange 对象，
        // 或从控件选中区中创建 controlRange 集合。
        var sTextRange = document.selection.createRange();
        // 判断选中的是不是textarea对象
        if (sTextRange.parentElement() === oTextarea) {
          // 创建一个TextRange对象
          var oTextRange = document.body.createTextRange();
          // 移动文本范围以便范围的开始和结束位置能够完全包含给定元素的文本。
          oTextRange.moveToElementText(oTextarea);
          // 这里我们比较oTextRange和sTextRange的开头，的到选中区域的开头位置
          for (start = 0; oTextRange.compareEndPoints('StartToStart', sTextRange) < 0; start++) {
            oTextRange.moveStart('character', 1);
          }
          // 需要计算一下\n的数目(按字符移动的方式不计\n,所以这里加上)
          for (var i = 0; i <= start; i++) {
            if (oTextarea.value.charAt(i) === '\n') {
              start++;
            }
          }
          // 再计算一次结束的位置
          oTextRange.moveToElementText(oTextarea);
          for (end = 0; oTextRange.compareEndPoints('StartToEnd', sTextRange) < 0; end++) {
            oTextRange.moveStart('character', 1);
          }
          for (var j = 0; j <= end; j++) {
            if (oTextarea.value.charAt(j) === '\n') {
              end++;
            }
          }
        }
      } else {
        start = oTextarea.selectionStart;
        end = oTextarea.selectionEnd;
      }
      _this.setState({
        startNum: start,
        endNum: end
      });
    });
    /**
     * 跳转到上一次光标的位置
     * @参考 http://blog.csdn.net/chadcao/article/details/6575927
     * @TODO IE、火狐浏览器下未验证
     */
    _defineProperty(_assertThisInitialized(_this), "moveToCursor", function () {
      var _this$state2 = _this.state,
        startNum = _this$state2.startNum,
        endNum = _this$state2.endNum;
      var oTextarea = _this.content.querySelector('textarea');
      var start = startNum;
      var end = endNum;
      if (isNaN(start) || isNaN(end)) {
        alert('位置输入错误');
      }
      if (isIE) {
        var oTextRange = oTextarea.createTextRange();
        var LStart = startNum;
        var LEnd = endNum;
        var _start = 0;
        var _end = 0;
        var value = oTextarea.value;
        for (var i = 0; i < value.length && i < LStart; i++) {
          var c = value.charAt(i);
          if (c !== '\n') {
            _start++;
          }
        }
        for (var j = value.length - 1; j >= LEnd && j >= 0; j--) {
          var _c = value.charAt(j);
          if (_c !== '\n') {
            _end++;
          }
        }
        oTextRange.moveStart('character', _start);
        oTextRange.moveEnd('character', -_end);
        // oTextRange.collapse(true);
        oTextRange.select();
        oTextarea.focus();
      } else {
        oTextarea.select();
        oTextarea.selectionStart = startNum;
        oTextarea.selectionEnd = endNum;
      }
    });
    var _value = props.value || '';
    _this.state = {
      currentContent: _value,
      startNum: _value.length,
      // 光标开始位置(当选中文本时)
      endNum: _value.length,
      // 光标结束位置(当选中文本时)
      wordCount: _value.length // 输入框内的字符数总和（包含占位符所需要的长度）
    };
    _this.content = /*#__PURE__*/_react.default.createRef();
    return _this;
  }
  _createClass(VarTemplate, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      var _this$props = this.props,
        size = _this$props.size,
        style = _this$props.style,
        tags = _this$props.tags,
        disabled = _this$props.disabled,
        fieldStatus = _this$props.fieldStatus,
        _this$props$tagsOptio = _this$props.tagsOptionName,
        tagsOptionName = _this$props$tagsOptio === void 0 ? {
          key: 'key',
          label: 'label',
          value: 'value'
        } : _this$props$tagsOptio,
        showCountTip = _this$props.showCountTip;
      var _this$state3 = this.state,
        currentContent = _this$state3.currentContent,
        wordCount = _this$state3.wordCount;
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "spec-vart-wrap",
        style: style,
        ref: function ref(cRef) {
          _this2.content = cRef;
        }
      }, tags && Array.isArray(tags) && /*#__PURE__*/_react.default.createElement("div", {
        className: "spec-vart-header"
      }, tags.map(function (item) {
        return /*#__PURE__*/_react.default.createElement(_antd.Tag, {
          style: {
            marginBottom: '4px',
            cursor: 'pointer'
          },
          key: item[tagsOptionName === null || tagsOptionName === void 0 ? void 0 : tagsOptionName.key],
          onClick: function onClick() {
            return !(disabled || fieldStatus === 'disabled') && _this2.setTagWords(item[tagsOptionName === null || tagsOptionName === void 0 ? void 0 : tagsOptionName.value]);
          }
        }, item[tagsOptionName === null || tagsOptionName === void 0 ? void 0 : tagsOptionName.label]);
      })), /*#__PURE__*/_react.default.createElement("div", {
        className: "spec-vart-input"
      }, /*#__PURE__*/_react.default.createElement(TextArea, {
        type: "text",
        size: size,
        value: currentContent,
        placeholder: "\u8BF7\u8F93\u5165",
        onFocus: this.handleFocus,
        onBlur: this.handleBlur,
        onChange: function onChange(e) {
          return _this2.handleInputChange(e);
        },
        disabled: disabled || fieldStatus === 'disabled'
      })), showCountTip && /*#__PURE__*/_react.default.createElement("div", {
        className: "spec-vart-desc",
        style: {
          marginTop: '4px',
          fontSize: '12px'
        }
      }, " \u60A8\u5DF2\u5F55\u5165 ", /*#__PURE__*/_react.default.createElement("b", null, wordCount), " \u4E2A\u5B57"));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps) {
      // console.log('执行getDerivedStateFromProps', nextProps)
      // Should be a controlled component.
      // 如果 props 中的value属性发生变化，返回一个新的子状态对象
      if ('value' in nextProps) {
        // console.log('nextProps', nextProps, nextProps.value || {})
        var nValue = nextProps.value || '';
        return _objectSpread({
          value: nValue,
          currentContent: nValue,
          startNum: nValue.length,
          // 光标开始位置(当选中文本时)
          endNum: nValue.length,
          // 光标结束位置(当选中文本时)
          wordCount: nValue.length
        }, nextProps.value || {});
      }
      // 如果props没有变化，返回null或undefined ,不触发任何状态更新
      return null;
    }
  }]);
  return VarTemplate;
}(_react.Component);
var _default = exports.default = VarTemplate;