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

var _dec, _class;

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 { Choerodon } from '@choerodon/boot';
import _ from 'lodash';
import classnames from 'classnames';
import "./index.less";
var FormItem = _Form.Item;
var RadioGroup = _Radio.Group;
var Option = _Select.Option;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var Index = (_dec = inject('AppState'), injectIntl(_class = withRouter(_class = _dec(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(Index, _Component);

  var _super = _createSuper(Index);

  function Index(props) {
    var _this;

    _classCallCheck(this, Index);

    _this = _super.call(this, props);
    _this.checkName = _.debounce(function (rule, value, callback) {
      var _this$props = _this.props,
          formatMessage = _this$props.intl.formatMessage,
          projectId = _this$props.AppState.currentMenuType.projectId,
          DomainStore = _this$props.DomainStore,
          envId = _this$props.envId;
      var p = /^([a-z0-9]([-a-z0-9]?[a-z0-9])*)$/;

      if (value && p.test(value)) {
        if (envId) {
          DomainStore.checkName(projectId, value, envId).then(function (data) {
            if (data) {
              callback();
            } else {
              callback(formatMessage({
                id: 'domain.name.check.exist'
              }));
            }
          })["catch"](function () {
            return callback();
          });
        } else {
          callback(formatMessage({
            id: 'network.form.app.disable'
          }));
        }
      } else {
        callback(formatMessage({
          id: 'domain.name.check.failed'
        }));
      }
    }, 1000);

    _this.checkPath = function (rule, value, callback) {
      var _this$props2 = _this.props,
          _this$props2$form = _this$props2.form,
          getFieldValue = _this$props2$form.getFieldValue,
          getFieldError = _this$props2$form.getFieldError,
          projectId = _this$props2.AppState.currentMenuType.projectId,
          formatMessage = _this$props2.intl.formatMessage,
          type = _this$props2.type,
          DomainStore = _this$props2.DomainStore,
          envId = _this$props2.envId;

      if (value) {
        var p = /^\/(\S)*$/;

        var count = _.countBy(getFieldValue('path'));

        var domain = getFieldValue('domain');
        var domainError = getFieldError('domain');

        if (p.test(value)) {
          // 重复检查
          if (count[value] < 2) {
            // 如果域名校验不通过，则不发起域名路径组合校验
            if (!domainError) {
              var checkPromise = DomainStore.checkPath(projectId, domain, envId, encodeURIComponent(value));

              _this.handleCheckResponse(checkPromise, callback);
            } else {
              callback();
            }
          } else {
            callback(formatMessage({
              id: 'domain.path.check.exist'
            }));
          }
        } else {
          callback(formatMessage({
            id: 'domain.path.check.failed'
          }));
        }
      } else {
        callback(formatMessage({
          id: 'domain.path.check.notSet'
        }));
      }
    };

    _this.handleCheckResponse = function (promise, callback) {
      var formatMessage = _this.props.intl.formatMessage;

      if (promise) {
        promise.then(function (data) {
          if (data) {
            callback();
          } else {
            callback(formatMessage({
              id: 'domain.path.check.exist'
            }));
          }
        })["catch"](function (err) {
          Choerodon.handleResponseError(err);
          callback();
        });
      }
    };

    _this.checkDomain = _.debounce(function (rule, value, callback) {
      var _this$props3 = _this.props,
          formatMessage = _this$props3.intl.formatMessage,
          getFieldValue = _this$props3.form.getFieldValue;
      var pattern = /^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)+)$/;

      if (pattern.test(value)) {
        var paths = getFieldValue('paths');
        var fields = [];

        _.forEach(paths, function (item) {
          return fields.push("path[".concat(item, "]"));
        });

        _this.triggerPathCheck();

        callback();
      } else {
        callback(formatMessage({
          id: 'domain.domain.check.failed'
        }));
      }
    }, 1000);

    _this.checkPorts = function (rule, value, callback) {
      var _this$props4 = _this.props,
          formatMessage = _this$props4.intl.formatMessage,
          getFieldValue = _this$props4.form.getFieldValue;

      if (value && getFieldValue('port') && !getFieldValue('port').includes(value)) {
        callback(formatMessage({
          id: 'domain.network.check.failed'
        }));
      } else {
        callback();
      }
    };

    _this.addPath = function () {
      var _this$props$form = _this.props.form,
          getFieldValue = _this$props$form.getFieldValue,
          setFieldsValue = _this$props$form.setFieldsValue;
      var keys = getFieldValue('paths');
      var uuid = _this.pathKeys;

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

      _this.pathKeys = uuid + 1;
      setFieldsValue({
        paths: nextKeys
      });

      _this.setState({
        pathCountChange: true
      });
    };

    _this.removePath = function (k) {
      var _this$props$form2 = _this.props.form,
          getFieldValue = _this$props$form2.getFieldValue,
          setFieldsValue = _this$props$form2.setFieldsValue;
      var keys = getFieldValue('paths');

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

      setFieldsValue({
        paths: _.filter(keys, function (key) {
          return key !== k;
        })
      });

      _this.setState({
        pathCountChange: true
      });
    };

    _this.triggerPathCheck = function () {
      var _this$props$form3 = _this.props.form,
          getFieldValue = _this$props$form3.getFieldValue,
          validateFields = _this$props$form3.validateFields;
      var paths = getFieldValue('paths');
      var fields = [];

      _.forEach(paths, function (item) {
        return fields.push("path[".concat(item, "]"));
      });

      validateFields(fields, {
        force: true
      });

      _this.setState({
        pathCountChange: false
      });
    };

    _this.handleTypeChange = function (e) {
      var _this$props$form4 = _this.props.form,
          getFieldValue = _this$props$form4.getFieldValue,
          getFieldError = _this$props$form4.getFieldError,
          setFieldsValue = _this$props$form4.setFieldsValue;
      var protocol = e.target.value;
      var domain = getFieldValue('domain');

      if (domain && !getFieldError('domain')) {
        _this.loadCertByDomain(domain, protocol);
      }

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

    _this.loadCertByDomain = function (e, p) {
      var _this$props5 = _this.props,
          _this$props5$form = _this$props5.form,
          isModifiedField = _this$props5$form.isModifiedField,
          resetFields = _this$props5$form.resetFields,
          projectId = _this$props5.AppState.currentMenuType.projectId,
          DomainStore = _this$props5.DomainStore,
          envId = _this$props5.envId;
      var protocol = _this.state.protocol;
      var value = e.target ? e.target.value : e;
      var type = p || protocol;

      if (isModifiedField('domain')) {
        resetFields('certId');
      }

      if (type === 'secret' && envId) {
        DomainStore.loadCertByEnv(projectId, envId, value);
      }
    };

    _this.state = {
      protocol: 'normal',
      pathCountChange: false
    };
    _this.pathKeys = 1;
    return _this;
  }
  /**
   * 添加或删除包含路径的表单项触发路径的校验
   * 确保 新添加 的一组路径已经渲染在页面上
   */


  _createClass(Index, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.state.pathCountChange) {
        this.triggerPathCheck();
      }
    }
    /**
     * 检查名称的唯一性
     * @type {Function}
     */

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props6 = this.props,
          _this$props6$form = _this$props6.form,
          getFieldDecorator = _this$props6$form.getFieldDecorator,
          getFieldValue = _this$props6$form.getFieldValue,
          getFieldsError = _this$props6$form.getFieldsError,
          formatMessage = _this$props6.intl.formatMessage,
          DomainStore = _this$props6.DomainStore,
          envId = _this$props6.envId;
      var protocol = this.state.protocol;
      var getCertificates = DomainStore.getCertificates;
      getFieldDecorator('paths', {
        initialValue: [0]
      });
      var paths = getFieldValue('paths'); // 是否还存在校验未通过的path值

      var pathsError = getFieldsError(_.map(paths, function (item) {
        return "path[".concat(item, "]");
      }));
      var hasPathError = true;

      _.forEach(pathsError, function (pv, pk) {
        if (pv[0]) {
          hasPathError = true;
        } else {
          hasPathError = false;
        }
      }); // 生成路径-网络-端口的表单组


      var pathItem = _.map(paths, function (k, index) {
        return /*#__PURE__*/React.createElement("div", {
          className: "domain-network-wrap",
          key: "paths-".concat(k)
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "domain-network-item c7ncd-domain-path"
        }, formItemLayout), getFieldDecorator("path[".concat(k, "]"), {
          rules: [{
            validator: _this2.checkPath
          }],
          initialValue: '/'
        })( /*#__PURE__*/React.createElement(_Input, {
          onChange: function onChange() {
            return _this2.setState({
              pathCountChange: true
            });
          },
          disabled: !getFieldValue('domain'),
          maxLength: 30,
          label: formatMessage({
            id: 'domain.column.path'
          }),
          size: "default"
        }))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "domain-network-item"
        }, formItemLayout), getFieldDecorator("network[".concat(k, "]"), {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }],
          initialValue: getFieldValue('networkName')
        })( /*#__PURE__*/React.createElement(_Input, {
          disabled: true,
          label: formatMessage({
            id: 'domain.column.network'
          })
        }))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "domain-network-item c7ncd-domain-port"
        }, formItemLayout), getFieldDecorator("netPort[".concat(k, "]"), {
          trigger: ['onChange', 'onSubmit'],
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }, {
            validator: _this2.checkPorts
          }]
        })( /*#__PURE__*/React.createElement(_Select, {
          getPopupContainer: function getPopupContainer(triggerNode) {
            return triggerNode.parentNode;
          },
          disabled: !getFieldValue("network[".concat(k, "]")),
          label: formatMessage({
            id: 'domain.column.port'
          }),
          showSearch: true,
          dropdownMatchSelectWidth: true,
          size: "default",
          optionLabelProp: "children"
        }, _.map(_.filter(getFieldValue('port')), function (item) {
          return /*#__PURE__*/React.createElement(Option, {
            key: item,
            value: item
          }, item);
        })))), paths.length > 1 && /*#__PURE__*/React.createElement(_Button, {
          shape: "circle",
          className: "c7n-domain-icon-delete",
          onClick: _this2.removePath.bind(_this2, k)
        }, /*#__PURE__*/React.createElement("i", {
          className: "icon icon-delete"
        })));
      });

      return /*#__PURE__*/React.createElement(_Form, {
        className: "c7ncd-deploy-domain-form"
      }, /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('domainName', {
        rules: [{
          required: true,
          whitespace: true,
          message: formatMessage({
            id: 'required'
          })
        }, {
          validator: this.checkName
        }]
      })( /*#__PURE__*/React.createElement(_Input, {
        disabled: !envId,
        maxLength: 40,
        label: formatMessage({
          id: 'domain.column.name'
        })
      }))), /*#__PURE__*/React.createElement("div", {
        className: "c7n-protocol-type-title"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "domain.protocol.type"
      })), /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "creation-radio-form",
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ctf.target.type"
        })
      }, formItemLayout), getFieldDecorator('type', {
        initialValue: protocol
      })( /*#__PURE__*/React.createElement(RadioGroup, {
        disabled: !envId,
        name: "type",
        onChange: this.handleTypeChange
      }, /*#__PURE__*/React.createElement(_Radio, {
        value: "normal"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "domain.protocol.normal"
      })), /*#__PURE__*/React.createElement(_Radio, {
        value: "secret"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "domain.protocol.secret"
      }))))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "creation-form-item"
      }, formItemLayout), getFieldDecorator('domain', {
        rules: [{
          required: true,
          whitespace: true,
          message: formatMessage({
            id: 'required'
          })
        }, {
          validator: this.checkDomain
        }]
      })( /*#__PURE__*/React.createElement(_Input, {
        disabled: !envId,
        maxLength: 50,
        type: "text",
        label: formatMessage({
          id: 'domain.form.domain'
        }),
        onBlur: this.loadCertByDomain
      }))), protocol === 'secret' && /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "creation-form-item"
      }, formItemLayout), getFieldDecorator('certId', {
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }]
      })( /*#__PURE__*/React.createElement(_Select, {
        optionFilterProp: "children",
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "domain.form.cert"
        }),
        notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "domain.cert.none"
        }),
        getPopupContainer: function getPopupContainer(triggerNode) {
          return triggerNode.parentNode;
        },
        filterOption: function filterOption(input, option) {
          return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        filter: true,
        showSearch: true
      }, _.map(getCertificates, function (item) {
        return /*#__PURE__*/React.createElement(Option, {
          value: item.id,
          key: item.id
        }, item.certName);
      })))), pathItem, /*#__PURE__*/React.createElement("div", {
        className: "c7n-domain-btn-wrapper"
      }, /*#__PURE__*/React.createElement(_Tooltip, {
        title: hasPathError || !getFieldValue('domain') ? formatMessage({
          id: 'domain.path.isnull'
        }) : ''
      }, /*#__PURE__*/React.createElement(_Button, {
        className: "c7n-domain-btn",
        onClick: this.addPath,
        type: "primary",
        disabled: hasPathError || !getFieldValue('domain'),
        icon: "add"
      }, formatMessage({
        id: 'domain.path.add'
      })))));
    }
  }]);

  return Index;
}(Component)) || _class) || _class) || _class) || _class);
export { Index as default };
Index.defaultProps = {
  type: 'create'
};