import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
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/radio/style";
import _Radio from "choerodon-ui/lib/radio";
import "choerodon-ui/lib/select/style";
import _Select from "choerodon-ui/lib/select";
import "choerodon-ui/lib/form/style";
import _Form from "choerodon-ui/lib/form";

var _dec, _class;

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

import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { injectIntl, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import _ from 'lodash';
import "./index.less";
var FormItem = _Form.Item;
var Option = _Select.Option;
var RadioGroup = _Radio.Group;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var CreateNetwork = (_dec = inject('AppState'), injectIntl(_class = withRouter(_class = _dec(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(CreateNetwork, _Component);

  var _super = _createSuper(CreateNetwork);

  function CreateNetwork(props) {
    var _this;

    _classCallCheck(this, CreateNetwork);

    _this = _super.call(this, props);
    /* **************
     *                        state              this
     * portKeys/targetKeys | 用于radio选择模式 | 生成一组表单项的唯一表示
     *
     ************** */

    _this.checkName = _.debounce(function (rule, value, callback) {
      var _this$props = _this.props,
          formatMessage = _this$props.intl.formatMessage,
          store = _this$props.store,
          projectId = _this$props.AppState.currentMenuType.projectId,
          envId = _this$props.envId;
      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.checkNetWorkName(projectId, envId, value).then(function (data) {
          if (data) {
            callback();
          } else {
            callback(formatMessage({
              id: 'network.name.check.exist'
            }));
          }
        });
      } else {
        callback();
      }
    }, 1000);

    _this.checkIP = function (rule, value, callback, type) {
      var formatMessage = _this.props.intl.formatMessage;
      var p = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/;
      var validIp = {};
      var data = type === 'targetIps' ? 'targetIp' : 'validIp';
      var errorMsg;

      if (value && value.length) {
        _.forEach(value, function (item) {
          if (!p.test(item)) {
            errorMsg = formatMessage({
              id: 'network.ip.check.failed'
            });
            validIp[item] = true;
          }
        });

        _this.setState(_defineProperty({}, data, validIp));

        callback(errorMsg);
      } else {
        callback();
      }
    };

    _this.checkPort = function (rule, value, callback, type) {
      var _this$props2 = _this.props,
          formatMessage = _this$props2.intl.formatMessage,
          getFieldValue = _this$props2.form.getFieldValue;
      var p = /^([1-9]\d*|0)$/;

      var count = _.countBy(getFieldValue(type));

      var data = {
        typeMsg: '',
        min: 0,
        max: 65535,
        failedMsg: 'network.port.check.failed'
      };

      switch (type) {
        case 'tport':
          data.typeMsg = 'network.tport.check.repeat';
          break;

        case 'nport':
          data.typeMsg = 'network.nport.check.repeat';
          data.min = 30000;
          data.max = 32767;
          data.failedMsg = 'network.nport.check.failed';
          break;

        case 'targetport':
          data.typeMsg = 'network.tport.check.repeat';
          break;

        default:
          data.typeMsg = 'network.port.check.repeat';
      }

      if (value) {
        if (p.test(value) && parseInt(value, 10) >= data.min && parseInt(value, 10) <= data.max) {
          if (count[value] < 2) {
            callback();
          } else {
            callback(formatMessage({
              id: data.typeMsg
            }));
          }
        } else {
          callback(formatMessage({
            id: data.failedMsg
          }));
        }
      } else {
        callback();
      }
    };

    _this.handleTypeChange = function (e, key) {
      var _this$props$form = _this.props.form,
          resetFields = _this$props$form.resetFields,
          setFieldsValue = _this$props$form.setFieldsValue;
      _this.portKeys = 1;
      resetFields(['port', 'tport', 'nport', 'protocol']);
      setFieldsValue(_defineProperty({}, key, [0]));

      _this.setState(_defineProperty({}, key, e.target.value));
    };

    _this.removeGroup = function (k, type) {
      var _this$props3 = _this.props,
          _this$props3$form = _this$props3.form,
          getFieldValue = _this$props3$form.getFieldValue,
          setFieldsValue = _this$props3$form.setFieldsValue,
          validateFields = _this$props3$form.validateFields,
          store = _this$props3.store;
      var portKeys = _this.state.portKeys;
      var keys = getFieldValue(type);

      if (keys.length === 1) {
        return;
      }

      var list = [];

      switch (type) {
        case 'portKeys':
          list = ['port', 'tport'];
          portKeys !== 'ClusterIP' && list.push('nport');
          break;

        case 'endPoints':
          list = ['targetport'];
          break;

        case 'targetKeys':
          list = ['keywords'];
          break;

        default:
          break;
      }

      setFieldsValue(_defineProperty({}, type, _.filter(keys, function (key) {
        return key !== k;
      })), function () {
        validateFields(list, {
          force: true
        });

        _this.triggerNetPortCheck();
      });
    };

    _this.addGroup = function (type) {
      var _this$props$form2 = _this.props.form,
          getFieldValue = _this$props$form2.getFieldValue,
          setFieldsValue = _this$props$form2.setFieldsValue;
      var keys = getFieldValue(type);
      var uuid = _this[type];

      var nextKeys = _.concat(keys, uuid);

      _this[type] = uuid + 1;
      setFieldsValue(_defineProperty({}, type, nextKeys));
    };

    _this.changeValue = _.debounce(function (type, keyFiled, valueFiled, value) {
      var validateFields = _this.props.form.validateFields;

      if (type === 'keywords') {
        _this.selectLabel(value, keyFiled, valueFiled);
      }

      if (type === 'port') {
        _this.triggerNetPortCheck();
      }

      validateFields([type], {
        force: true
      });
    }, 400);

    _this.triggerNetPortCheck = function () {
      var _this$props$form3 = _this.props.form,
          validateFields = _this$props$form3.validateFields,
          getFieldValue = _this$props$form3.getFieldValue,
          setFieldsValue = _this$props$form3.setFieldsValue;

      _.forEach(getFieldValue('paths'), function (item) {
        var value = getFieldValue("netPort[".concat(item, "]"));

        if (value && !getFieldValue('port').includes(value)) {
          setFieldsValue(_defineProperty({}, "netPort[".concat(item, "]"), ''));
        }
      });
    };

    _this.handleChoiceRender = function (liNode, value, type) {
      return /*#__PURE__*/React.cloneElement(liNode, {
        className: classnames(liNode.props.className, {
          'ip-check-error': _this.state[type || 'validIp'][value]
        })
      });
    };

    _this.handleChoiceRemove = function (value, type) {
      var data = _this.state[type || 'validIp']; // 直接删除

      if (value in data) {
        delete data[value];
      }
    };

    _this.handleInputKeyDown = function (e, type) {
      var value = e.target.value;

      if (e.keyCode === 13 && !e.isDefaultPrevented() && value) {
        _this.setIpInSelect(value, type);
      }
    };

    _this.setIpInSelect = function (value, type) {
      var _this$props$form4 = _this.props.form,
          getFieldValue = _this$props$form4.getFieldValue,
          validateFields = _this$props$form4.validateFields,
          setFieldsValue = _this$props$form4.setFieldsValue;
      var itemType = type || 'externalIps';
      var ip = getFieldValue(itemType) || [];

      if (!ip.includes(value)) {
        ip.push(value);
        setFieldsValue(_defineProperty({}, itemType, ip));
      }

      validateFields([itemType]);
      var data = type === 'targetIps' ? _this.targetIpSelect : _this.ipSelect;

      if (data) {
        data.setInputValue('');
      }
    };

    _this.ipSelectRef = function (node, type) {
      var data = type === 'targetIps' ? 'targetIpSelect' : 'ipSelect';

      if (node) {
        _this[data] = node.rcSelect;
      }
    };

    _this.selectLabel = function (value, keyFiled, valueFiled) {
      var _this$props$form5 = _this.props.form,
          setFieldsValue = _this$props$form5.setFieldsValue,
          validateFields = _this$props$form5.validateFields;

      if (_.includes(value, '__')) {
        var _setFieldsValue6;

        setFieldsValue((_setFieldsValue6 = {}, _defineProperty(_setFieldsValue6, keyFiled, value.split('__')[0]), _defineProperty(_setFieldsValue6, valueFiled, value.split('__')[1]), _setFieldsValue6));
        validateFields(['keywords'], {
          force: true
        });
      }
    };

    _this.handleChangeName = function (e) {
      var _this$props4 = _this.props,
          store = _this$props4.store,
          _this$props4$form = _this$props4.form,
          getFieldValue = _this$props4$form.getFieldValue,
          setFieldsValue = _this$props4$form.setFieldsValue;

      _.forEach(getFieldValue('paths'), function (item) {
        setFieldsValue(_defineProperty({}, "network[".concat(item, "]"), e.target.value));
      });
    };

    _this.state = {
      targetKeys: 'instance',
      portKeys: 'ClusterIP',
      initName: '',
      validIp: {},
      targetIp: {}
    };
    _this.portKeys = 1;
    _this.targetKeys = 0;
    _this.endPoints = 0;
    return _this;
  }
  /**
   * 检查名字的唯一性
   * @param rule
   * @param value
   * @param callback
   */


  _createClass(CreateNetwork, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props5 = this.props,
          _this$props5$form = _this$props5.form,
          getFieldDecorator = _this$props5$form.getFieldDecorator,
          getFieldValue = _this$props5$form.getFieldValue,
          formatMessage = _this$props5.intl.formatMessage,
          store = _this$props5.store,
          envId = _this$props5.envId;
      var _this$state = this.state,
          configType = _this$state.portKeys,
          initName = _this$state.initName; // 生成多组 port

      getFieldDecorator('portKeys', {
        initialValue: [0]
      });
      var portKeys = getFieldValue('portKeys');

      var portItems = _.map(portKeys, function (k) {
        return /*#__PURE__*/React.createElement("div", {
          key: "port-".concat(k),
          className: "network-port-wrap"
        }, configType !== 'ClusterIP' && /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "c7n-select_118 network-panel-form network-port-form"
        }, formItemLayout), getFieldDecorator("nport[".concat(k, "]"), {
          rules: [{
            validator: function validator(rule, value, callback) {
              return _this2.checkPort(rule, value, callback, 'nport');
            }
          }]
        })( /*#__PURE__*/React.createElement(_Input, {
          type: "text",
          maxLength: 5,
          onChange: _this2.changeValue.bind(_this2, 'nport'),
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "network.config.nodePort"
          })
        }))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "c7n-select_118 network-panel-form network-port-form"
        }, formItemLayout), getFieldDecorator("port[".concat(k, "]"), {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }, {
            validator: function validator(rule, value, callback) {
              return _this2.checkPort(rule, value, callback, 'port');
            }
          }]
        })( /*#__PURE__*/React.createElement(_Input, {
          type: "text",
          maxLength: 5,
          onChange: _this2.changeValue.bind(_this2, 'port'),
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "network.config.port"
          })
        }))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "c7n-select_118 network-panel-form network-port-form"
        }, formItemLayout), getFieldDecorator("tport[".concat(k, "]"), {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }, {
            validator: function validator(rule, value, callback) {
              return _this2.checkPort(rule, value, callback, 'tport');
            }
          }]
        })( /*#__PURE__*/React.createElement(_Input, {
          type: "text",
          maxLength: 5,
          onChange: _this2.changeValue.bind(_this2, 'tport'),
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "network.config.targetPort"
          })
        }))), configType === 'NodePort' && /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "c7n-select_118 network-panel-form network-port-form"
        }, formItemLayout), getFieldDecorator("protocol[".concat(k, "]"), {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }]
        })( /*#__PURE__*/React.createElement(_Select, {
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "ist.deploy.ports.protocol"
          })
        }, _.map(['TCP', 'UDP'], function (item) {
          return /*#__PURE__*/React.createElement(Option, {
            value: item,
            key: item
          }, item);
        })))), portKeys.length > 1 && /*#__PURE__*/React.createElement(_Icon, {
          className: "network-group-icon",
          type: "delete",
          onClick: function onClick() {
            return _this2.removeGroup(k, 'portKeys');
          }
        }));
      });

      return /*#__PURE__*/React.createElement(_Form, {
        layout: "horizontal",
        className: "c7ncd-deploy-network-form-wrap",
        style: {
          width: '66.66%'
        }
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "network-form-name"
      }, formItemLayout), getFieldDecorator('networkName', {
        initialValue: initName,
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }, {
          validator: this.checkName
        }]
      })( /*#__PURE__*/React.createElement(_Input, {
        maxLength: 30,
        disabled: !envId,
        type: "text",
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "network.form.name"
        }),
        onChange: this.handleChangeName
      }))), /*#__PURE__*/React.createElement("div", {
        className: "network-panel-title"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ist.networking.service.type"
      })), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "network-radio-form"
      }, formItemLayout), getFieldDecorator('config', {
        initialValue: configType
      })( /*#__PURE__*/React.createElement(RadioGroup, {
        name: "config",
        onChange: function onChange(e) {
          return _this2.handleTypeChange(e, 'portKeys');
        }
      }, /*#__PURE__*/React.createElement(_Radio, {
        value: "ClusterIP"
      }, "ClusterIP"), /*#__PURE__*/React.createElement(_Radio, {
        value: "NodePort"
      }, "NodePort"), /*#__PURE__*/React.createElement(_Radio, {
        value: "LoadBalancer"
      }, "LoadBalancer")))), /*#__PURE__*/React.createElement("div", {
        className: "network-panel"
      }, configType === 'ClusterIP' && /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "network-panel-form"
      }, formItemLayout), getFieldDecorator('externalIps', {
        rules: [{
          validator: this.checkIP
        }]
      })( /*#__PURE__*/React.createElement(_Select, {
        mode: "tags",
        ref: this.ipSelectRef,
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "network.config.ip"
        }),
        onInputKeyDown: this.handleInputKeyDown,
        choiceRender: this.handleChoiceRender,
        onChoiceRemove: this.handleChoiceRemove,
        filterOption: false,
        notFoundContent: false,
        showNotFindInputItem: false,
        showNotFindSelectedItem: false,
        allowClear: true
      }))), portItems, /*#__PURE__*/React.createElement(_Button, {
        type: "primary",
        funcType: "flat",
        onClick: function onClick() {
          return _this2.addGroup('portKeys');
        },
        icon: "add",
        className: "c7ncd-deploy-network-btn"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "network.config.addport"
      })))));
    }
  }]);

  return CreateNetwork;
}(Component)) || _class) || _class) || _class) || _class);
export { CreateNetwork as default };