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(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; }
import React, { useMemo, useState } from 'react';
import { Button, Popover, Form, Input, Select } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import Icon from "../Icon";
import { mergeMetadataTexts } from "../metadata/locale";
function LabelFormItem(props) {
  var form = props.form,
    type = props.type,
    count = props.count,
    setCount = props.setCount,
    _props$valueRequired = props.valueRequired,
    valueRequired = _props$valueRequired === void 0 ? false : _props$valueRequired,
    textsProp = props.texts;
  var t = useMemo(function () {
    return mergeMetadataTexts(textsProp);
  }, [textsProp]);
  var pattern = {
    chrLimit: {
      rule: /^[A-Za-z0-9_.-]+$/,
      tips: t.ruleValidCharacterUL // '仅允许使用大小写字母、数字、点（.）、中划线（-）和下划线（_）'
    },
    chrBE: {
      rule: /^[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?$/,
      tips: t.ruleBeginAndEnd // '必须以大小写字母或数字开头结尾'
    },
    prefLimit: {
      rule: /^[a-z0-9.-]+$/,
      tips: t.ruleValidCharacterL //'仅允许使用小写字母、数字、点（.）、中划线（-）'
    },
    prefBE: {
      ruleA: /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/,
      //必须以小写字母或数字开头结尾
      ruleB: /^(?!.*\.\.)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/,
      //不能连续使用点（.）
      ruleC: /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,
      //每个子域标签不能以中划线（-）开头或结尾
      tips: t.ruleBeginAndEndAndMore //'必须以小写字母或数字开头结尾，每个子域标签不能以中划线（-）开头或结尾，且不能连续使用点（.），'
    }
  };
  var transMap = {
    val: {
      labels: t.labelValueLower,
      taints: t.taintValueLower,
      annotations: t.annotationValueLower
    },
    keyUpper: {
      labels: t.labelKey,
      taints: t.taintKey,
      annotations: t.annotationKey
    },
    keyLower: {
      labels: t.labelKeyLower,
      taints: t.taintKeyLower,
      annotations: t.annotationKeyLower
    },
    name: {
      labels: t.label,
      taints: t.taint,
      annotations: t.annotation
    }
  };
  var defultKeyNameCheck = [{
    state: 0,
    // 0：未校验；1：校验成功；-1：校验失败
    tips: t.characterLen1T36 //'长度限制在 1-63 个字符间'
  }, {
    state: 0,
    tips: pattern.chrLimit.tips
  }, {
    state: 0,
    tips: pattern.chrBE.tips
  }];
  var defultKeyPrefCheck = [{
    state: 0,
    tips: t.characterLen253L63 //'长度限制在 253 个字符内，每个子域标签长度限制在 63 个字符内'
  }, {
    state: 0,
    tips: pattern.prefLimit.tips
  }, {
    state: 0,
    tips: pattern.prefBE.tips
  }];
  var defaultValNameCheck = [{
    state: 0,
    tips: t.characterLenL63 // '长度限制在 63 个字符内'
  }, {
    state: 0,
    tips: pattern.chrLimit.tips
  }, {
    state: 0,
    tips: pattern.chrBE.tips
  }];
  var _useState = useState([].concat(defultKeyNameCheck)),
    _useState2 = _slicedToArray(_useState, 2),
    keyNameCheck = _useState2[0],
    setKeyNameCheck = _useState2[1];
  var _useState3 = useState([].concat(defultKeyPrefCheck)),
    _useState4 = _slicedToArray(_useState3, 2),
    keyPrefCheck = _useState4[0],
    setKeyPrefCheck = _useState4[1];
  var _useState5 = useState([].concat(defaultValNameCheck)),
    _useState6 = _slicedToArray(_useState5, 2),
    valNameCheck = _useState6[0],
    setValNameCheck = _useState6[1];
  var handleKeyCheck = function handleKeyCheck(value) {
    var perfix = '';
    var name = '';
    if (value && value.indexOf('/') > -1) {
      perfix = value.split('/')[0];
      name = value.split('/')[1];
    } else {
      name = value;
    }
    var nCheck = _toConsumableArray(keyNameCheck);
    if (name) {
      var _name;
      if (((_name = name) === null || _name === void 0 ? void 0 : _name.length) >= 1 && name.length <= 63) {
        nCheck[0].state = 1;
      } else {
        nCheck[0].state = -1;
      }
      if (new RegExp(pattern.chrLimit.rule).test(name)) {
        nCheck[1].state = 1;
      } else {
        nCheck[1].state = -1;
      }
      if (new RegExp(pattern.chrBE.rule).test(name)) {
        nCheck[2].state = 1;
      } else {
        nCheck[2].state = -1;
      }
    } else {
      nCheck[0].state = -1;
      nCheck[1].state = -1;
      nCheck[2].state = -1;
    }
    setKeyNameCheck(nCheck);
    var pCheck = _toConsumableArray(keyPrefCheck);
    if (perfix) {
      var _perfix;
      var subs = [];
      if (perfix.indexOf('.') > -1) {
        subs = perfix.split('.');
      } else {
        subs = [perfix];
      }
      if (((_perfix = perfix) === null || _perfix === void 0 ? void 0 : _perfix.length) <= 253) {
        var flag = true;
        subs.forEach(function (item) {
          if (item.length > 63) {
            flag = false;
          }
        });
        pCheck[0].state = flag ? 1 : -1;
      } else {
        pCheck[0].state = -1;
      }
      if (new RegExp(pattern.prefLimit.rule).test(perfix)) {
        pCheck[1].state = 1;
      } else {
        pCheck[1].state = -1;
      }
      if (new RegExp(pattern.prefBE.ruleA).test(perfix) && new RegExp(pattern.prefBE.ruleB).test(perfix)) {
        var _flag = true;
        subs.forEach(function (item) {
          if (!new RegExp(pattern.prefBE.ruleC).test(item)) {
            _flag = false;
          }
        });
        pCheck[2].state = _flag ? 1 : -1;
      } else {
        pCheck[2].state = -1;
      }
    } else if (value && value.indexOf('/') > -1) {
      pCheck[2].state = -1;
    } else {
      pCheck[0].state = 0;
      pCheck[1].state = 0;
      pCheck[2].state = 0;
    }
    setKeyPrefCheck(pCheck);
  };
  var handleValueCheck = function handleValueCheck(value) {
    var nCheck = _toConsumableArray(valNameCheck);
    if (value.length <= 63) {
      nCheck[0].state = 1;
    } else {
      nCheck[0].state = -1;
    }
    if (new RegExp(pattern.chrLimit.rule).test(value)) {
      nCheck[1].state = 1;
    } else {
      nCheck[1].state = -1;
    }
    if (new RegExp(pattern.chrBE.rule).test(value)) {
      nCheck[2].state = 1;
    } else {
      nCheck[2].state = -1;
    }
    setValNameCheck(nCheck);
  };
  var popoverTipRender = function popoverTipRender(record, key) {
    var className = '';
    var iconName = 'v35_Help';
    if (record.state === 1) {
      className = 'pass';
      iconName = 'v35_Success';
    }
    if (record.state === -1) {
      className = 'error';
      iconName = 'v35_Failure';
    }
    if (record.state === 0) {
      className = '';
      iconName = 'v35_Help';
    }
    return /*#__PURE__*/React.createElement("p", {
      key: key,
      className: className
    }, /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(Icon, {
      name: iconName
    })), /*#__PURE__*/React.createElement("span", null, record.tips));
  };
  return /*#__PURE__*/React.createElement(Form.List, {
    name: type
  }, function (fields, _ref) {
    var add = _ref.add,
      remove = _ref.remove;
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      className: "metadata-list"
    }, fields.map(function (field) {
      return /*#__PURE__*/React.createElement("div", {
        className: "metadata-item",
        key: field.key
      }, /*#__PURE__*/React.createElement(Popover, {
        content: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h5", null, t.keyTipsSN1(transMap.keyLower[type]), /*#__PURE__*/React.createElement("b", null, t.keyTipsSN2), t.keyTipsSN3, /*#__PURE__*/React.createElement("b", null, t.keyTipsSN4), t.keyTipsSN5), /*#__PURE__*/React.createElement("p", {
          className: "title"
        }, t.keyTipsNameRule), keyNameCheck.map(function (item, i) {
          return popoverTipRender(item, i);
        }), /*#__PURE__*/React.createElement("p", {
          className: "title"
        }, t.keyTipsPrefixRule), keyPrefCheck.map(function (item, i) {
          return popoverTipRender(item, i);
        })),
        placement: "rightTop",
        onOpenChange: function onOpenChange(isOpen) {
          if (isOpen) {
            var key = form.getFieldValue([type, field.name, 'key']);
            handleKeyCheck(key);
          }
        },
        overlayClassName: 'metadata-check-tips-popover'
      }, /*#__PURE__*/React.createElement(Form.Item, {
        name: [field.name, 'key'],
        rules: [{
          required: true,
          message: t.enterPL(transMap.keyLower[type])
        }, {
          validator: function validator(_, value) {
            if (value) {
              var check = [];
              var perfix = '';
              var name = '';
              var subs = [];
              if (value.indexOf('/') > -1) {
                perfix = value.split('/')[0];
                name = value.split('/')[1];
                if (perfix) {
                  if (perfix.indexOf('.') > -1) {
                    subs = perfix.split('.');
                  } else {
                    subs = [perfix];
                  }
                } else {
                  // 无前缀但输入了‘/’
                  check.push(false);
                }
              } else {
                name = value;
              }
              // 名称校验
              var namePattern = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]{0,61}[a-zA-Z0-9])?$/;
              var nameRegx = new RegExp(namePattern);
              check.push(nameRegx.test(name));
              if (perfix) {
                var _perfix2;
                // 前缀整体校验
                if (((_perfix2 = perfix) === null || _perfix2 === void 0 ? void 0 : _perfix2.length) <= 253 && new RegExp(pattern.prefBE.ruleA).test(perfix) && new RegExp(pattern.prefBE.ruleB).test(perfix)) {
                  check.push(true);
                } else {
                  check.push(false);
                }
                // 前缀子域校验
                subs.forEach(function (item) {
                  if (item.length <= 63 && new RegExp(pattern.prefBE.ruleC).test(item)) {
                    check.push(true);
                  } else {
                    check.push(false);
                  }
                });
              }
              // 校验结果
              var flag = check.some(function (item) {
                return item === false;
              });
              if (flag) {
                return Promise.reject(t.ruleInvalid);
              } else {
                var list = form.getFieldValue(type) || [];
                var isRepeat = list.some(function (item, index) {
                  return field.name !== index && item.key === value;
                });
                if (isRepeat) {
                  return Promise.reject(t.keyRepeat(transMap.keyUpper[type]));
                } else {
                  return Promise.resolve();
                }
              }
            } else {
              return Promise.resolve();
            }
          }
        }]
      }, /*#__PURE__*/React.createElement(Input, {
        placeholder: t.enterPL(transMap.keyLower[type]),
        onChange: function onChange(e) {
          handleKeyCheck(e.target.value);
        }
      }))), type === 'annotations' ? /*#__PURE__*/React.createElement(Form.Item, {
        name: [field.name, 'value'],
        rules: [{
          required: valueRequired,
          message: t.enterPL(transMap.val[type])
        }, {
          max: 10240,
          message: t.characterLenL10240
        }]
      }, /*#__PURE__*/React.createElement(Input, {
        placeholder: form.getFieldValue([type, field.name, 'key']) ? t.enterPL(transMap.val[type]) : t.enterFirstPL(transMap.keyLower[type]),
        disabled: !form.getFieldValue([type, field.name, 'key'])
      })) : /*#__PURE__*/React.createElement(Popover, {
        content: form.getFieldValue([type, field.name, 'key']) ? valNameCheck.map(function (item, i) {
          return popoverTipRender(item, i);
        }) : /*#__PURE__*/React.createElement("p", null, t.enterFirstPL(transMap.keyLower[type])),
        placement: "rightTop",
        onOpenChange: function onOpenChange(isOpen) {
          if (isOpen) {
            var value = form.getFieldValue([type, field.name, 'value']);
            if (value) {
              handleValueCheck(value);
            } else {
              if (valueRequired) {
                var check = [].concat(defaultValNameCheck);
                check[0].state = -1;
                check[1].state = -1;
                check[2].state = -1;
                setValNameCheck(check);
              } else {
                setValNameCheck([].concat(defaultValNameCheck));
              }
            }
          }
        },
        overlayClassName: 'metadata-check-tips-popover'
      }, /*#__PURE__*/React.createElement(Form.Item, {
        name: [field.name, 'value'],
        rules: [{
          required: valueRequired,
          message: t.enterPL(transMap.val[type])
        }, {
          validator: function validator(_, value) {
            if (value) {
              var namePattern = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]{0,61}[a-zA-Z0-9])?$/;
              var nameRegx = new RegExp(namePattern);
              var flag = nameRegx.test(value);
              if (flag) {
                return Promise.resolve();
              } else {
                return Promise.reject(t.ruleInvalid);
              }
            } else {
              return Promise.resolve();
            }
          }
        }]
      }, /*#__PURE__*/React.createElement(Input, {
        placeholder: form.getFieldValue([type, field.name, 'key']) ? t.enterPL(transMap.val[type]) : t.enterFirstPL(transMap.keyLower[type]),
        disabled: !form.getFieldValue([type, field.name, 'key']),
        onChange: function onChange(e) {
          handleValueCheck(e.target.value);
        }
      }))), type === 'taints' && /*#__PURE__*/React.createElement(Form.Item, {
        name: [field.name, 'effect'],
        rules: [{
          required: true,
          message: t.taintEffectPL
        }]
      }, /*#__PURE__*/React.createElement(Select, {
        placeholder: t.taintEffectPL,
        options: [{
          value: 'NoSchedule',
          label: t.NoSchedule // '禁止调度（NoSchedule）',
        }, {
          value: 'PreferNoSchedule',
          label: t.PreferNoSchedule // '尽量避免调度（PreferNoSchedule）',
        }, {
          value: 'NoExecute',
          label: t.NoExecute //'驱逐调度（NoExecute）',
        }]
      })), /*#__PURE__*/React.createElement(Button, {
        type: "text",
        icon: /*#__PURE__*/React.createElement(Icon, {
          name: "v35_TrashCan"
        }),
        onClick: function onClick() {
          remove(field.name);
          setCount(count - 1);
        }
      }));
    })), /*#__PURE__*/React.createElement(Button, {
      type: "dashed",
      className: "metadata-add-btn",
      onClick: function onClick() {
        var data = {};
        if (type === 'taints') {
          data = {
            effect: 'NoSchedule'
          };
        }
        add(data);
        setCount(count + 1);
      },
      icon: /*#__PURE__*/React.createElement(PlusCircleOutlined, null)
    }, t.add(transMap.name[type])));
  });
}
export default LabelFormItem;