function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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(r) { if (Array.isArray(r)) return r; }
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,
    _ref$readOnly = _ref.readOnly,
    readOnly = _ref$readOnly === void 0 ? true : _ref$readOnly,
    defaultMode = _ref.defaultMode,
    columnExtra = _ref.columnExtra,
    rowClassName = _ref.rowClassName,
    labelRender = _ref.labelRender,
    onChange = _ref.onChange,
    _ref$defaultExpandDee = _ref.defaultExpandDeep,
    defaultExpandDeep = _ref$defaultExpandDee === void 0 ? 3 : _ref$defaultExpandDee,
    _ref$defaultExpandLen = _ref.defaultExpandLength,
    defaultExpandLength = _ref$defaultExpandLen === void 0 ? 10 : _ref$defaultExpandLen;
  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)))));
};
export default JsonEditor;