"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
var _useLanguage = require("../../hooks/use-language");
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 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 _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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /**
 * Created by S.C. on 2024/10/10
 */
var TextArea = _antd.Input.TextArea;
var isIE = !!document.all;
var VarTemplate = function VarTemplate(props) {
  var value = props.value,
    size = props.size,
    style = props.style,
    tags = props.tags,
    disabled = props.disabled,
    fieldStatus = props.fieldStatus,
    _props$tagsOptionName = props.tagsOptionName,
    tagsOptionName = _props$tagsOptionName === void 0 ? {
      key: 'key',
      label: 'label',
      value: 'value'
    } : _props$tagsOptionName,
    showCountTip = props.showCountTip,
    onChange = props.onChange,
    maxLength = props.maxLength,
    _props$readOnly = props.readOnly,
    readOnly = _props$readOnly === void 0 ? false : _props$readOnly;
  var lang = (0, _useLanguage.useLanguageObject)(); // 当前使用的语言包
  var contentRef = (0, _react.useRef)();
  var _useState = (0, _react.useState)({
      currentContent: '',
      startNum: 0,
      endNum: 0,
      wordCount: 0
    }),
    _useState2 = _slicedToArray(_useState, 2),
    vartData = _useState2[0],
    setVartData = _useState2[1];
  var handleBlur = function handleBlur() {
    getCurrentCursor();
  };
  var handleFocus = function handleFocus() {
    // console.log('获取焦点', event)
  };
  var handleInputChange = function handleInputChange(e) {
    var eValue = e === null || e === void 0 ? void 0 : e.target.value;
    getCurrentCursor();
    setVartData({
      currentContent: eValue,
      startNum: eValue.length,
      endNum: eValue.length,
      wordCount: eValue.length
    });
    if (onChange) onChange(eValue);
  };
  var setTagWords = (0, _react.useCallback)(function (key) {
    var currentContent = vartData.currentContent,
      startNum = vartData.startNum,
      endNum = vartData.endNum;
    var insert = insertContent(currentContent, key, startNum, endNum);
    var newContent = insert.length > maxLength ? insert.substring(0, maxLength) : insert;
    // if (newContent.length > maxLength) {
    //   console.log('字数超出了', newContent, newContent.substring(0, maxLength))
    // }
    // 数字超出需要截取
    setVartData({
      currentContent: newContent,
      startNum: startNum + key.length,
      // 光标起始位置累加
      endNum: endNum + key.length,
      // 光标起始位置累加
      wordCount: newContent.length
    });
    if (onChange) onChange(newContent);
    setTimeout(function () {
      moveToCursor(key.length); // 重新定位光标
    });
  }, [vartData, maxLength]);

  /**
   * 指定位置插入标签占位符字符串，当光标有选中一段字符时，会将直接将其替换
   * @param {str}       需要做插入的字符串
   * @param {insertStr} 需要插入的字符串
   * @param {start}     指定开始位置
   * @param {end}       指定结束位置
   * */
  var insertContent = function insertContent(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、火狐浏览器下未验证
   */
  var getCurrentCursor = (0, _react.useCallback)(function () {
    var _contentRef$current;
    var start = 0;
    var end = 0;
    var oTextarea = contentRef === null || contentRef === void 0 || (_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 ? void 0 : _contentRef$current.querySelector('textarea'); // 获取textarea标签
    if (isIE) {
      // selection 当前激活选中区，即高亮文本块，和/或文当中用户可执行某些操作的其它元素。
      // createRange 从当前文本选中区中创建 TextRange 对象，
      // 或从控件选中区中创建 controlRange 集合。
      // @ts-ignore
      var sTextRange = document.selection.createRange();
      // 判断选中的是不是textarea对象
      if (sTextRange.parentElement() === oTextarea) {
        // 创建一个TextRange对象
        // @ts-ignore
        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;
    }
    setVartData(_objectSpread(_objectSpread({}, vartData), {}, {
      startNum: start,
      endNum: end
    }));
  }, [vartData, value]);

  /**
   * 跳转到上一次光标的位置
   * @参考 http://blog.csdn.net/chadcao/article/details/6575927
   * @TODO IE、火狐浏览器下未验证
   * @{params} {number} appendLength 当前切换的长度
   */
  var moveToCursor = (0, _react.useCallback)(function (insertLength) {
    var _contentRef$current2;
    var startNum = vartData.startNum,
      endNum = vartData.endNum;
    var oTextarea = contentRef === null || contentRef === void 0 || (_contentRef$current2 = contentRef.current) === null || _contentRef$current2 === void 0 ? void 0 : _contentRef$current2.querySelector('textarea');
    var start = startNum;
    var end = endNum;
    if (isNaN(start) || isNaN(end)) {
      console.error('位置输入错误');
    }
    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.focus();
      //  判断如果是原来已经有选中(文本高亮），则插入文本后高亮的位置需要变成当前插入的文本
      // startNum === endNum表示未选中过
      // let aStartNum = startNum === endNum ? startNum + insertLength : startNum
      // let aEndNum = startNum === endNum ? endNum + insertLength : startNum + insertLength
      oTextarea.selectionStart = startNum + insertLength; // aStartNum
      oTextarea.selectionEnd = startNum + insertLength; // aEndNum
      // if (oTextarea.setSelectionRange) {
      //   setTimeout(() => {
      //     oTextarea.focus();
      //     oTextarea.setSelectionRange(aStartNum, aEndNum);
      //   }, 0);
      // } else {
      //   oTextarea.selectionStart = aStartNum
      //   oTextarea.selectionEnd = aEndNum
      // }
    }
  }, [vartData]);
  (0, _react.useEffect)(function () {
    setVartData({
      currentContent: value || '',
      startNum: (value === null || value === void 0 ? void 0 : value.length) || 0,
      // 光标开始位置(当选中文本时)
      endNum: (value === null || value === void 0 ? void 0 : value.length) || 0,
      // 光标结束位置(当选中文本时)
      wordCount: (value === null || value === void 0 ? void 0 : value.length) || 0 // 输入框内的字符数总和（包含占位符所需要的长度）
    });
  }, [value]);
  // const setCursorPosition = (elemId, index) =>{
  //   const elem = document.getElementById(elemId);
  //   if (elem.setSelectionRange) {
  //     setTimeout(function() {
  //       elem.focus();
  //       elem.setSelectionRange(index, index);
  //     }, 0);
  //   } else if (elem.createTextRange) {
  //     const range = elem.createTextRange();
  //     range.collapse(true);
  //     range.moveEnd('character', index);
  //     range.moveStart('character', index);
  //     range.select();
  //   }
  // }
  return /*#__PURE__*/_react.default.createElement("div", {
    className: "spec-vart-wrap",
    style: style,
    ref: contentRef
  }, 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) || 'key'],
      onClick: function onClick() {
        return !(disabled || fieldStatus === 'disabled' || readOnly || fieldStatus === 'viewOnly') && setTagWords(item[(tagsOptionName === null || tagsOptionName === void 0 ? void 0 : tagsOptionName.value) || 'value']);
      }
    }, item[(tagsOptionName === null || tagsOptionName === void 0 ? void 0 : tagsOptionName.label) || 'label']);
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "spec-vart-input"
  }, /*#__PURE__*/_react.default.createElement(TextArea
  // type="text"
  , {
    size: size,
    value: vartData.currentContent,
    placeholder: (lang === null || lang === void 0 ? void 0 : lang['field.input.placeholder']) || "请输入",
    onFocus: handleFocus,
    onBlur: handleBlur,
    onChange: function onChange(e) {
      return handleInputChange(e);
    },
    disabled: disabled || fieldStatus === 'disabled',
    maxLength: maxLength,
    readOnly: readOnly || fieldStatus === 'viewOnly'
  })), showCountTip && /*#__PURE__*/_react.default.createElement("div", {
    className: "spec-vart-desc",
    style: {
      marginTop: '4px',
      fontSize: '12px'
    }
  }, (lang === null || lang === void 0 ? void 0 : lang['filed.varTemplate.enter']) || '您已录入', " ", /*#__PURE__*/_react.default.createElement("b", null, vartData.wordCount, maxLength ? "/".concat(maxLength) : ''), " ", (lang === null || lang === void 0 ? void 0 : lang['filed.varTemplate.words']) || '个字'));
};
var _default = exports.default = VarTemplate;