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/pro/lib/radio/style";
import _Radio from "choerodon-ui/pro/lib/radio";
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, { Component, Fragment, useState, useEffect } from 'react';
import { inject } from 'mobx-react';
import { observer } from 'mobx-react-lite';
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 FormItem = _Form.Item; // const { Group: RadioGroup } = Radio;

var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var ResourceSidebar = injectIntl(inject('AppState')(observer(function (props) {
  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      showError = _useState2[0],
      setShowError = _useState2[1];

  var _useState3 = useState('paste'),
      _useState4 = _slicedToArray(_useState3, 2),
      mode = _useState4[0],
      setMode = _useState4[1];

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      changedValue = _useState6[0],
      setChangedValue = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      hasEditorError = _useState8[0],
      setHasEditorError = _useState8[1];

  var _useState9 = useState(false),
      _useState10 = _slicedToArray(_useState9, 2),
      fileDisabled = _useState10[0],
      setFileDisabled = _useState10[1];

  useEffect(function () {
    var store = props.store,
        projectId = props.AppState.currentMenuType.projectId,
        type = props.type,
        id = props.id,
        modal = props.modal;

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

    modal.handleOk(handleSubmit);
    return function () {
      store.setSingleData({});
    };
  }, [changedValue]);

  var handleSubmit = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var validateFields, store, type, projectId, propsEnv, refresh, result, formData, _store$getSingleData, id, envId, data, res;

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

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

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

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

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

            case 6:
              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 = 11;
                break;
              }

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

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

            case 14:
              res = _context.sent;

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

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

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

            case 20:
              _context.next = 26;
              break;

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

            case 26:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[11, 22]]);
    }));

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

  var checkFile = function checkFile(rule, value, callback) {
    var formatMessage = 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') && !_name.endsWith('.yaml')) {
        callback(formatMessage({
          id: 'file.type.error'
        }));
      } else if (fileList.length > 1) {
        callback(formatMessage({
          id: 'resource.one.file'
        }));
      } else {
        callback();
      }
    }
  };

  var beforeUpload = function beforeUpload() {
    setFileDisabled(true);
    return false;
  };

  var removeFile = function removeFile() {
    setFileDisabled(false);
  };
  /**
   * 切换添加模式
   * @param e
   */


  var changeMode = function changeMode(value, oldValue) {
    var modal = props.modal;
    var modeCurrent = value;
    setChangedValue(null);
    setHasEditorError(false);
    setShowError(false);
    setFileDisabled(false);
    setMode(modeCurrent);
    modal.update({
      okProps: {
        disabled: false
      }
    });
  };

  var handleChangeValue = function handleChangeValue(value) {
    setChangedValue(value);
    setShowError(false);
  };

  var handleEnableNext = function handleEnableNext(flag) {
    var modal = props.modal;
    setHasEditorError(flag);
    modal.update({
      okProps: {
        disabled: flag
      }
    });
  };

  var type = props.type,
      getFieldDecorator = props.form.getFieldDecorator,
      formatMessage = props.intl.formatMessage,
      name = props.AppState.currentMenuType.name,
      store = props.store;
  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"), _.map(['paste', 'upload'], function (item) {
    return /*#__PURE__*/React.createElement(_Radio, {
      name: "addMode",
      key: item,
      value: item,
      checked: mode === item,
      onChange: changeMode,
      className: "c7ncd-resource-radio"
    }, formatMessage({
      id: "resource.mode.".concat(item)
    }));
  }))), mode === 'paste' && /*#__PURE__*/React.createElement(YamlEditor, {
    readOnly: false,
    value: changedValue || resourceContent || '',
    originValue: resourceContent || '',
    onValueChange: handleChangeValue,
    handleEnableNext: handleEnableNext
  }), mode === 'upload' && /*#__PURE__*/React.createElement(FormItem, Object.assign({}, formItemLayout, {
    className: "c7ncd-resource-upload-item"
  }), getFieldDecorator('file', {
    rules: [{
      validator: checkFile
    }]
  })( /*#__PURE__*/React.createElement(_Upload, {
    // action="//jsonplaceholder.typicode.com/posts/"
    accept: ".yml, .yaml",
    disabled: fileDisabled,
    beforeUpload: beforeUpload,
    onRemove: 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"
  })));
})));
export default _Form.create()(ResourceSidebar);