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

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, { useMemo, useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Choerodon } from '@choerodon/boot';
import debounce from 'lodash/debounce';
import forEach from 'lodash/forEach';
import includes from 'lodash/includes';
import CertConfig from "../../../../components/certConfig";
import Tips from "../../../../components/new-tips";
import { handlePromptError } from "../../../../utils";
import "./index.less";
var FormItem = _Form.Item;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};

var CreateForm = function CreateForm(_ref) {
  var certId = _ref.certId,
      formatMessage = _ref.intl.formatMessage,
      form = _ref.form,
      store = _ref.store,
      projectId = _ref.projectId,
      modal = _ref.modal,
      refresh = _ref.refresh,
      intlPrefix = _ref.intlPrefix,
      prefixCls = _ref.prefixCls;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      uploadMode = _useState2[0],
      setUploadMode = _useState2[1];

  var getFieldDecorator = form.getFieldDecorator,
      validateFieldsAndScroll = form.validateFieldsAndScroll;
  var checkName = useMemo(function () {
    return debounce(function (rule, value, callback) {
      var _ref2 = store.getCert || {},
          name = _ref2.name;

      if (value && value !== name) {
        store.checkCertName(projectId, encodeURIComponent(value)).then(function (res) {
          if (res && res.failed || !res) {
            callback(formatMessage({
              id: 'checkNameExist'
            }));
          } else {
            callback();
          }
        })["catch"](function (e) {
          callback(formatMessage({
            id: 'checkNameFailed'
          }));
        });
      } else {
        callback();
      }
    }, 1000);
  }, []);
  useEffect(function () {
    certId && store.loadCertById(projectId, certId);
  }, []);
  /**
   * 域名格式检查
   * @param rule
   * @param value
   * @param callback
   */

  function checkDomain(rule, value, callback) {
    var p = /^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)+)$/;

    if (p.test(value)) {
      callback();
    } else {
      callback(formatMessage({
        id: "".concat(intlPrefix, ".domain.failed")
      }));
    }
  }

  function formValidate() {
    var formData = new FormData();
    return new Promise(function (resolve) {
      validateFieldsAndScroll(function (err, data) {
        if (!err) {
          var excludeProps = ['domainArr', 'cert', 'key'];

          if (uploadMode) {
            var 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);
            }
          });

          if (certId) {
            var _ref3 = store.getCert || {},
                skipCheckProjectPermission = _ref3.skipCheckProjectPermission,
                objectVersionNumber = _ref3.objectVersionNumber,
                id = _ref3.id;

            formData.append('skipCheckProjectPermission', skipCheckProjectPermission);
            formData.append('objectVersionNumber', objectVersionNumber);
            formData.append('id', id);
            formData.append('type', 'update');
          } else {
            formData.append('skipCheckProjectPermission', true);
            formData.append('type', 'create');
          }

          resolve(formData);
        }

        resolve(false);
      });
    });
  } // eslint-disable-next-line consistent-return


  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var formData, res;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return formValidate();

          case 2:
            formData = _context.sent;

            if (formData) {
              _context.next = 5;
              break;
            }

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

          case 5:
            _context.prev = 5;
            _context.next = 8;
            return store.createCert(projectId, formData);

          case 8:
            res = _context.sent;

            if (!handlePromptError(res, false)) {
              _context.next = 13;
              break;
            }

            refresh();
            _context.next = 14;
            break;

          case 13:
            return _context.abrupt("return", false);

          case 14:
            _context.next = 20;
            break;

          case 16:
            _context.prev = 16;
            _context.t0 = _context["catch"](5);
            Choerodon.handleResponseError(_context.t0);
            return _context.abrupt("return", false);

          case 20:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[5, 16]]);
  })));

  function changeUploadMode() {
    setUploadMode(function (pre) {
      return !pre;
    });
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap")
  }, /*#__PURE__*/React.createElement(_Form, {
    layout: "float"
  }, /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('name', {
    rules: [{
      required: true,
      message: formatMessage({
        id: 'required'
      })
    }, {
      validator: checkName
    }],
    initialValue: store.getCert ? store.getCert.name : ''
  })( /*#__PURE__*/React.createElement(_Input, {
    maxLength: 40,
    type: "text",
    label: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".name")
    }),
    autoFocus: true
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap-section")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap-section-title")
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "".concat(intlPrefix, ".upload")
  })), /*#__PURE__*/React.createElement(FormItem, formItemLayout, getFieldDecorator('domain', {
    rules: [{
      required: true,
      message: formatMessage({
        id: 'required'
      })
    }, {
      validator: checkDomain
    }],
    initialValue: store.getCert ? store.getCert.domain : ''
  })( /*#__PURE__*/React.createElement(_Input, {
    type: "text",
    maxLength: 50,
    label: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".domain")
    })
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-create-wrap-add-title")
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Tips, {
    helpText: formatMessage({
      id: "".concat(intlPrefix, ".add.tips")
    }),
    title: formatMessage({
      id: "".concat(intlPrefix, ".add")
    }),
    showHelp: !uploadMode
  })), /*#__PURE__*/React.createElement(_Button, {
    type: "primary",
    funcType: "flat",
    onClick: changeUploadMode
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "".concat(intlPrefix, ".upload.mode")
  }))), CertConfig(uploadMode, form, formatMessage, store.getCert || {}))));
};

export default _Form.create()(injectIntl(observer(CreateForm)));