import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/lib/Spin";
import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(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 _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, { useEffect, useMemo, useState, Fragment } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl } from 'react-intl';
import { Choerodon } from '@choerodon/boot';
import debounce from 'lodash/debounce';
import { useUpgradeStore } from "./stores";
import { handlePromptError } from "../../../../../../../utils";
import YamlEditor from "../../../../../../../components/yamlEditor";
export default injectIntl(observer(function () {
  var _useUpgradeStore = useUpgradeStore(),
      projectId = _useUpgradeStore.AppState.currentMenuType.projectId,
      formatMessage = _useUpgradeStore.intl.formatMessage,
      store = _useUpgradeStore.store,
      _useUpgradeStore$vo = _useUpgradeStore.vo,
      id = _useUpgradeStore$vo.id,
      parentId = _useUpgradeStore$vo.parentId,
      versionId = _useUpgradeStore$vo.versionId,
      appServiceId = _useUpgradeStore$vo.appServiceId,
      intlPrefix = _useUpgradeStore.intlPrefix,
      prefixCls = _useUpgradeStore.prefixCls,
      refresh = _useUpgradeStore.refresh,
      modal = _useUpgradeStore.modal,
      upgradeDs = _useUpgradeStore.upgradeDs,
      versionsDs = _useUpgradeStore.versionsDs,
      upgradeStore = _useUpgradeStore.upgradeStore,
      valueDs = _useUpgradeStore.valueDs;

  var record = upgradeDs.current;

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      searchValue = _useState2[0],
      setSearchValue = _useState2[1];

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

  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!hasEditorError) {
              _context.next = 2;
              break;
            }

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

          case 2:
            _context.prev = 2;
            _context.next = 5;
            return upgradeDs.submit();

          case 5:
            _context.t0 = _context.sent;

            if (!(_context.t0 !== false)) {
              _context.next = 9;
              break;
            }

            refresh();
            return _context.abrupt("return", true);

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

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

          case 16:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[2, 12]]);
  })));
  useEffect(function () {
    function loadData() {
      return _loadData.apply(this, arguments);
    }

    function _loadData() {
      _loadData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
        var _ref2, newVersionId;

        return regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return loadInitVersion();

              case 2:
                if (versionsDs.totalCount && !versionId) {
                  _ref2 = versionsDs.toData()[0] || {}, newVersionId = _ref2.id;
                  record.set('appServiceVersionId', newVersionId);
                } else {
                  valueDs.setQueryParameter('versionId', versionId);
                  valueDs.query();
                }

              case 3:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));
      return _loadData.apply(this, arguments);
    }

    loadData();
  }, []);

  function loadInitVersion() {
    versionId && versionsDs.setQueryParameter('app_service_version_id', versionId);
    return loadVersions();
  }

  function loadVersions() {
    return _loadVersions.apply(this, arguments);
  }

  function _loadVersions() {
    _loadVersions = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var page,
          res,
          records,
          item,
          loadMoreRecord,
          _args3 = arguments;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              page = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : 1;
              _context3.next = 3;
              return versionsDs.query(page);

            case 3:
              res = _context3.sent;
              records = upgradeStore.getOldVersions;

              if (!(res && !res.failed)) {
                _context3.next = 12;
                break;
              }

              if (!res.isFirstPage) {
                versionsDs.unshift.apply(versionsDs, _toConsumableArray(records));
              }

              item = versionsDs.find(function (r) {
                return r.get('version') === 'more__versions';
              });
              item && versionsDs.remove(item);
              upgradeStore.setOldVersions(versionsDs.records);

              if (res.hasNextPage) {
                loadMoreRecord = versionsDs.create({
                  version: 'more__versions'
                });
                versionsDs.push(loadMoreRecord);
              }

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

            case 12:
              return _context3.abrupt("return", false);

            case 13:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _loadVersions.apply(this, arguments);
  }

  function handleSearchVersion(e) {
    e.persist();
    setSearchValue(e.target.value);
    searchVersion(e.target.value);
  }

  var searchVersion = useMemo(function () {
    return debounce(function (value) {
      versionsDs.setQueryParameter('version', value);

      if (value) {
        versionsDs.setQueryParameter('app_service_version_id', null);
        loadVersions();
      } else {
        loadInitVersion();
      }
    }, 500);
  }, []);

  function handleBlur() {
    setSearchValue('');

    if (searchValue && !versionsDs.totalCount) {
      searchVersion();
    }
  }

  function handleOptionRenderer(_ref3) {
    var text = _ref3.text,
        value = _ref3.value;

    if (text === 'more__versions') {
      return /*#__PURE__*/React.createElement("a", {
        className: "".concat(prefixCls, "-instance-upgrade-select-more"),
        onClick: handleLoadMoreVersion,
        role: "none"
      }, formatMessage({
        id: 'loadMore'
      }));
    }

    return text;
  }

  function handleLoadMoreVersion(e) {
    e.stopPropagation();
    loadVersions(versionsDs.currentPage + 1);
  }

  function handleRenderer(_ref4) {
    var text = _ref4.text,
        value = _ref4.value;

    if (upgradeDs.current && upgradeDs.current.get('appServiceVersionName')) {
      return upgradeDs.current.get('appServiceVersionName');
    }

    if (value === text) {
      return '';
    }

    return text;
  }

  function getValue() {
    var yaml = valueDs && valueDs.current ? valueDs.current.get('yaml') : '';
    var values = record ? record.get('values') : '';
    return /*#__PURE__*/React.createElement(YamlEditor, {
      readOnly: false,
      value: values || yaml || '',
      originValue: yaml,
      handleEnableNext: handleNextStepEnable,
      onValueChange: handleChangeValue
    });
  }

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

  function handleChangeValue(value) {
    record.set('values', value);
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Form, {
    dataSet: upgradeDs
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "appServiceVersionId",
    searchable: true,
    searchMatcher: function searchMatcher() {
      return true;
    },
    onInput: handleSearchVersion,
    onBlur: handleBlur,
    renderer: handleRenderer,
    optionRenderer: handleOptionRenderer,
    clearButton: false,
    className: "".concat(prefixCls, "-instance-upgrade-select"),
    popupCls: "c7ncd-select-menu-item-more-hidden"
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-instance-upgrade-tips")
  }, /*#__PURE__*/React.createElement("strong", null, "\u6CE8\u610F\uFF1A"), /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("br", null), "- \u5728\u53D8\u66F4\u5B9E\u4F8B\u65F6\uFF0CChart\u5305\u5185\u6216\u8005values\u4E2D\u63A7\u5236\u526F\u672C\u6570\u91CF\u7684\u914D\u7F6E\u5C06\u4E0D\u4F1A\u751F\u6548\uFF0C\u800C\u662F\u4F1A\u548C\u73B0\u6709\u751F\u6548\u7684\u5B9E\u4F8B\u7684\u526F\u672C\u6570\u4FDD\u6301\u4E00\u81F4\u3002", /*#__PURE__*/React.createElement("br", null), "- \u82E5\u60F3\u4FEE\u6539\u526F\u672C\u6570\u91CF\uFF0C\u8BF7\u5728\u90E8\u7F72\u540E\u524D\u5F80\u8FD0\u884C\u8BE6\u60C5\u9875\u9762\u4E2D\u66F4\u6539Pod\u6570\u91CF\u5373\u53EF\u3002", /*#__PURE__*/React.createElement("br", null), "- \u4E0B\u65B9values\u4E2D\u5176\u4ED6\u53C2\u6570\u5B57\u6BB5\u4FEE\u6539\u540E\u4F9D\u7136\u4F1A\u751F\u6548\u3002")), /*#__PURE__*/React.createElement(_Spin, {
    spinning: valueDs.status === 'loading'
  }, getValue()));
}));