import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/select-box/style";
import _SelectBox from "choerodon-ui/pro/lib/select-box";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

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, { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import get from 'lodash/get';
import { mapping } from "./stores/ManualDeployDataSet";
import YamlEditor from "../../../../components/yamlEditor";
import StatusDot from "../../../../components/status-dot";
import Tips from "../../../../components/new-tips";
import NetworkForm from "./NetworkForm";
import DomainForm from "./DomainForm";
import HostDeployForm from "./HostDeployForm";
import { useManualDeployStore } from "./stores";
import "./index.less";
var Option = _Select.Option,
    OptGroup = _Select.OptGroup;
var DeployModal = observer(function () {
  var _useManualDeployStore = useManualDeployStore(),
      manualDeployDs = _useManualDeployStore.manualDeployDs,
      deployStore = _useManualDeployStore.deployStore,
      refresh = _useManualDeployStore.refresh,
      intlPrefix = _useManualDeployStore.intlPrefix,
      prefixCls = _useManualDeployStore.prefixCls,
      modal = _useManualDeployStore.modal,
      formatMessage = _useManualDeployStore.intl.formatMessage,
      envId = _useManualDeployStore.envId,
      history = _useManualDeployStore.history,
      search = _useManualDeployStore.location.search,
      marketAndVersionOptionsDs = _useManualDeployStore.marketAndVersionOptionsDs,
      hasDevops = _useManualDeployStore.hasDevops,
      hasMarket = _useManualDeployStore.hasMarket,
      isSaaS = _useManualDeployStore.isSaaS;

  var record = manualDeployDs.current;

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

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

  var _useState5 = useState(true),
      _useState6 = _slicedToArray(_useState5, 2),
      netIsExpand = _useState6[0],
      setNetIsExpand = _useState6[1];

  var _useState7 = useState(true),
      _useState8 = _slicedToArray(_useState7, 2),
      ingressIsExpand = _useState8[0],
      setIngressIsExpand = _useState8[1];

  var optionLoading = useMemo(function () {
    return /*#__PURE__*/React.createElement(Option, {
      value: "loading"
    }, /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-select-option-loading",
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      role: "none"
    }, /*#__PURE__*/React.createElement(_Spin, null)));
  }, []);
  useEffect(function () {
    if (envId) {
      record.init('environmentId', envId);
    }
  }, [envId]);
  useEffect(function () {
    ChangeConfigValue(deployStore.getConfigValue);
  }, [deployStore.getConfigValue]); // eslint-disable-next-line consistent-return

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

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

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

          case 5:
            res = _context.sent;

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

            refresh(res.list[0]);
            return _context.abrupt("return", true);

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

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

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

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

  function handleEnableNext(flag) {
    setHasYamlFailed(flag);
  }

  function renderEnvOption(_ref2) {
    var envRecord = _ref2.record,
        text = _ref2.text,
        value = _ref2.value;
    return /*#__PURE__*/React.createElement(React.Fragment, null, value && /*#__PURE__*/React.createElement(StatusDot, {
      connect: envRecord.get('connect'),
      synchronize: envRecord.get('synchro'),
      active: envRecord.get('active'),
      size: "small"
    }), /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-select-option-text")
    }, text));
  }

  function renderOptionProperty(_ref3) {
    var envRecord = _ref3.record;
    var isAvailable = envRecord.get('connect') && envRecord.get('synchro') && envRecord.get('permission');
    return {
      disabled: !isAvailable
    };
  }

  function handleExpand(Operating) {
    Operating(function (pre) {
      return !pre;
    });
  }

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

    if (value && value['group-0'] && value.meaning) {
      return "".concat(value['group-0'], "-").concat(value.meaning);
    }

    return text;
  }

  function renderSearchMatcher(_ref5) {
    var _eachRecord$get, _eachRecord$get2;

    var eachRecord = _ref5.record,
        text = _ref5.text,
        textField = _ref5.textField;
    return ((_eachRecord$get = eachRecord.get(textField)) === null || _eachRecord$get === void 0 ? void 0 : _eachRecord$get.indexOf(text)) !== -1 || eachRecord.get('group-0') && ((_eachRecord$get2 = eachRecord.get('group-0')) === null || _eachRecord$get2 === void 0 ? void 0 : _eachRecord$get2.indexOf(text)) !== -1;
  }

  function getMarketItem() {
    var colSpan = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
    var marketAppId = get(record.get('marketService'), 'marketAppId');
    var href = "".concat(window.location.origin, "/#/market/app-market/app-detail/").concat(marketAppId).concat(search);
    return [/*#__PURE__*/React.createElement(_Select, {
      name: "marketAppAndVersion",
      searchable: true,
      newLine: true,
      colSpan: colSpan,
      renderer: renderMarketApp,
      searchMatcher: renderSearchMatcher,
      addonAfter: /*#__PURE__*/React.createElement(Tips, {
        helpText: "\u6B64\u5904\u4F1A\u663E\u793A\u51FA\u5E94\u7528\u5E02\u573A\u4E2D\u6240\u6709\u5DF2\u4E0A\u7EBF\u7684\u5E02\u573A\u5E94\u7528\u53CA\u5176\u7248\u672C\u3002"
      })
    }, getMarketAndVersionContent()), /*#__PURE__*/React.createElement(_Select, {
      name: "marketService",
      disabled: !record.get('marketAppAndVersion'),
      searchable: true,
      colSpan: colSpan,
      addonAfter: /*#__PURE__*/React.createElement(Tips, {
        helpText: function helpText() {
          return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, " \u6B64\u5904\u4F1A\u663E\u793A\u51FA\u6240\u9009\u5E02\u573A\u5E94\u7528\u7248\u672C\u4E2D\u5BF9\u5E94\u7684\u6240\u6709\u53D1\u5E03\u4E86\u90E8\u7F72\u5305\u7684\u5E02\u573A\u670D\u52A1\u53CA\u5176\u5BF9\u5E94\u7684\u7248\u672C\u3002"), /*#__PURE__*/React.createElement("p", null, "\u82E5\u60F3\u67E5\u770B\u6240\u9009\u5E02\u573A\u670D\u52A1\u53CA\u7248\u672C\u4E2D\u542B\u6709\u7684\u5E94\u7528\u670D\u52A1\u4FE1\u606F\uFF0C\u70B9\u51FB\u53F3\u4FA7\u7684\u300C\u67E5\u770B\u7248\u672C\u8BE6\u60C5\u300D\u6309\u94AE\u8DF3\u8F6C\u67E5\u770B\u5373\u53EF\u3002"));
        }
      })
    }), /*#__PURE__*/React.createElement(_Button, {
      className: "".concat(prefixCls, "-manual-deploy-market-btn"),
      disabled: !record.get('marketService')
    }, marketAppId ? /*#__PURE__*/React.createElement("a", {
      href: href,
      rel: "nofollow me noopener noreferrer",
      target: "_blank",
      className: "".concat(prefixCls, "-manual-deploy-market-btn-link")
    }, "\u67E5\u770B\u7248\u672C\u8BE6\u60C5") : /*#__PURE__*/React.createElement("span", null, "\u67E5\u770B\u7248\u672C\u8BE6\u60C5"))];
  }

  function getMarketAndVersionContent() {
    if (marketAndVersionOptionsDs.status === 'loading') {
      return optionLoading;
    }

    return marketAndVersionOptionsDs.map(function (marketRecord) {
      return /*#__PURE__*/React.createElement(OptGroup, {
        label: marketRecord.get('name'),
        key: marketRecord.get('id')
      }, map(marketRecord.get('appVersionVOS') || [], function (item) {
        return /*#__PURE__*/React.createElement(Option, {
          value: item,
          key: item.id
        }, item.versionNumber);
      }));
    });
  }

  function handleOptionProps(_ref6) {
    var optionRecord = _ref6.record;
    return {
      disabled: optionRecord.get('value') === 'normal_service' && !hasDevops || optionRecord.get('value') === 'market_service' && !hasMarket
    };
  }

  function getAppServiceOptions() {
    if (deployStore.getAppServiceLoading || !record) {
      return optionLoading;
    }

    return record.get('appServiceSource') === 'normal_service' ? map(deployStore.getAppService[0] && deployStore.getAppService[0].appServiceList, function (_ref7) {
      var id = _ref7.id,
          name = _ref7.name,
          code = _ref7.code;
      return /*#__PURE__*/React.createElement(Option, {
        value: "".concat(id, "**").concat(code),
        key: id
      }, "".concat(name, "(").concat(code, ")"));
    }) : map(deployStore.getAppService, function (_ref8) {
      var groupId = _ref8.id,
          groupName = _ref8.name,
          appServiceList = _ref8.appServiceList;
      return /*#__PURE__*/React.createElement(OptGroup, {
        label: groupName,
        key: groupId
      }, map(appServiceList, function (_ref9) {
        var id = _ref9.id,
            name = _ref9.name,
            code = _ref9.code;
        return /*#__PURE__*/React.createElement(Option, {
          value: "".concat(id, "**").concat(code),
          key: id
        }, "".concat(name, "(").concat(code, ")"));
      }));
    });
  }

  var renderRestForm = function renderRestForm() {
    return record.get(mapping.deployWay.value) === mapping.deployWay.options[0].value ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".source.tips")
      }),
      title: formatMessage({
        id: "".concat(intlPrefix, ".source")
      })
    }), /*#__PURE__*/React.createElement(_Form, {
      className: "c7ncd-deploy-content-appService",
      record: record,
      columns: 3
    }, /*#__PURE__*/React.createElement(_SelectBox, {
      name: "appServiceSource",
      colSpan: 1,
      onOption: handleOptionProps
    }, /*#__PURE__*/React.createElement(Option, {
      value: "normal_service"
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: hasDevops ? '' : '仅【DevOps流程】项目类型支持部署本项目应用服务'
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-manual-deploy-radio")
    }, formatMessage({
      id: "".concat(intlPrefix, ".source.project")
    })))), /*#__PURE__*/React.createElement(Option, {
      value: "share_service"
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-manual-deploy-radio")
    }, formatMessage({
      id: "".concat(intlPrefix, ".source.organization")
    }))), !isSaaS ? /*#__PURE__*/React.createElement(Option, {
      value: "market_service"
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      title: hasMarket ? '' : '未安装【应用市场】插件，无法使用此功能'
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-manual-deploy-radio")
    }, formatMessage({
      id: "".concat(intlPrefix, ".source.market")
    })))) : null), record.get('appServiceSource') === 'market_service' ? getMarketItem() : [/*#__PURE__*/React.createElement(_Select, {
      name: "appServiceId",
      searchable: true,
      newLine: record.get('appServiceSource') !== 'market_service',
      notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".app.empty")
      }),
      searchMatcher: renderSearchMatcher
    }, getAppServiceOptions()), /*#__PURE__*/React.createElement(_Select, {
      name: "appServiceVersionId",
      searchable: true,
      searchMatcher: "version",
      disabled: !record.get('appServiceId')
    })], !envId ? /*#__PURE__*/React.createElement(_Select, {
      name: "environmentId",
      searchable: true,
      newLine: true,
      optionRenderer: renderEnvOption,
      notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".env.empty")
      }),
      onOption: renderOptionProperty
    }) : null, /*#__PURE__*/React.createElement(_TextField, {
      name: "instanceName",
      addonAfter: /*#__PURE__*/React.createElement(Tips, {
        helpText: formatMessage({
          id: "".concat(intlPrefix, ".instance.tips")
        })
      }),
      colSpan: !envId ? 1 : 2,
      newLine: !!envId
    }), record.get('appServiceSource') !== 'market_service' && /*#__PURE__*/React.createElement(_Select, {
      name: "valueId",
      searchable: true,
      colSpan: 2,
      newLine: true,
      clearButton: true,
      addonAfter: /*#__PURE__*/React.createElement(Tips, {
        helpText: formatMessage({
          id: "".concat(intlPrefix, ".config.tips")
        })
      }),
      notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".config.empty")
      })
    }), /*#__PURE__*/React.createElement(YamlEditor, {
      colSpan: 3,
      newLine: true,
      readOnly: false,
      originValue: deployStore.getConfigValue,
      value: record.get('values') || deployStore.getConfigValue,
      onValueChange: ChangeConfigValue,
      handleEnableNext: handleEnableNext
    })), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-resource-config")
    }, /*#__PURE__*/React.createElement("div", {
      role: "none",
      className: "".concat(prefixCls, "-resource-config-title"),
      onClick: function onClick() {
        return handleExpand(setResourceIsExpand);
      }
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".resource")
    }), /*#__PURE__*/React.createElement(_Icon, {
      type: resourceIsExpand ? 'expand_less' : 'expand_more',
      className: "".concat(prefixCls, "-resource-config-icon")
    })), /*#__PURE__*/React.createElement("div", {
      className: resourceIsExpand ? '' : "".concat(prefixCls, "-resource-display")
    }, /*#__PURE__*/React.createElement("div", {
      role: "none",
      className: "".concat(prefixCls, "-resource-config-network"),
      onClick: function onClick() {
        return handleExpand(setNetIsExpand);
      }
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: netIsExpand ? 'expand_less' : 'expand_more',
      className: "".concat(prefixCls, "-resource-config-network-icon")
    }), /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".network")
    })), /*#__PURE__*/React.createElement("div", {
      className: netIsExpand ? "".concat(prefixCls, "-resource-content") : "".concat(prefixCls, "-resource-display")
    }, /*#__PURE__*/React.createElement(NetworkForm, null)), /*#__PURE__*/React.createElement("div", {
      role: "none",
      className: "".concat(prefixCls, "-resource-config-network"),
      onClick: function onClick() {
        return handleExpand(setIngressIsExpand);
      }
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: ingressIsExpand ? 'expand_less' : 'expand_more',
      className: "".concat(prefixCls, "-resource-config-network-icon")
    }), /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".ingress")
    })), /*#__PURE__*/React.createElement("div", {
      className: ingressIsExpand ? "".concat(prefixCls, "-resource-content") : "".concat(prefixCls, "-resource-display")
    }, /*#__PURE__*/React.createElement(DomainForm, null))))) : /*#__PURE__*/React.createElement(HostDeployForm, {
      getMarketItem: getMarketItem
    });
  };

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-manual-deploy")
  }, /*#__PURE__*/React.createElement(_Form, {
    record: record,
    columns: 3
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    colSpan: 1,
    name: mapping.deployWay.value
  }, mapping.deployWay.options.map(function (o) {
    return /*#__PURE__*/React.createElement(Option, {
      value: o.value
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-manual-deploy-radio")
    }, o.label));
  }))), renderRestForm());
});
export default DeployModal;