import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
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 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; }

/* eslint-disable jsx-a11y/click-events-have-key-events,max-len, jsx-a11y/no-static-element-interactions */
import React, { Fragment, useEffect, useState, useMemo } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import forEach from 'lodash/forEach';
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 { useBatchDeployStore } from "./stores";
import "./index.less";
var Option = _Select.Option,
    OptGroup = _Select.OptGroup;
var BatchDeployModal = injectIntl(observer(function () {
  var _useBatchDeployStore = useBatchDeployStore(),
      batchDeployDs = _useBatchDeployStore.batchDeployDs,
      deployStore = _useBatchDeployStore.deployStore,
      refresh = _useBatchDeployStore.refresh,
      intlPrefix = _useBatchDeployStore.intlPrefix,
      prefixCls = _useBatchDeployStore.prefixCls,
      modal = _useBatchDeployStore.modal,
      formatMessage = _useBatchDeployStore.intl.formatMessage,
      envId = _useBatchDeployStore.envId;

  var record = useMemo(function () {
    return batchDeployDs.current;
  }, [batchDeployDs.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 _useState9 = useState(false),
      _useState10 = _slicedToArray(_useState9, 2),
      showError = _useState10[0],
      setShowError = _useState10[1];

  useEffect(function () {
    if (envId) {
      record.init('environmentId', envId);
    }
  }, [envId]);
  modal.handleOk( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
    var hasError, res;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (!hasYamlFailed) {
              _context2.next = 2;
              break;
            }

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

          case 2:
            _context2.prev = 2;
            hasError = false;
            batchDeployDs.forEach( /*#__PURE__*/function () {
              var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(eachRecord) {
                var result;
                return regeneratorRuntime.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        _context.next = 2;
                        return eachRecord.validate();

                      case 2:
                        result = _context.sent;

                        if (!result) {
                          hasError = true;
                        }

                        eachRecord.set('hasError', !result);

                      case 5:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              }));

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

            if (!hasError) {
              _context2.next = 8;
              break;
            }

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

          case 8:
            _context2.next = 10;
            return batchDeployDs.submit();

          case 10:
            res = _context2.sent;

            if (!(res !== false)) {
              _context2.next = 14;
              break;
            }

            refresh(res.list ? res.list[0] : {}, 'resource');
            return _context2.abrupt("return", true);

          case 14:
            setShowError(true);
            return _context2.abrupt("return", false);

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

          case 21:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[2, 18]]);
  })));

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

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

  function renderEnvOption(_ref3) {
    var envRecord = _ref3.record,
        text = _ref3.text,
        value = _ref3.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(_ref4) {
    var envRecord = _ref4.record;
    var isAvailable = envRecord.get('connect') && envRecord.get('synchro') && envRecord.get('permission');
    return {
      disabled: !isAvailable
    };
  }

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

  function handleRemoveForm(formRecord) {
    batchDeployDs.remove(formRecord);
  }

  function handleAddForm(appServiceType) {
    batchDeployDs.create();
    batchDeployDs.current.init('appServiceSource', appServiceType);
    deployStore.setConfigValue('');
  }

  function handleClickAppService(formRecord) {
    batchDeployDs.current = formRecord;
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-batch-deploy")
  }, !envId && /*#__PURE__*/React.createElement(_Form, {
    record: batchDeployDs.current,
    columns: 2
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "environmentId",
    searchable: true,
    clearButton: false,
    optionRenderer: renderEnvOption,
    notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "".concat(intlPrefix, ".env.empty")
    }),
    onOption: renderOptionProperty
  }), /*#__PURE__*/React.createElement("span", {
    colSpan: 1
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-batch-deploy-content")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-batch-deploy-content-app")
  }, map(batchDeployDs.data, function (formRecord) {
    if (formRecord.get('appServiceSource') === 'normal_service') {
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-batch-deploy-content-app-item ").concat(batchDeployDs.current === formRecord ? "".concat(prefixCls, "-batch-deploy-content-app-active") : ''),
        key: formRecord.id
      }, /*#__PURE__*/React.createElement(_Form, {
        record: formRecord,
        columns: 8
      }, /*#__PURE__*/React.createElement(_Select, {
        name: "appServiceId",
        searchable: true,
        colSpan: 6,
        notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".app.empty")
        }),
        onClick: function onClick() {
          return handleClickAppService(formRecord);
        }
      }, map(deployStore.getAppService[0] && deployStore.getAppService[0].appServiceList, function (_ref5) {
        var id = _ref5.id,
            name = _ref5.name,
            code = _ref5.code;
        return /*#__PURE__*/React.createElement(Option, {
          value: "".concat(id, "**").concat(code),
          key: id
        }, name);
      })), batchDeployDs.data.length > 1 ? /*#__PURE__*/React.createElement(_Button, {
        funcType: "flat",
        icon: "delete",
        colSpan: 1,
        className: "appService-delete-btn",
        onClick: function onClick() {
          return handleRemoveForm(formRecord);
        }
      }) : /*#__PURE__*/React.createElement("span", {
        colSpan: 1
      }), formRecord.get('hasError') ? /*#__PURE__*/React.createElement(_Icon, {
        type: "error",
        colSpan: 1,
        className: "appService-error-icon"
      }) : /*#__PURE__*/React.createElement("span", {
        colSpan: 1
      })));
    }

    return null;
  }), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    color: "primary",
    icon: "add",
    className: "appService-add-btn",
    onClick: function onClick() {
      return handleAddForm('normal_service');
    },
    disabled: batchDeployDs.data.length >= 20
  }, formatMessage({
    id: "".concat(intlPrefix, ".add.appService.normal")
  })), map(batchDeployDs.data, function (formRecord) {
    if (formRecord.get('appServiceSource') === 'share_service') {
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-batch-deploy-content-app-item ").concat(batchDeployDs.current === formRecord ? "".concat(prefixCls, "-batch-deploy-content-app-active") : ''),
        key: formRecord.id
      }, /*#__PURE__*/React.createElement(_Form, {
        record: formRecord,
        columns: 8
      }, /*#__PURE__*/React.createElement(_Select, {
        name: "appServiceId",
        searchable: true,
        colSpan: 6,
        notFoundContent: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".app.empty")
        }),
        onClick: function onClick() {
          return handleClickAppService(formRecord);
        }
      }, map(deployStore.getShareAppService, function (_ref6) {
        var groupId = _ref6.id,
            groupName = _ref6.name,
            appServiceList = _ref6.appServiceList;
        return /*#__PURE__*/React.createElement(OptGroup, {
          label: groupName,
          key: groupId
        }, map(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
          }, name);
        }));
      })), batchDeployDs.data.length > 1 ? /*#__PURE__*/React.createElement(_Button, {
        funcType: "flat",
        icon: "delete",
        colSpan: 1,
        className: "appService-delete-btn",
        onClick: function onClick() {
          return handleRemoveForm(formRecord);
        }
      }) : /*#__PURE__*/React.createElement("span", {
        colSpan: 1
      }), formRecord.get('hasError') ? /*#__PURE__*/React.createElement(_Icon, {
        type: "error",
        colSpan: 1,
        className: "appService-error-icon"
      }) : /*#__PURE__*/React.createElement("span", {
        colSpan: 1
      })));
    }

    return null;
  }), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    color: "primary",
    icon: "add",
    className: "appService-add-btn",
    onClick: function onClick() {
      return handleAddForm('share_service');
    },
    disabled: batchDeployDs.data.length >= 20
  }, formatMessage({
    id: "".concat(intlPrefix, ".add.appService.share")
  })), showError && /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-batch-deploy-error")
  }, formatMessage({
    id: "".concat(intlPrefix, ".batch.deploy.error")
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-batch-deploy-content-form")
  }, /*#__PURE__*/React.createElement(_Form, {
    record: batchDeployDs.current,
    columns: 3
  }, /*#__PURE__*/React.createElement(_Select, {
    name: "appServiceVersionId",
    searchable: true,
    searchMatcher: "version",
    disabled: record && !record.get('appServiceId')
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "instanceName",
    addonAfter: /*#__PURE__*/React.createElement(Tips, {
      helpText: formatMessage({
        id: "".concat(intlPrefix, ".instance.tips")
      })
    })
  }), /*#__PURE__*/React.createElement(_Select, {
    name: "valueId",
    searchable: true,
    colSpan: 2,
    newLine: true,
    clearButton: true,
    disabled: record && (!record.get('appServiceId') || !record.get('environmentId')),
    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,
    value: record ? record.get('values') || '' : '',
    onValueChange: ChangeConfigValue,
    handleEnableNext: handleEnableNext
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-resource-config")
  }, /*#__PURE__*/React.createElement("div", {
    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", {
    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", {
    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)))))));
}));
export default BatchDeployModal;