import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/Table";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/lib/input/style";
import _Input from "choerodon-ui/lib/input";
import "choerodon-ui/lib/form/style";
import _Form from "choerodon-ui/lib/form";
import "choerodon-ui/lib/modal/style";
import _Modal from "choerodon-ui/lib/modal";

var _dec, _dec2, _class, _class2, _temp;

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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 _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 _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 _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 _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, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); 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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || 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; } 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 : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/* eslint-disable */
import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import { injectIntl, FormattedMessage } from 'react-intl';
import _ from 'lodash';
import { Choerodon } from '@choerodon/boot';
import { EditableCell, EditableFormRow } from "./editableTable";
import { objToYaml, yamlToObj, takeObject, ConfigNode, makePostData } from "../utils";
import YamlEditor from "../../../../../../../components/yamlEditor";
import { handlePromptError } from "../../../../../../../utils";
import "../../../../../../main.less";
import "./index.less";
var Sidebar = _Modal.Sidebar;
var FormItem = _Form.Item;
var TextArea = _Input.TextArea;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var FormView = (_dec = _Form.create({}), _dec2 = inject('AppState'), _dec(_class = injectIntl(_class = _dec2(_class = observer(_class = (_temp = _class2 = /*#__PURE__*/function (_Component) {
  _inherits(FormView, _Component);

  var _super = _createSuper(FormView);

  function FormView() {
    var _this;

    _classCallCheck(this, FormView);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      // 键值对格式
      dataSource: [new ConfigNode()],
      // yaml 格式
      dataYaml: '',
      counter: 1,
      submitting: false,
      hasItemError: false,
      warningMes: '',
      data: false,
      isYamlEdit: false,
      hasYamlError: false,
      // yaml格式的value只能是字符串或null
      hasValueError: false,
      valueErrorMsg: ''
    };
    _this.checkName = _.debounce(function (rule, value, callback) {
      var _this$props = _this.props,
          formatMessage = _this$props.intl.formatMessage,
          projectId = _this$props.AppState.currentMenuType.projectId,
          envId = _this$props.envId,
          store = _this$props.store;
      var pattern = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

      if (value && !pattern.test(value)) {
        callback(formatMessage({
          id: 'network.name.check.failed'
        }));
      } else if (value && pattern.test(value)) {
        store.checkName(projectId, envId, value).then(function (res) {
          if (handlePromptError(res, false)) {
            callback();
          } else {
            callback(formatMessage({
              id: 'checkNameExist'
            }));
          }
        })["catch"](function (error) {
          callback(formatMessage({
            id: 'checkNameFailed'
          }));
        });
      } else {
        callback();
      }
    }, 1000);

    _this.handleDelete = function (key) {
      var dataSource = _toConsumableArray(_this.state.dataSource).filter(function (item) {
        return item.index !== key;
      });

      _this.asyncCheckErrorData(dataSource);

      _this.setState({
        dataSource: dataSource
      });
    };

    _this.handleAdd = function (data) {
      var _this$state = _this.state,
          counter = _this$state.counter,
          dataSource = _this$state.dataSource;
      var _data = data;

      if (!Array.isArray(data)) {
        _data = [[null, null]];
      }

      var _counter = counter;

      var newData = _.map(_data, function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
            key = _ref2[0],
            value = _ref2[1];

        return new ConfigNode(key, value, ++_counter);
      });

      if (!newData.length) {
        var initConfig = new ConfigNode();
        newData.push(initConfig);
      }

      var uniqData = _.uniqBy([].concat(_toConsumableArray(dataSource.filter(function (item) {
        return item.index !== '';
      })), _toConsumableArray(newData)), 'index');

      _this.setState({
        dataSource: uniqData,
        counter: _counter
      });
    };

    _this.handleSave = function (row) {
      var newData = _toConsumableArray(_this.state.dataSource);

      var index = _.findIndex(newData, ['index', row.index]);

      newData.splice(index, 1, _objectSpread(_objectSpread({}, newData[index]), row));

      _this.checkErrorData(newData);

      _this.setState({
        dataSource: newData
      });
    };

    _this.checkConfigRuleError = function () {
      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      var yaml = data || _this.state.dataYaml;
      var yamlObj = yamlToObj(yaml) || {};
      var values = Object.values(yamlObj);
      var error = false;

      for (var i = 0, len = values.length; i < len; i++) {
        if (typeof values[i] !== 'string' || values[i] === '') {
          error = true;
          break;
        }
      }

      _this.setState({
        hasValueError: error
      }, function () {
        return _this.checkButtonDisabled;
      });

      return error;
    };

    _this.asyncCheckConfigRuleError = _.debounce(_this.checkConfigRuleError, 600);

    _this.checkErrorData = function () {
      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var isSubmit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var _this$props2 = _this.props,
          title = _this$props2.title,
          formatMessage = _this$props2.intl.formatMessage,
          modal = _this$props2.modal;

      var _data = data || _this.state.dataSource;

      var hasKey = _data.filter(function (_ref3) {
        var key = _ref3.key;
        return !_.isEmpty(key);
      });

      var onlyHasValue = _data.filter(function (_ref4) {
        var key = _ref4.key,
            value = _ref4.value;
        return _.isEmpty(key) && !_.isEmpty(value);
      });

      var onlyHasKey = hasKey.filter(function (_ref5) {
        var value = _ref5.value;
        return _.isEmpty(value);
      });
      var hasErrorItem = onlyHasKey.length || onlyHasValue.length;

      var hasRepeatKey = hasKey.length !== _.uniqBy(hasKey, 'key').length;

      var hasEmptyKey = title === 'cipher' && (_.isEmpty(hasKey) || hasKey.length !== _data.length);

      var hasErrorKey;

      var _iterator = _createForOfIteratorHelper(hasKey),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var key = _step.value.key;
          var pattern = /[^0-9A-Za-z\.\-\_]/;

          if (pattern.test(key)) {
            hasErrorKey = true;
            break;
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      if (!(hasErrorItem || hasErrorKey || hasRepeatKey || hasEmptyKey)) {
        _this.setState({
          warningMes: '',
          hasItemError: false
        }, function () {
          return _this.checkButtonDisabled(isSubmit);
        });

        return false;
      }

      var errorMsg = formatMessage({
        id: hasRepeatKey ? 'configMap.keyRepeat' : "".concat(title, ".keyValueSpan")
      });

      _this.setConfigError(errorMsg);

      return true;
    };

    _this.asyncCheckErrorData = _.debounce(_this.checkErrorData, 500);

    _this.formValidate = function () {
      var _this$props3 = _this.props,
          id = _this$props3.id,
          envId = _this$props3.envId,
          appId = _this$props3.appId,
          validateFields = _this$props3.form.validateFields;
      var _this$state2 = _this.state,
          dataSource = _this$state2.dataSource,
          isYamlEdit = _this$state2.isYamlEdit,
          hasYamlError = _this$state2.hasYamlError,
          dataYaml = _this$state2.dataYaml;
      var configData = [];
      var hasKVError = false;
      var hasConfigRuleError = false;
      return new Promise(function (resolve) {
        validateFields(function (err, _ref6) {
          var name = _ref6.name,
              description = _ref6.description;

          if (!isYamlEdit) {
            hasKVError = _this.checkErrorData(null, true);

            var allData = _toConsumableArray(dataSource.filter(function (item) {
              return !_.isEmpty(item.key);
            }));

            configData = _.uniqBy(allData, 'index');
          } else {
            hasConfigRuleError = _this.checkConfigRuleError();
            configData = yamlToObj(dataYaml);
          }

          if (hasYamlError || hasKVError || hasConfigRuleError) {
            resolve(false);
          } else {
            _this.setState({
              submitting: true,
              hasItemError: false
            });

            if (!err) {
              var _value = takeObject(configData);

              var dto = {
                name: name,
                description: description,
                envId: envId,
                appServiceId: appId,
                type: id ? 'update' : 'create',
                id: id || undefined,
                value: _value
              };
              resolve(dto);
            }

            resolve(false);
          }
        });
      });
    };

    _this.handleSubmit = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _this$props4, store, projectId, refresh, postData, res;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _this$props4 = _this.props, store = _this$props4.store, projectId = _this$props4.AppState.currentMenuType.id, refresh = _this$props4.refresh;
              _context.next = 3;
              return _this.formValidate();

            case 3:
              postData = _context.sent;

              if (postData) {
                _context.next = 6;
                break;
              }

              return _context.abrupt("return", false);

            case 6:
              _context.prev = 6;
              _context.next = 9;
              return store.postKV(projectId, postData);

            case 9:
              res = _context.sent;

              if (!handlePromptError(res)) {
                _context.next = 14;
                break;
              }

              refresh();
              _context.next = 15;
              break;

            case 14:
              return _context.abrupt("return", false);

            case 15:
              _context.next = 21;
              break;

            case 17:
              _context.prev = 17;
              _context.t0 = _context["catch"](6);
              Choerodon.handleResponseError(_context.t0);
              return _context.abrupt("return", false);

            case 21:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[6, 17]]);
    }));

    _this.getFormContent = function () {
      var _this$props5 = _this.props,
          formatMessage = _this$props5.intl.formatMessage,
          getFieldDecorator = _this$props5.form.getFieldDecorator,
          id = _this$props5.id,
          title = _this$props5.title;
      var data = _this.state.data;
      return /*#__PURE__*/React.createElement(_Form, {
        className: "c7n-sidebar-form",
        layout: "vertical"
      }, /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('name', {
        initialValue: data ? data.name : null,
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }, {
          validator: id ? null : _this.checkName
        }]
      })( /*#__PURE__*/React.createElement(_Input, {
        autoFocus: !id,
        disabled: !!id,
        maxLength: 100,
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "app.name"
        })
      }))), /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('description', {
        initialValue: data ? data.description : null
      })( /*#__PURE__*/React.createElement(TextArea, {
        autoFocus: !!id,
        autosize: {
          minRows: 2
        },
        maxLength: 30,
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "configMap.des"
        })
      }))));
    };

    _this.getConfigMap = function () {
      var _this$props6 = _this.props,
          title = _this$props6.title,
          intlPrefix = _this$props6.intlPrefix;
      var _this$state3 = _this.state,
          dataSource = _this$state3.dataSource,
          isYamlEdit = _this$state3.isYamlEdit,
          hasItemError = _this$state3.hasItemError,
          warningMes = _this$state3.warningMes,
          dataYaml = _this$state3.dataYaml,
          hasValueError = _this$state3.hasValueError,
          valueErrorMsg = _this$state3.valueErrorMsg;
      var configMap = null;

      if (!isYamlEdit) {
        var components = {
          body: {
            row: EditableFormRow,
            cell: EditableCell
          }
        };
        var baseColumns = [{
          title: 'key',
          dataIndex: 'key',
          width: '25%',
          editable: true
        }, {
          title: '',
          width: '5%',
          className: 'icon-equal',
          align: 'center',
          dataIndex: 'temp'
        }, {
          title: title,
          width: '100%',
          dataIndex: 'value',
          editable: true
        }, {
          title: '',
          dataIndex: 'operation',
          render: function render(text, _ref8) {
            var index = _ref8.index;
            return dataSource.length >= 1 ? /*#__PURE__*/React.createElement(_Icon, {
              className: "del-btn",
              type: "delete",
              onClick: _this.handleDelete.bind(_assertThisInitialized(_this), index)
            }) : null;
          }
        }];
        var columns = baseColumns.map(function (col) {
          if (!col.editable) return col;
          return _objectSpread(_objectSpread({}, col), {}, {
            onCell: function onCell(record) {
              return {
                record: record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                save: _this.handleSave,
                add: _this.handleAdd
              };
            }
          });
        });
        configMap = /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(_Table, {
          filterBar: false,
          showHeader: false,
          pagination: false,
          components: components,
          className: "c7n-editable-table",
          dataSource: dataSource,
          columns: columns,
          rowKey: function rowKey(record) {
            return record.index;
          }
        }), /*#__PURE__*/React.createElement(_Button, {
          icon: "add",
          onClick: _this.handleAdd,
          type: "primary"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".").concat(title, ".add")
        })), hasItemError ? /*#__PURE__*/React.createElement("div", {
          className: "c7n-cm-warning"
        }, warningMes) : null);
      } else {
        configMap = /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(YamlEditor, {
          readOnly: false,
          modeChange: false,
          value: dataYaml,
          onValueChange: _this.changeYamlValue,
          handleEnableNext: _this.checkYamlError
        }), /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-config-yaml-tip"
        }, hasValueError && (valueErrorMsg || /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "configMap.yaml.error"
        }))));
      }

      return configMap;
    };

    _this.changeYamlValue = function (value) {
      _this.asyncCheckConfigRuleError(value);

      _this.setState({
        dataYaml: value
      });
    };

    _this.checkYamlError = function (flag) {
      _this.setState({
        hasYamlError: flag
      }, function () {
        return _this.checkButtonDisabled();
      });
    };

    _this.changeEditMode = function () {
      var _this$state4 = _this.state,
          dataSource = _this$state4.dataSource,
          dataYaml = _this$state4.dataYaml,
          hasYamlError = _this$state4.hasYamlError,
          isYamlEdit = _this$state4.isYamlEdit,
          hasValueError = _this$state4.hasValueError,
          hasItemError = _this$state4.hasItemError;
      var modal = _this.props.modal;
      if (hasYamlError || hasValueError || hasItemError) return;

      if (!isYamlEdit) {
        var result = _this.checkErrorData(dataSource);

        if (result) return;
        var yamlValue = objToYaml(dataSource);

        _this.checkConfigRuleError(yamlValue);

        _this.setState({
          counter: 1,
          hasItemError: false,
          isYamlEdit: true,
          warningMes: '',
          dataSource: [],
          dataYaml: yamlValue
        }, function () {
          return _this.checkButtonDisabled();
        });
      } else {
        var _result = _this.checkConfigRuleError(dataYaml);

        if (_result) return;

        try {
          var kvValue = yamlToObj(dataYaml);
          var postData = makePostData(kvValue);
          var counter = postData.length;

          _this.setState({
            dataSource: postData,
            hasYamlError: false,
            isYamlEdit: false,
            dataYaml: '',
            counter: counter
          }, function () {
            return _this.checkButtonDisabled();
          });
        } catch (e) {
          _this.setState({
            hasValueError: true,
            valueErrorMsg: e.message
          });

          modal.update({
            okProps: {
              disabled: true
            }
          });
        }
      }
    };

    _this.checkButtonDisabled = function () {
      var isSubmit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var modal = _this.props.modal;
      var _this$state5 = _this.state,
          hasYamlError = _this$state5.hasYamlError,
          hasValueError = _this$state5.hasValueError,
          hasItemError = _this$state5.hasItemError;
      !isSubmit && modal.update({
        okProps: {
          disabled: hasYamlError || hasValueError || hasItemError
        }
      });
    };

    return _this;
  }

  _createClass(FormView, [{
    key: "componentDidMount",
    value: function () {
      var _componentDidMount = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var _this$props7, id, store, projectId, modal, res, counter, dataSource;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$props7 = this.props, id = _this$props7.id, store = _this$props7.store, projectId = _this$props7.AppState.currentMenuType.projectId, modal = _this$props7.modal;

                if (!id) {
                  _context2.next = 12;
                  break;
                }

                _context2.prev = 2;
                _context2.next = 5;
                return store.loadSingleData(projectId, id);

              case 5:
                res = _context2.sent;

                if (handlePromptError(res)) {
                  counter = 1;

                  if (!_.isEmpty(res.value)) {
                    dataSource = _.map(res.value, function (value, key) {
                      return new ConfigNode(key, value, counter++);
                    });
                    this.setState({
                      dataSource: dataSource,
                      counter: counter
                    });
                  }

                  this.setState({
                    data: res
                  });
                }

                _context2.next = 12;
                break;

              case 9:
                _context2.prev = 9;
                _context2.t0 = _context2["catch"](2);
                Choerodon.handleResponseError(_context2.t0);

              case 12:
                modal.handleOk(this.handleSubmit);

              case 13:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[2, 9]]);
      }));

      function componentDidMount() {
        return _componentDidMount.apply(this, arguments);
      }

      return componentDidMount;
    }()
    /**
     * 删除key-value
     * @param key
     */

  }, {
    key: "setConfigError",
    value:
    /**
     * 设置键值对模式下的错误提示
     * @param msg
     */
    function setConfigError(msg) {
      var modal = this.props.modal;
      this.setState({
        warningMes: msg,
        hasItemError: true
      });
      modal.update({
        okProps: {
          disabled: true
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props8 = this.props,
          formatMessage = _this$props8.intl.formatMessage,
          visible = _this$props8.visible,
          id = _this$props8.id,
          title = _this$props8.title,
          modeSwitch = _this$props8.modeSwitch,
          menuName = _this$props8.AppState.currentMenuType.name,
          intlPrefix = _this$props8.intlPrefix;
      var _this$state6 = this.state,
          submitting = _this$state6.submitting,
          data = _this$state6.data,
          hasYamlError = _this$state6.hasYamlError,
          isYamlEdit = _this$state6.isYamlEdit,
          hasValueError = _this$state6.hasValueError,
          hasItemError = _this$state6.hasItemError;
      var titleName = id ? data.name : menuName;
      var titleCode = "".concat(intlPrefix, ".").concat(title, ".").concat(id ? 'edit' : 'create');
      var disableBtn = hasYamlError || hasValueError || hasItemError;
      return /*#__PURE__*/React.createElement("div", {
        className: "c7n-region"
      }, /*#__PURE__*/React.createElement("div", null, this.getFormContent(), /*#__PURE__*/React.createElement("div", {
        className: "c7n-sidebar-from-title"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".").concat(title, ".head")
      }), !isYamlEdit && /*#__PURE__*/React.createElement(_Tooltip, {
        overlayStyle: {
          maxWidth: 350
        },
        title: formatMessage({
          id: "".concat(intlPrefix, ".").concat(title, ".help.tooltip")
        })
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "help"
      })), modeSwitch ? /*#__PURE__*/React.createElement(_Button, {
        className: "c7n-config-mode-btn",
        type: "primary",
        funcType: "flat",
        disabled: disableBtn,
        onClick: this.changeEditMode
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: isYamlEdit ? 'configMap.mode.yaml' : 'configMap.mode.kv'
      })) : null), /*#__PURE__*/React.createElement("div", {
        className: "c7n-config-editor"
      }, this.getConfigMap())));
    }
  }]);

  return FormView;
}(Component), _class2.defaultProps = {
  modeSwitch: false
}, _temp)) || _class) || _class) || _class) || _class);
export { FormView as default };