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";
import "choerodon-ui/lib/modal/style";
import _Modal from "choerodon-ui/lib/modal";

var _dec, _dec2, _class;

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 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 _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 no-underscore-dangle,react/no-access-state-in-setstate */

/* eslint-disable */
import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Content, Choerodon } from '@choerodon/boot';
import _ from 'lodash';
import classnames from 'classnames';
import CertConfig from "../../../../../../../components/certConfig";
import Tips from "../../../../../../../components/Tips/Tips";
import InterceptMask from "../../../../../../../components/intercept-mask";
import { handlePromptError } from "../../../../../../../utils";
import "../../../../../../main.less";
import "./index.less";
var Sidebar = _Modal.Sidebar;
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 CERT_TYPE_REQUEST = 'request';
var CERT_TYPE_UPLOAD = 'upload';
var CERT_TYPE_CHOOSE = 'choose';
var CertificateCreate = (_dec = _Form.create({}), _dec2 = inject('AppState'), _dec(_class = injectIntl(_class = _dec2(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(CertificateCreate, _Component);

  var _super = _createSuper(CertificateCreate);

  function CertificateCreate() {
    var _this;

    _classCallCheck(this, CertificateCreate);

    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 = {
      type: CERT_TYPE_REQUEST,
      submitting: false,
      suffix: null,
      certId: null,
      uploadMode: false
    };
    _this.domainCount = 1;
    _this.checkName = _.debounce(function (rule, value, callback) {
      var formatMessage = _this.props.intl.formatMessage;
      var pattern = /^([a-z0-9]([-a-z0-9]?[a-z0-9])*)$/;

      if (!value) {
        callback();
      }

      if (!pattern.test(value)) {
        callback(formatMessage({
          id: 'ctf.names.check.failed'
        }));
      } else {
        var _this$props = _this.props,
            store = _this$props.store,
            projectId = _this$props.AppState.currentMenuType.id,
            envId = _this$props.envId;
        store.checkCertName(projectId, value, envId).then(function (data) {
          if (data) {
            callback();
          } else {
            callback(formatMessage({
              id: 'ctf.name.check.exist'
            }));
          }
        })["catch"](function () {
          return callback('名称检验失败，请稍后再试！');
        });
      }
    }, 600);

    _this.handleSubmit = function (e) {
      if (e && e.preventDefault) {
        e.preventDefault();
      }

      var _this$props2 = _this.props,
          form = _this$props2.form,
          store = _this$props2.store,
          envId = _this$props2.envId,
          projectId = _this$props2.AppState.currentMenuType.id;
      var _this$state = _this.state,
          suffix = _this$state.suffix,
          uploadMode = _this$state.uploadMode;

      _this.setState({
        submitting: true
      });

      form.validateFieldsAndScroll( /*#__PURE__*/function () {
        var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(err, data) {
          var _data, formData, excludeProps, key, cert, response;

          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (err) {
                    _context.next = 20;
                    break;
                  }

                  _data = _objectSpread({}, data);
                  formData = new FormData();
                  excludeProps = ['domainArr', 'cert', 'key'];
                  _data.domains = _.filter(_data.domains);
                  _data.envId = envId;

                  if (_data.type === CERT_TYPE_CHOOSE) {
                    _data.type = CERT_TYPE_REQUEST;
                    _data.domains = _.map(_data.domains, function (item) {
                      return "".concat(item).concat(suffix);
                    });
                  } else if (_data.type === CERT_TYPE_UPLOAD && uploadMode) {
                    key = data.key, cert = data.cert;
                    formData.append('key', key.file);
                    formData.append('cert', cert.file);
                  }

                  _.forEach(_data, function (value, k) {
                    if (!_.includes(excludeProps, k)) {
                      formData.append(k, value);
                    }
                  });

                  _context.prev = 8;
                  _context.next = 11;
                  return store.createCert(projectId, formData);

                case 11:
                  response = _context.sent;

                  if (handlePromptError(response, false)) {
                    _this.handleClose(true);

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

                  _context.next = 18;
                  break;

                case 15:
                  _context.prev = 15;
                  _context.t0 = _context["catch"](8);

                  _this.setState({
                    submitting: false
                  });

                case 18:
                  _context.next = 21;
                  break;

                case 20:
                  _this.setState({
                    submitting: false
                  });

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

        return function (_x, _x2) {
          return _ref.apply(this, arguments);
        };
      }());
    };

    _this.handleClose = function () {
      var isload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var onClose = _this.props.onClose;
      onClose(isload);
    };

    _this.isUniqCheck = function (value) {
      var getFieldValue = _this.props.form.getFieldValue;

      var keyCount = _.countBy(getFieldValue('domains'));

      return keyCount[value] < 2;
    };

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

      if (type === CERT_TYPE_CHOOSE) {
        pattern = /^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)$/;
      }

      if (!value) callback();

      if (pattern.test(value)) {
        if (_this.isUniqCheck(value)) {
          callback();
        } else {
          callback(formatMessage({
            id: 'ctf.domain.check.repeat'
          }));
        }
      } else {
        callback(formatMessage({
          id: 'ctf.domain.check.failed'
        }));
      }
    };

    _this.addDomain = function () {
      var _this$props$form = _this.props.form,
          getFieldValue = _this$props$form.getFieldValue,
          setFieldsValue = _this$props$form.setFieldsValue;
      var keys = getFieldValue('domainArr');
      var uuid = _this.domainCount;

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

      _this.domainCount = uuid + 1;
      setFieldsValue({
        domainArr: nextKeys
      });
    };

    _this.removeGroup = function (k) {
      var _this$props$form2 = _this.props.form,
          getFieldValue = _this$props$form2.getFieldValue,
          setFieldsValue = _this$props$form2.setFieldsValue,
          validateFields = _this$props$form2.validateFields;
      var keys = getFieldValue('domainArr');
      if (keys.length === 1) return;
      setFieldsValue({
        domainArr: _.filter(keys, function (key) {
          return key !== k;
        })
      });
      setFieldsValue(_defineProperty({}, "domains[".concat(k, "]"), undefined));
      validateFields(['domains'], {
        force: true
      });
    };

    _this.handleTypeChange = function (e) {
      var _this$props3 = _this.props,
          store = _this$props3.store,
          _this$props3$form = _this$props3.form,
          resetFields = _this$props3$form.resetFields,
          setFieldsValue = _this$props3$form.setFieldsValue,
          projectId = _this$props3.AppState.currentMenuType.id;
      var type = e.target.value;

      if (type === CERT_TYPE_CHOOSE) {
        store.loadCert(projectId);
      }

      _this.setState({
        type: type,
        suffix: null,
        certId: null
      });

      resetFields(['domainArr']);
      setFieldsValue({
        'domains[0]': ''
      });
    };

    _this.handleCertSelect = function (value) {
      var store = _this.props.store;
      var cert = store.getCert;

      var data = _.filter(cert, ['id', value]);

      _this.setState({
        suffix: data.length ? ".".concat(data[0].domain) : null,
        certId: value
      });
    };

    _this.changeUploadMode = function () {
      _this.setState({
        uploadMode: !_this.state.uploadMode
      });
    };

    _this.changeDomainValue = _.debounce(function () {
      var validateFields = _this.props.form.validateFields;
      validateFields(['domains'], {
        force: true
      });
    }, 400);
    return _this;
  }

  _createClass(CertificateCreate, [{
    key: "getChooseContent",
    get: function get() {
      var _this$props4 = this.props,
          getFieldDecorator = _this$props4.form.getFieldDecorator,
          formatMessage = _this$props4.intl.formatMessage,
          certs = _this$props4.store.getCert;

      var certOptions = _.map(certs, function (_ref2) {
        var id = _ref2.id,
            name = _ref2.name;
        return /*#__PURE__*/React.createElement(Option, {
          key: id,
          value: id
        }, name);
      });

      return /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-sidebar-select"
      }, /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('certId', {
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }]
      })( /*#__PURE__*/React.createElement(_Select, {
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ctf.choose"
        }),
        placeholder: formatMessage({
          id: 'ctf.choose'
        }),
        optionFilterProp: "children",
        onChange: this.handleCertSelect,
        filterOption: function filterOption(input, option) {
          return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        filter: true
      }, certOptions))), /*#__PURE__*/React.createElement(Tips, {
        type: "form",
        data: "ctf.choose.tips"
      }));
    }
    /**
     * 每当域名输入改变，强制校验所有域名，消除重复域名的报错信息
     */

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

      var _this$props5 = this.props,
          visible = _this$props5.visible,
          form = _this$props5.form,
          formatMessage = _this$props5.intl.formatMessage,
          envs = _this$props5.store.getEnvData,
          envId = _this$props5.envId,
          menuName = _this$props5.AppState.currentMenuType.name,
          modal = _this$props5.modal;
      modal.handleOk(this.handleSubmit.bind(this));
      modal.handleCancel(this.handleClose.bind(this, false));
      var _this$state2 = this.state,
          submitting = _this$state2.submitting,
          type = _this$state2.type,
          suffix = _this$state2.suffix,
          certId = _this$state2.certId,
          uploadMode = _this$state2.uploadMode;
      var getFieldDecorator = form.getFieldDecorator,
          getFieldValue = form.getFieldValue;
      getFieldDecorator('domainArr', {
        initialValue: [0]
      });
      var domainArr = getFieldValue('domainArr');
      var isDomainGroup = domainArr.length > 1;

      var domainItems = _.map(domainArr, function (k) {
        return /*#__PURE__*/React.createElement("div", {
          key: "domains-".concat(k),
          className: "creation-panel-group c7n-form-domains"
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          className: "creation-form-item c7ncd-certificate-form-domain"
        }, formItemLayout), getFieldDecorator("domains[".concat(k, "]"), {
          rules: [{
            required: true,
            message: formatMessage({
              id: 'required'
            })
          }, {
            validator: _this2.checkDomain
          }]
        })( /*#__PURE__*/React.createElement(_Input, {
          type: "text",
          maxLength: 50,
          suffix: suffix,
          label: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "ctf.config.domain"
          }),
          disabled: type === 'choose' && !certId,
          onChange: _this2.changeDomainValue
        }))), isDomainGroup ? /*#__PURE__*/React.createElement(_Icon, {
          className: "creation-panel-icon",
          type: "delete",
          onClick: function onClick() {
            return _this2.removeGroup(k);
          }
        }) : null);
      });

      return this.props.pro ? /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-deployment-ctf-create sidebar-content"
      }, /*#__PURE__*/React.createElement(_Form, {
        layout: "vertical"
      }, /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('certName', {
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }, {
          validator: this.checkName
        }]
      })( /*#__PURE__*/React.createElement(_Input, {
        autoFocus: true,
        maxLength: 40,
        type: "text",
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ctf.name"
        })
      }))), /*#__PURE__*/React.createElement("div", {
        className: "c7n-creation-title"
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "settings"
      }), /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.config"
      })), /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ctf.target.type"
        })
      }, formItemLayout), getFieldDecorator('type', {
        initialValue: CERT_TYPE_REQUEST
      })( /*#__PURE__*/React.createElement(RadioGroup, {
        name: "type",
        onChange: this.handleTypeChange
      }, /*#__PURE__*/React.createElement(_Radio, {
        value: CERT_TYPE_REQUEST
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.apply"
      })), /*#__PURE__*/React.createElement(_Radio, {
        value: CERT_TYPE_UPLOAD
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.upload"
      })), /*#__PURE__*/React.createElement(_Radio, {
        value: CERT_TYPE_CHOOSE
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.choose"
      }))))), /*#__PURE__*/React.createElement("div", {
        className: "c7n-creation-panel"
      }, type === 'choose' && this.getChooseContent, domainItems, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "creation-panel-button"
      }, formItemLayout), /*#__PURE__*/React.createElement(_Button, {
        type: "primary",
        funcType: "flat",
        onClick: this.addDomain,
        icon: "add"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.config.add"
      }))), type === CERT_TYPE_UPLOAD && /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement("div", {
        className: "ctf-upload-head"
      }, /*#__PURE__*/React.createElement(Tips, {
        type: "title",
        data: "certificate.file.add",
        help: !uploadMode
      }), /*#__PURE__*/React.createElement(_Button, {
        type: "primary",
        funcType: "flat",
        onClick: this.changeUploadMode
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ctf.upload.mode"
      }))), CertConfig(uploadMode, form, formatMessage)))), /*#__PURE__*/React.createElement(InterceptMask, {
        visible: submitting
      })) : /*#__PURE__*/React.createElement("div", {
        className: "c7n-region"
      }, /*#__PURE__*/React.createElement(Sidebar, {
        destroyOnClose: true,
        cancelText: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "cancel"
        }),
        okText: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "create"
        }),
        title: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ctf.sidebar.create"
        }),
        visible: visible,
        onOk: this.handleSubmit,
        onCancel: this.handleClose.bind(this, false),
        confirmLoading: submitting,
        maskClosable: false,
        width: 380,
        className: "c7ncd-addcerModal"
      }));
    }
  }]);

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