import "choerodon-ui/lib/upload/style";
import _Upload from "choerodon-ui/lib/upload";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
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";
import "choerodon-ui/lib/select/style";
import _Select from "choerodon-ui/lib/select";
import "choerodon-ui/lib/modal/style";
import _Modal from "choerodon-ui/lib/modal";

var _dec, _dec2, _class;

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

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 InterceptMask from "../../../../../../../components/intercept-mask";
import YamlEditor from "../../../../../../../components/yamlEditor/YamlEditor";
import { handlePromptError } from "../../../../../../../utils";
import "./index.less";
var Sidebar = _Modal.Sidebar;
var Option = _Select.Option;
var FormItem = _Form.Item;
var RadioGroup = _Radio.Group;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var ResourceSidebar = (_dec = _Form.create({}), _dec2 = inject('AppState'), _dec(_class = injectIntl(_class = _dec2(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(ResourceSidebar, _Component);

  var _super = _createSuper(ResourceSidebar);

  function ResourceSidebar() {
    var _this;

    _classCallCheck(this, ResourceSidebar);

    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 = {
      showError: false,
      mode: 'paste',
      changedValue: null,
      hasEditorError: false,
      fileDisabled: false
    };
    _this.handleSubmit = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _this$props, validateFields, store, type, projectId, propsEnv, refresh, _this$state, hasEditorError, changedValue, mode, result, formData, _store$getSingleData, id, envId, data, res;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _this$props = _this.props, validateFields = _this$props.form.validateFields, store = _this$props.store, type = _this$props.type, projectId = _this$props.AppState.currentMenuType.projectId, propsEnv = _this$props.envId, refresh = _this$props.refresh;
              _this$state = _this.state, hasEditorError = _this$state.hasEditorError, changedValue = _this$state.changedValue, mode = _this$state.mode;

              if (!hasEditorError) {
                _context.next = 4;
                break;
              }

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

            case 4:
              if (!(mode === 'paste' && !changedValue)) {
                _context.next = 7;
                break;
              }

              _this.setState({
                showError: true
              });

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

            case 7:
              result = true;
              formData = new FormData();

              if (type === 'edit') {
                _store$getSingleData = store.getSingleData, id = _store$getSingleData.id, envId = _store$getSingleData.envId;
                data = {
                  envId: envId || propsEnv,
                  type: 'update',
                  content: changedValue,
                  resourceId: id
                };

                _.forEach(data, function (value, key) {
                  return formData.append(key, value);
                });
              } else {
                validateFields(function (err, data) {
                  result = !err;

                  if (!err) {
                    var file = data.file;
                    formData.append('envId', propsEnv);
                    formData.append('type', 'create');

                    if (mode === 'paste') {
                      formData.append('content', changedValue);
                    } else {
                      formData.append('contentFile', file.file);
                    }
                  }
                });
              }

              if (result) {
                _context.next = 12;
                break;
              }

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

            case 12:
              _context.prev = 12;
              _context.next = 15;
              return store.createData(projectId, formData);

            case 15:
              res = _context.sent;

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

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

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

            case 21:
              _context.next = 27;
              break;

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

            case 27:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[12, 23]]);
    }));

    _this.checkFile = function (rule, value, callback) {
      var formatMessage = _this.props.intl.formatMessage;

      if (!value) {
        callback(formatMessage({
          id: 'resource.required'
        }));
      } else {
        var name = value.file.name,
            fileList = value.fileList;

        if (!fileList.length) {
          callback(formatMessage({
            id: 'resource.required'
          }));
        } else if (!name.endsWith('.yml')) {
          callback(formatMessage({
            id: 'file.type.error'
          }));
        } else if (fileList.length > 1) {
          callback(formatMessage({
            id: 'resource.one.file'
          }));
        } else {
          callback();
        }
      }
    };

    _this.beforeUpload = function () {
      _this.setState({
        fileDisabled: true
      });

      return false;
    };

    _this.removeFile = function () {
      _this.setState({
        fileDisabled: false
      });
    };

    _this.changeMode = function (e) {
      var modal = _this.props.modal;
      var mode = e.target.value;

      _this.setState({
        changedValue: null,
        hasEditorError: false,
        showError: false,
        mode: mode
      });

      modal.update({
        okProps: {
          disabled: false
        }
      });
    };

    _this.handleChangeValue = function (value) {
      _this.setState({
        changedValue: value,
        showError: false
      });
    };

    _this.handleEnableNext = function (flag) {
      var modal = _this.props.modal;

      _this.setState({
        hasEditorError: flag
      });

      modal.update({
        okProps: {
          disabled: flag
        }
      });
    };

    return _this;
  }

  _createClass(ResourceSidebar, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props2 = this.props,
          store = _this$props2.store,
          projectId = _this$props2.AppState.currentMenuType.projectId,
          type = _this$props2.type,
          id = _this$props2.id,
          modal = _this$props2.modal;

      if (id && type === 'edit') {
        store.loadSingleData(projectId, id);
      }

      modal.handleOk(this.handleSubmit);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var store = this.props.store;
      store.setSingleData({});
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          type = _this$props3.type,
          getFieldDecorator = _this$props3.form.getFieldDecorator,
          formatMessage = _this$props3.intl.formatMessage,
          name = _this$props3.AppState.currentMenuType.name,
          store = _this$props3.store;
      var _this$state2 = this.state,
          changedValue = _this$state2.changedValue,
          fileDisabled = _this$state2.fileDisabled,
          mode = _this$state2.mode,
          showError = _this$state2.showError;
      var _store$getSingleData2 = store.getSingleData,
          resourceName = _store$getSingleData2.name,
          resourceContent = _store$getSingleData2.resourceContent;
      var uploadClass = classnames({
        'c7ncd-upload-select': !fileDisabled,
        'c7ncd-upload-disabled': fileDisabled
      });
      return /*#__PURE__*/React.createElement("div", {
        className: "c7n-region c7ncd-deployment-resource-sidebar"
      }, /*#__PURE__*/React.createElement(_Form, {
        layout: "vertical"
      }, type === 'create' && /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-resource-mode"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-resource-mode-label"
      }, formatMessage({
        id: 'resource.mode'
      }), "\uFF1A"), /*#__PURE__*/React.createElement(RadioGroup, {
        value: mode,
        onChange: this.changeMode
      }, _.map(['paste', 'upload'], function (item) {
        return /*#__PURE__*/React.createElement(_Radio, {
          key: item,
          value: item,
          className: "c7ncd-resource-radio"
        }, formatMessage({
          id: "resource.mode.".concat(item)
        }));
      })))), mode === 'paste' && /*#__PURE__*/React.createElement(YamlEditor, {
        readOnly: false,
        value: changedValue || resourceContent || '',
        originValue: resourceContent || '',
        onValueChange: this.handleChangeValue,
        handleEnableNext: this.handleEnableNext
      }), mode === 'upload' && /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
        className: "c7ncd-resource-upload-item"
      }), getFieldDecorator('file', {
        rules: [{
          validator: this.checkFile
        }]
      })( /*#__PURE__*/React.createElement(_Upload, {
        // action="//jsonplaceholder.typicode.com/posts/"
        disabled: fileDisabled,
        beforeUpload: this.beforeUpload,
        onRemove: this.removeFile
      }, /*#__PURE__*/React.createElement("div", {
        className: uploadClass
      }, /*#__PURE__*/React.createElement(_Icon, {
        className: "c7ncd-resource-upload-icon",
        type: "add"
      }), /*#__PURE__*/React.createElement("div", {
        className: "c7n-resource-upload-text"
      }, "Upload")))))), showError && /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-resource-error"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "contentCanNotBeEmpty"
      })));
    }
  }]);

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