import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/pro/lib/text-area/style";
import _TextArea from "choerodon-ui/pro/lib/text-area";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";

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 _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 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 _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 = 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; }

import React, { Fragment, useState, useEffect, useMemo, useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import { FormattedMessage } from 'react-intl';
import _ from 'lodash';
import { Choerodon } from '@choerodon/boot';
import { objToYaml, yamlToObj, takeObject, ConfigNode, makePostData } from "../utils";
import YamlEditor from "../../../../../../../components/yamlEditor";
import { handlePromptError } from "../../../../../../../utils";
import { useKeyValueStore } from "./stores";
import "../../../../../../main.less";
import "./index.less";
var FormView = observer(function () {
  var _useKeyValueStore = useKeyValueStore(),
      id = _useKeyValueStore.id,
      appId = _useKeyValueStore.appId,
      store = _useKeyValueStore.store,
      formatMessage = _useKeyValueStore.intl.formatMessage,
      _useKeyValueStore$App = _useKeyValueStore.AppState.currentMenuType,
      projectId = _useKeyValueStore$App.projectId,
      menuName = _useKeyValueStore$App.name,
      title = _useKeyValueStore.title,
      modeSwitch = _useKeyValueStore.modeSwitch,
      intlPrefix = _useKeyValueStore.intlPrefix,
      envId = _useKeyValueStore.envId,
      refresh = _useKeyValueStore.refresh,
      modal = _useKeyValueStore.modal,
      FormDataSet = _useKeyValueStore.FormDataSet,
      KeyValueDataSet = _useKeyValueStore.KeyValueDataSet;

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      dataYaml = _useState2[0],
      setDataYaml = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      hasItemError = _useState4[0],
      setHasItemError = _useState4[1];

  var _useState5 = useState(''),
      _useState6 = _slicedToArray(_useState5, 2),
      warningMes = _useState6[0],
      setWarningMes = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      isYamlEdit = _useState8[0],
      setIsYamlEdit = _useState8[1];

  var _useState9 = useState(false),
      _useState10 = _slicedToArray(_useState9, 2),
      hasYamlError = _useState10[0],
      setHasYamlError = _useState10[1];

  var _useState11 = useState(false),
      _useState12 = _slicedToArray(_useState11, 2),
      hasValueError = _useState12[0],
      setHasValueError = _useState12[1];

  var _useState13 = useState(''),
      _useState14 = _slicedToArray(_useState13, 2),
      valueErrorMsg = _useState14[0],
      setValueErrorMsg = _useState14[1];

  var _useState15 = useState(false),
      _useState16 = _slicedToArray(_useState15, 2),
      isSubmit = _useState16[0],
      setIsSubmit = _useState16[1];

  useEffect(function () {
    function callBack() {
      return _callBack.apply(this, arguments);
    }

    function _callBack() {
      _callBack = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var res, dataSourceCurrent;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!id) {
                  _context.next = 6;
                  break;
                }

                _context.next = 3;
                return FormDataSet.query();

              case 3:
                res = _context.sent;
                dataSourceCurrent = _.map(res.value, function (value, key) {
                  return new ConfigNode(key, value);
                });
                KeyValueDataSet.loadData(dataSourceCurrent);

              case 6:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));
      return _callBack.apply(this, arguments);
    }

    callBack();
  }, []);
  useEffect(function () {
    checkButtonDisabled(isSubmit);
  }, [hasValueError, hasItemError, hasYamlError]);
  /**
   * 删除key-value
   * @param key
   */

  var handleDelete = function handleDelete(record) {
    KeyValueDataSet.remove(record);
    asyncCheckErrorData(KeyValueDataSet.toData());
  };
  /**
   * 添加一组 key/value
   * @param data
   */


  var handleAdd = function handleAdd() {
    KeyValueDataSet.create();
  };
  /**
   * configMap 规则中value只能是字符串
   * @param data
   */


  var checkConfigRuleError = function checkConfigRuleError() {
    var dataCurrent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    var yaml = dataCurrent || dataYaml;
    var yamlObj = yamlToObj(yaml) || {};
    var values = Object.values(yamlObj);
    var error = false; // eslint-disable-next-line no-plusplus

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

    setHasValueError(error);
    setValueErrorMsg('内容不符合规则 (value只能是字符串，如果是数字请用单引号包裹)');
    return error;
  };

  var asyncCheckConfigRuleError = _.debounce(checkConfigRuleError, 600);
  /**
   * 同步校验键值对
   * @param data
   * @returns {boolean}
   */


  var checkErrorData = function checkErrorData() {
    var dataCurrent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    var isSubmitCurrent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    var dataSource = KeyValueDataSet.toData(); // eslint-disable-next-line no-underscore-dangle

    var _data = dataCurrent || dataSource;

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

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

    var onlyHasKey = title === 'cipher' && hasKey.filter(function (_ref3) {
      var value = _ref3.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; // eslint-disable-next-line no-restricted-syntax

    var _iterator = _createForOfIteratorHelper(hasKey),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var key = _step.value.key;
        // eslint-disable-next-line no-useless-escape
        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)) {
      setWarningMes('');
      setIsSubmit(isSubmitCurrent);
      setHasItemError(false);
      return false;
    }

    var errorMsg = hasErrorKey ? '键值不能含空格及-、_、.以外的特殊字符，请检查输入' : formatMessage({
      id: hasRepeatKey ? 'configMap.keyRepeat' : "".concat(title, ".keyValueSpan")
    });
    setConfigError(errorMsg);
    return true;
  };
  /**
   * 校验键值对
   * @param data
   * @returns {boolean}
   */


  var asyncCheckErrorData = _.debounce(checkErrorData, 500);
  /**
   * 设置键值对模式下的错误提示
   * @param msg
   */


  function setConfigError(msg) {
    setWarningMes(msg);
    setHasItemError(true);
    modal.update({
      okProps: {
        disabled: true
      }
    });
  }

  var formValidate = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var configData, hasKVError, hasConfigRuleError;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              configData = [];
              hasKVError = false;
              hasConfigRuleError = false;
              return _context2.abrupt("return", new Promise(function (resolve) {
                var _FormDataSet$toData$ = FormDataSet.toData()[0],
                    name = _FormDataSet$toData$.name,
                    description = _FormDataSet$toData$.description;
                var dataSource = KeyValueDataSet.toData();

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

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

                  configData = allData;
                } else {
                  hasConfigRuleError = checkConfigRuleError();
                  configData = yamlToObj(dataYaml);
                }

                if (hasYamlError || hasKVError || hasConfigRuleError) {
                  resolve(false);
                } else {
                  setHasItemError(false); // eslint-disable-next-line no-underscore-dangle

                  // eslint-disable-next-line no-underscore-dangle
                  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);
                }
              }));

            case 4:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function formValidate() {
      return _ref4.apply(this, arguments);
    };
  }();
  /**
   * form提交函数
   * 添加粘贴后key-value校验
   * @param e
   */


  var handleSubmit = /*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var isValidate, postData, res;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return FormDataSet.validate();

            case 2:
              isValidate = _context3.sent;

              if (!isValidate) {
                _context3.next = 25;
                break;
              }

              _context3.next = 6;
              return formValidate();

            case 6:
              postData = _context3.sent;

              if (postData) {
                _context3.next = 9;
                break;
              }

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

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

            case 12:
              res = _context3.sent;

              if (!handlePromptError(res)) {
                _context3.next = 16;
                break;
              }

              refresh();
              return _context3.abrupt("return", true);

            case 16:
              return _context3.abrupt("return", false);

            case 19:
              _context3.prev = 19;
              _context3.t0 = _context3["catch"](9);
              Choerodon.handleResponseError(_context3.t0);
              return _context3.abrupt("return", false);

            case 23:
              _context3.next = 26;
              break;

            case 25:
              return _context3.abrupt("return", false);

            case 26:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[9, 19]]);
    }));

    return function handleSubmit() {
      return _ref5.apply(this, arguments);
    };
  }();

  var getDataSourceMapFormItem = function getDataSourceMapFormItem() {
    return KeyValueDataSet.data.map(function (record) {
      return /*#__PURE__*/React.createElement(_Form, {
        record: record,
        key: record.id,
        columns: 18,
        className: "c7n-config-container"
      }, /*#__PURE__*/React.createElement(_TextField, {
        name: "key",
        onBlur: function onBlur() {
          return checkErrorData(null, false);
        },
        colSpan: 5
      }), /*#__PURE__*/React.createElement("span", {
        className: "c7n-config-equal"
      }, "="), /*#__PURE__*/React.createElement(_TextArea, {
        className: "c7n-config-value",
        name: "value",
        autoSize: {
          minRows: 1
        },
        resize: "vertical",
        onBlur: function onBlur() {
          return checkErrorData(null, false);
        },
        colSpan: 11
      }), /*#__PURE__*/React.createElement(_Button, {
        funcType: "flat",
        icon: "delete",
        className: "c7ncd-form-record-delete-btn",
        onClick: function onClick() {
          return handleDelete(record);
        }
      }));
    });
  };
  /**
   * 编辑 configMap 组件节点
   * 有两种模式：key/value编辑模式、YAML代码编辑模式
   * @returns {*}
   */


  var getConfigMap = function getConfigMap() {
    var configMap = null;

    if (!isYamlEdit) {
      configMap = /*#__PURE__*/React.createElement(React.Fragment, null, getDataSourceMapFormItem(), /*#__PURE__*/React.createElement(_Button, {
        icon: "add",
        onClick: 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(React.Fragment, null, /*#__PURE__*/React.createElement(YamlEditor, {
        readOnly: false,
        modeChange: false,
        value: dataYaml,
        onValueChange: changeYamlValue,
        handleEnableNext: checkYamlError
      }), /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-config-yaml-tip"
      }, hasValueError && (valueErrorMsg || /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "configMap.yaml.error"
      }))));
    }

    return configMap;
  };
  /**
   * yaml 值改变
   * @param value
   */


  var changeYamlValue = function changeYamlValue(value) {
    asyncCheckConfigRuleError(value);
    setDataYaml(value);
  };
  /**
   * 校验yaml格式
   * @param flag
   */


  var checkYamlError = function checkYamlError(flag) {
    setHasYamlError(flag);
  };
  /**
   * 切换配置映射的编辑模式
   */


  var changeEditMode = function changeEditMode() {
    if (hasYamlError || hasValueError || hasItemError) return;

    if (!isYamlEdit) {
      var dataSource = KeyValueDataSet.toData();
      var result = checkErrorData(dataSource);
      if (result) return;
      var yamlValue = objToYaml(dataSource);
      checkConfigRuleError(yamlValue);
      setHasItemError(false);
      setIsYamlEdit(true);
      setWarningMes('');
      setDataYaml(yamlValue);
    } else {
      var _result = checkConfigRuleError(dataYaml);

      if (_result) return;

      try {
        var kvValue = yamlToObj(dataYaml);
        var postData = makePostData(kvValue);
        KeyValueDataSet.loadData(postData);
        setHasYamlError(false);
        setIsYamlEdit(false);
        setDataYaml('');
      } catch (e) {
        setHasValueError(true);
        setValueErrorMsg(e.message);
        modal.update({
          okProps: {
            disabled: true
          }
        });
      }
    }
  };

  var checkButtonDisabled = function checkButtonDisabled() {
    var isSubmitCurrent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    !isSubmitCurrent && modal.update({
      okProps: {
        disabled: hasYamlError || hasValueError || hasItemError
      }
    });
    setIsSubmit(false);
  };

  var disableBtn = hasYamlError || hasValueError || hasItemError;
  modal.handleOk(handleSubmit);
  return /*#__PURE__*/React.createElement("div", {
    className: "c7n-region"
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_Form, {
    dataSet: FormDataSet,
    className: "c7n-sidebar-form",
    layout: "vertical"
  }, /*#__PURE__*/React.createElement(_TextField, {
    name: "name" // autoFocus={!id}
    ,
    disabled: !!id
  }), /*#__PURE__*/React.createElement(_TextArea, {
    name: "description" // autoFocus={!!id}
    ,
    autosize: {
      minRows: 2
    }
  })), /*#__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: changeEditMode
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: isYamlEdit ? 'configMap.mode.yaml' : 'configMap.mode.kv'
  })) : null), /*#__PURE__*/React.createElement("div", {
    className: "c7n-config-editor"
  }, getConfigMap())));
});
export default FormView;