import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/lib/Spin";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/lib/select/style";
import _Select from "choerodon-ui/lib/select";

var _dec, _class;

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

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 { Choerodon } from '@choerodon/boot';
import _ from 'lodash';
import YamlEditor from "../../../../../../../components/yamlEditor";
import InterceptMask from "../../../../../../../components/intercept-mask";
import { handlePromptError } from "../../../../../../../utils";
import "./index.less";
var Option = _Select.Option;
var Upgrade = (_dec = inject('AppState'), injectIntl(_class = _dec(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(Upgrade, _Component);

  var _super = _createSuper(Upgrade);

  function Upgrade() {
    var _this;

    _classCallCheck(this, Upgrade);

    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 = {
      versionId: undefined,
      values: '',
      loading: false,
      submitting: false,
      hasEditorError: false,
      idArr: {},
      versionLoading: false,
      versionOptions: [],
      versions: [],
      versionPageNum: 2
    };

    _this.handleLoadVersion = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(appId) {
        var param,
            init,
            shouldLoadValue,
            _this$props,
            projectId,
            store,
            vo,
            data,
            hasNextPage,
            list,
            versionOptions,
            loadMoreBtn,
            id,
            parentId,
            _parentId$split,
            _parentId$split2,
            envId,
            newIdArr,
            _args = arguments;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                param = _args.length > 1 && _args[1] !== undefined ? _args[1] : '';
                init = _args.length > 2 && _args[2] !== undefined ? _args[2] : '';
                shouldLoadValue = _args.length > 3 && _args[3] !== undefined ? _args[3] : false;
                _this$props = _this.props, projectId = _this$props.AppState.currentMenuType.id, store = _this$props.store, vo = _this$props.vo;

                _this.setState({
                  versionLoading: true
                });

                _context.prev = 5;
                _context.next = 8;
                return store.loadUpVersion({
                  projectId: projectId,
                  appId: appId,
                  page: 1,
                  param: param,
                  init: init
                });

              case 8:
                data = _context.sent;

                if (handlePromptError(data)) {
                  hasNextPage = data.hasNextPage, list = data.list;
                  versionOptions = _this.renderVersionOptions(list);

                  if (hasNextPage) {
                    // 在选项最后置入一个加载更多按钮
                    loadMoreBtn = renderLoadMoreBtn(_this.handleLoadMoreVersion);
                    versionOptions.push(loadMoreBtn);
                  }

                  _this.setState({
                    versionOptions: versionOptions,
                    versions: list,
                    versionLoading: false
                  });

                  if (shouldLoadValue) {
                    id = vo.id, parentId = vo.parentId;
                    _parentId$split = parentId.split('**'), _parentId$split2 = _slicedToArray(_parentId$split, 1), envId = _parentId$split2[0];
                    newIdArr = {
                      appInstanceId: id,
                      environmentId: envId,
                      appId: appId,
                      appVersionId: list[0].id
                    };

                    _this.setState({
                      idArr: newIdArr
                    });

                    _this.handleVersionChange(list[0].id);
                  }
                }

                _context.next = 15;
                break;

              case 12:
                _context.prev = 12;
                _context.t0 = _context["catch"](5);

                _this.setState({
                  versionLoading: false
                });

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

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

    _this.renderVersionOptions = function (versions) {
      var _this$props2 = _this.props,
          formatMessage = _this$props2.intl.formatMessage,
          intlPrefix = _this$props2.intlPrefix,
          versionId = _this$props2.vo.versionId;
      return _.map(versions, function (_ref2, index) {
        var id = _ref2.id,
            version = _ref2.version;
        return /*#__PURE__*/React.createElement(Option, {
          key: id,
          value: id
        }, version, id === versionId && " (".concat(formatMessage({
          id: "".concat(intlPrefix, ".instance.current.version")
        }), ")"));
      });
    };

    _this.handleVersionSearch = _.debounce(function (value) {
      var idArr = _this.state.idArr;
      var versionId = _this.props.vo.versionId;

      _this.setState({
        versionSearchParam: value,
        versionPageNum: 2
      });

      _this.handleLoadVersion(idArr.appId, value, value ? '' : versionId);
    }, 500);

    _this.handleLoadMoreVersion = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(e) {
        var _this$props3, projectId, store, _this$state, versionId, versionOptions, versions, appId, versionPageNum, versionSearchParam, data, hasNextPage, list, moreVersion, options, newVersionOpt, newVersions;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                e.stopPropagation();
                _this$props3 = _this.props, projectId = _this$props3.AppState.currentMenuType.projectId, store = _this$props3.store;
                _this$state = _this.state, versionId = _this$state.versionId, versionOptions = _this$state.versionOptions, versions = _this$state.versions, appId = _this$state.idArr.appId, versionPageNum = _this$state.versionPageNum, versionSearchParam = _this$state.versionSearchParam;

                _this.setState({
                  versionLoading: true
                });

                _context2.next = 6;
                return store.loadUpVersion({
                  projectId: projectId,
                  appId: appId,
                  page: versionPageNum,
                  param: versionSearchParam
                })["catch"](function () {
                  _this.setState({
                    versionLoading: false
                  });
                });

              case 6:
                data = _context2.sent;

                if (handlePromptError(data)) {
                  hasNextPage = data.hasNextPage, list = data.list;
                  moreVersion = _.filter(list, function (_ref4) {
                    var id = _ref4.id;
                    return id !== versionId;
                  });
                  options = _this.renderVersionOptions(moreVersion);
                  /**
                   * 触发此事件说明初次渲染的选项versionOptions中的最后一个肯定是 “展开更多” 按钮
                   * 可以先将该按钮使用 initial 方法从原来去除
                   * 如果当前页页码仍然小于总页数，再讲该按钮放回到新的选项的最后
                   */

                  newVersionOpt = _.concat(_.initial(versionOptions), options, hasNextPage ? _.last(versionOptions) : []);
                  newVersions = _.concat(versions, moreVersion);

                  _this.setState({
                    versionOptions: newVersionOpt,
                    versions: newVersions,
                    versionLoading: false,
                    versionPageNum: versionPageNum + 1
                  });
                }

              case 8:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

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

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

      _this.setState({
        hasEditorError: flag
      });

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

    _this.handleChangeValue = function (values) {
      return _this.setState({
        values: values
      });
    };

    _this.handleOk = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var _this$props4, store, projectId, refresh, _this$state2, values, versionId, _this$state2$idArr, appInstanceId, environmentId, appId, appVersionId, verId, _ref6, yaml, data, result;

      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              if (!_this.state.hasEditorError) {
                _context3.next = 2;
                break;
              }

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

            case 2:
              _this.setState({
                submitting: true
              });

              _this$props4 = _this.props, store = _this$props4.store, projectId = _this$props4.AppState.currentMenuType.projectId, refresh = _this$props4.refresh;
              _this$state2 = _this.state, values = _this$state2.values, versionId = _this$state2.versionId, _this$state2$idArr = _this$state2.idArr, appInstanceId = _this$state2$idArr.appInstanceId, environmentId = _this$state2$idArr.environmentId, appId = _this$state2$idArr.appId, appVersionId = _this$state2$idArr.appVersionId;
              verId = versionId || appVersionId;
              _ref6 = store.getUpgradeValue || {}, yaml = _ref6.yaml;
              data = {
                values: values || yaml || '',
                appServiceVersionId: verId,
                type: 'update',
                instanceId: appInstanceId,
                environmentId: environmentId,
                appServiceId: appId
              };
              _context3.prev = 8;
              _context3.next = 11;
              return store.upgrade(projectId, data);

            case 11:
              result = _context3.sent;

              if (handlePromptError(result)) {
                Choerodon.prompt('变更成功');
                refresh();
              } else {
                Choerodon.prompt('变更失败');
              }

              _context3.next = 18;
              break;

            case 15:
              _context3.prev = 15;
              _context3.t0 = _context3["catch"](8);
              Choerodon.handleResponseError(_context3.t0);

            case 18:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[8, 15]]);
    }));

    _this.handleVersionChange = /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(id) {
        var _this$props5, store, projectId, appInstanceId, result;

        return regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _this$props5 = _this.props, store = _this$props5.store, projectId = _this$props5.AppState.currentMenuType.projectId, appInstanceId = _this$props5.vo.id;

                _this.setState({
                  loading: true
                });

                _context4.prev = 2;
                _context4.next = 5;
                return store.loadValue(projectId, appInstanceId, id);

              case 5:
                result = _context4.sent;

                if (handlePromptError(result)) {
                  _this.setState({
                    versionId: id,
                    values: null,
                    loading: false
                  });
                }

                _context4.next = 12;
                break;

              case 9:
                _context4.prev = 9;
                _context4.t0 = _context4["catch"](2);

                _this.setState({
                  loading: false
                });

              case 12:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, null, [[2, 9]]);
      }));

      return function (_x3) {
        return _ref7.apply(this, arguments);
      };
    }();

    return _this;
  }

  _createClass(Upgrade, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props6 = this.props,
          modal = _this$props6.modal,
          _this$props6$vo = _this$props6.vo,
          parentId = _this$props6$vo.parentId,
          versionId = _this$props6$vo.versionId,
          appServiceId = _this$props6$vo.appServiceId;
      modal.handleOk(this.handleOk);
      this.handleLoadVersion(appServiceId, '', versionId, true);
    }
    /**
     * 加载版本
     * @param appId
     * @param param 搜索内容
     * @param init 版本id 需要在列表中的版本
     * @param shouldLoadValue 是否需要加载value
     */

  }, {
    key: "render",
    value: function render() {
      var _this$props7 = this.props,
          formatMessage = _this$props7.intl.formatMessage,
          store = _this$props7.store,
          intlPrefix = _this$props7.intlPrefix,
          prefixCls = _this$props7.prefixCls;
      var _this$state3 = this.state,
          values = _this$state3.values,
          submitting = _this$state3.submitting,
          loading = _this$state3.loading,
          versionId = _this$state3.versionId,
          versionOptions = _this$state3.versionOptions,
          versions = _this$state3.versions,
          versionLoading = _this$state3.versionLoading;
      var _store$getUpgradeValu = store.getUpgradeValue,
          name = _store$getUpgradeValu.name,
          yaml = _store$getUpgradeValu.yaml;
      return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(_Select, {
        filter: true,
        className: "".concat(prefixCls, "-version-select"),
        label: formatMessage({
          id: "".concat(intlPrefix, ".modal.version")
        }),
        notFoundContent: formatMessage({
          id: "".concat(intlPrefix, ".modal.version.empty")
        }),
        loading: versionLoading,
        filterOption: false,
        onSearch: this.handleVersionSearch,
        onChange: this.handleVersionChange,
        value: versionId || (versions.length ? versions[0].id : undefined)
      }, versionOptions), /*#__PURE__*/React.createElement(_Spin, {
        spinning: loading
      }, /*#__PURE__*/React.createElement(YamlEditor, {
        readOnly: false,
        value: values || yaml || '',
        originValue: yaml,
        handleEnableNext: this.handleNextStepEnable,
        onValueChange: this.handleChangeValue
      })), /*#__PURE__*/React.createElement(InterceptMask, {
        visible: submitting
      }));
    }
  }]);

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

function renderLoadMoreBtn(handler) {
  return /*#__PURE__*/React.createElement(Option, {
    disabled: true,
    className: "c7ncd-more-btn-wrap",
    key: "btn_load_more"
  }, /*#__PURE__*/React.createElement(_Button, {
    type: "default",
    className: "c7ncd-more-btn",
    onClick: handler
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "loadMore"
  })));
}