function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import './styles/jsonEditor.less';
import { IconFont } from '@zgfe/business-lib';
import Row from './row';
import { Input } from 'antd';
import jsonUtil from './util';
export var classPrefix = 'json-editor';
export var JsonEditorContext = /*#__PURE__*/React.createContext({
  expandList: [],
  setExpandList: function setExpandList() {}
});
/**
 * 将传进来的json进行格式化展示，并且支持编辑
 */
var JsonEditor = function JsonEditor(_ref) {
  var value = _ref.value,
    readOnly = _ref.readOnly,
    defaultMode = _ref.defaultMode,
    columnExtra = _ref.columnExtra,
    rowClassName = _ref.rowClassName,
    labelRender = _ref.labelRender,
    onChange = _ref.onChange,
    defaultExpandDeep = _ref.defaultExpandDeep,
    defaultExpandLength = _ref.defaultExpandLength;
  var _React$useState = React.useState([]),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    expandList = _React$useState2[0],
    setExpandList = _React$useState2[1];
  var _useState = useState(readOnly ? 'view' : defaultMode || 'edit'),
    _useState2 = _slicedToArray(_useState, 2),
    mode = _useState2[0],
    setMode = _useState2[1];
  var _useState3 = useState(value || ''),
    _useState4 = _slicedToArray(_useState3, 2),
    json = _useState4[0],
    setJson = _useState4[1];
  var _useState5 = useState(''),
    _useState6 = _slicedToArray(_useState5, 2),
    errorMsg = _useState6[0],
    setErrorMsg = _useState6[1];
  useEffect(function () {
    var list = [];
    try {
      jsonUtil.iterateObject(JSON.parse(json), function (path, value, deep, index) {
        if (deep < defaultExpandDeep && (!index || index < defaultExpandLength)) {
          list.push(path);
        }
      });
    } catch (e) {
      // do nothing
    }
    setExpandList(list);
  }, []);
  function onSwitchMode() {
    if (mode === 'view') {
      setJson(function (val) {
        try {
          return JSON.stringify(JSON.parse(val), null, 2);
        } catch (e) {
          return val;
        }
      });
    }
    setMode(mode === 'edit' ? 'view' : 'edit');
  }
  function onChangeText(e) {
    e.persist();
    setJson(e.target.value);
    try {
      if (!e.target.value) {
        onChange && onChange(e.target.value);
        return;
      }
      JSON.parse(e.target.value);
      setErrorMsg('');
      onChange && onChange(e.target.value);
    } catch (e) {
      setErrorMsg(e.message);
    }
  }
  /**
   *
   * @param obj 要转换的对象
   * @param space 缩进空格数
   * @returns
   */
  function objectToDom(obj, label, deep, inArray, parentPath) {
    var currentDeep = deep || 0;
    var expanded = !parentPath || expandList.includes(parentPath);
    if (_.isArray(obj)) {
      var nodeList = obj.map(function (item, index) {
        var path = parentPath ? "".concat(parentPath, "[").concat(index, "]") : "[".concat(index, "]");
        return objectToDom(item, "".concat(index), currentDeep + 1, true, path);
      });
      return [/*#__PURE__*/React.createElement(Row, {
        label: label,
        isArrStart: true,
        isExpanded: expanded,
        deep: currentDeep,
        key: "".concat(deep, "-arrStart"),
        path: parentPath
      })].concat(_toConsumableArray(expanded ? nodeList : [/*#__PURE__*/React.createElement(Row, {
        isExpanded: false,
        key: "".concat(deep, "-obj-inner"),
        deep: currentDeep + 1,
        path: parentPath
      })]), [/*#__PURE__*/React.createElement(Row, {
        isArrEnd: true,
        deep: currentDeep,
        key: "".concat(deep, "-arrEnd"),
        path: parentPath
      })]);
    } else if (_.isObject(obj)) {
      var keys = Object.keys(obj);
      var _nodeList = keys.map(function (key) {
        var path = parentPath ? "".concat(parentPath, ".").concat(key) : key;
        return objectToDom(obj[key], key, currentDeep + 1, false, path);
      });
      return [/*#__PURE__*/React.createElement(Row, {
        label: label,
        isObjectStart: true,
        deep: currentDeep,
        key: "".concat(deep, "-objStart"),
        inArray: inArray,
        path: parentPath,
        isExpanded: expanded
      })].concat(_toConsumableArray(expanded ? _nodeList : [/*#__PURE__*/React.createElement(Row, {
        isExpanded: false,
        key: "".concat(deep, "-obj-inner"),
        deep: currentDeep + 1,
        path: parentPath
      })]), [/*#__PURE__*/React.createElement(Row, {
        isObjectEnd: true,
        deep: currentDeep,
        key: "".concat(deep, "-objEnd"),
        inArray: inArray,
        path: parentPath
      })]);
    } else {
      // 基本类型
      return /*#__PURE__*/React.createElement(Row, {
        label: label,
        value: obj,
        deep: currentDeep,
        inArray: inArray,
        path: parentPath,
        key: "".concat(label, "-").concat(deep)
      });
    }
  }
  function jsonToDom(json) {
    if (!json) {
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
        className: "".concat(classPrefix, "-empty")
      }, "\u6682\u65E0\u6570\u636E"), /*#__PURE__*/React.createElement("div", {
        className: "".concat(classPrefix, "-error")
      }, "\u8BF7\u8F93\u5165json\u683C\u5F0F\u7684\u8BF7\u6C42\u4F53"));
    }
    var jsonObj;
    try {
      jsonObj = JSON.parse(json);
    } catch (e) {
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(classPrefix, "-error")
      }, "JSON\u683C\u5F0F\u9519\u8BEF: ", e.message);
    }
    return objectToDom(jsonObj);
  }
  return /*#__PURE__*/React.createElement(JsonEditorContext.Provider, {
    value: {
      expandList: expandList,
      setExpandList: setExpandList,
      columnExtra: columnExtra,
      rowClassName: rowClassName,
      labelRender: labelRender
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: classPrefix
  }, !readOnly && /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-mode"),
    onClick: onSwitchMode
  }, /*#__PURE__*/React.createElement(IconFont, {
    type: mode === 'view' ? 'bianji' : 'a-yanjingkai'
  }), ' ', mode === 'view' ? '编辑' : '预览'), mode === 'view' ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-main")
  }, jsonToDom(json)) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Input.TextArea, {
    placeholder: "\u8BF7\u8F93\u5165json\u683C\u5F0F\u7684\u8BF7\u6C42\u4F53",
    className: "".concat(classPrefix, "-textarea"),
    rows: 10,
    value: json,
    onChange: onChangeText
  }), errorMsg && /*#__PURE__*/React.createElement("div", {
    className: "".concat(classPrefix, "-error")
  }, errorMsg))));
};
JsonEditor.defaultProps = {
  readOnly: true,
  defaultExpandDeep: 3,
  defaultExpandLength: 10
};
export default JsonEditor;