import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

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, useMemo, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { Action, Choerodon } from '@choerodon/boot';
import { SagaDetails } from '@choerodon/master';
import checkPermission from "../../../../../utils/checkPermission";
import StatusTag from "../../../../../components/status-tag";
import eventStopProp from "../../../../../utils/eventStopProp";
import { getEnvStatus, statusMappings } from "../../../../../components/status-dot";
import ClickText from "../../../../../components/click-text";
import { handlePromptError } from "../../../../../utils";
import EnvModifyForm from "../../modals/env-modify";
import Modals from "./modals";
import { useEnvironmentStore } from "../../../stores";
import { useMainStore } from "../../stores";
import { useEnvGroupStore } from "./stores";
var Column = _Table.Column;
var envKey = _Modal.key;
var modalKey = _Modal.key;
var deleteKey = _Modal.key;
var effectKey = _Modal.key;
var formKey = _Modal.key;
var Group = observer(function () {
  var modalStyle = useMemo(function () {
    return {
      width: 380
    };
  }, []);

  var _useEnvironmentStore = useEnvironmentStore(),
      intlPrefix = _useEnvironmentStore.intlPrefix,
      envStore = _useEnvironmentStore.envStore,
      treeDs = _useEnvironmentStore.treeDs,
      projectId = _useEnvironmentStore.AppState.currentMenuType.id,
      prefixCls = _useEnvironmentStore.prefixCls;

  var _useMainStore = useMainStore(),
      mainStore = _useMainStore.mainStore;

  var _useEnvGroupStore = useEnvGroupStore(),
      groupDs = _useEnvGroupStore.groupDs,
      formatMessage = _useEnvGroupStore.intl.formatMessage;

  var name = envStore.getSelectedMenu.name;

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

  useEffect(function () {
    function init() {
      return _init.apply(this, arguments);
    }

    function _init() {
      _init = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var res;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return checkPermission({
                  projectId: projectId,
                  code: 'choerodon.code.project.deploy.environment.ps.detail-group'
                });

              case 2:
                res = _context.sent;
                setCanDetail(res);

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));
      return _init.apply(this, arguments);
    }

    init();
  }, []);

  function refresh() {
    groupDs.query();
    treeDs.query();
  }

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

  function _openDelete() {
    _openDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(record) {
      var envId, envName, deleteModal, res, result;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              envId = record.get('id');
              envName = record.get('name');
              deleteModal = _Modal.open({
                key: deleteKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".delete.title")
                }, {
                  name: envName
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                footer: null,
                movable: false
              });
              _context2.prev = 3;
              _context2.next = 6;
              return checkStatus(record);

            case 6:
              res = _context2.sent;

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

              _context2.next = 10;
              return mainStore.checkDelete(projectId, envId);

            case 10:
              result = _context2.sent;

              if (result && result.failed) {
                deleteModal.close();
              } else if (result) {
                deleteModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".delete.des.resource.confirm")
                  }),
                  okText: formatMessage({
                    id: 'delete'
                  }),
                  okProps: {
                    color: 'red'
                  },
                  cancelProps: {
                    color: 'dark'
                  },
                  onOk: handleDelete,
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, cancelBtn, okBtn);
                  }
                });
              } else {
                deleteModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".delete.des.pipeline.confirm")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(okBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn);
                  }
                });
              }

              _context2.next = 15;
              break;

            case 14:
              deleteModal.update({
                children: formatMessage({
                  id: "".concat(intlPrefix, ".status.change")
                }),
                onOk: refresh,
                footer: function footer(okBtn, cancelBtn) {
                  return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn);
                }
              });

            case 15:
              _context2.next = 21;
              break;

            case 17:
              _context2.prev = 17;
              _context2.t0 = _context2["catch"](3);
              Choerodon.handlePromptError(_context2.t0);
              deleteModal.close();

            case 21:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 17]]);
    }));
    return _openDelete.apply(this, arguments);
  }

  function handleDelete() {
    return _handleDelete.apply(this, arguments);
  }

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var envId, res;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              envId = groupDs.current ? groupDs.current.get('id') : null;
              _context3.prev = 1;
              _context3.next = 4;
              return mainStore.deleteEnv(projectId, envId);

            case 4:
              res = _context3.sent;
              handlePromptError(res);
              _context3.next = 11;
              break;

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

            case 11:
              _context3.prev = 11;
              refresh();
              return _context3.finish(11);

            case 14:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[1, 8, 11, 14]]);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function handleEffect(_x2, _x3) {
    return _handleEffect.apply(this, arguments);
  }

  function _handleEffect() {
    _handleEffect = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(envId, target) {
      var res;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.prev = 0;
              _context4.next = 3;
              return mainStore.effectEnv(projectId, envId, target);

            case 3:
              res = _context4.sent;
              handlePromptError(res);
              _context4.next = 10;
              break;

            case 7:
              _context4.prev = 7;
              _context4.t0 = _context4["catch"](0);
              Choerodon.handleResponseError(_context4.t0);

            case 10:
              _context4.prev = 10;
              refresh();
              return _context4.finish(10);

            case 13:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4, null, [[0, 7, 10, 13]]);
    }));
    return _handleEffect.apply(this, arguments);
  }

  function checkStatus(record) {
    var envId = record.get('id');
    var oldStatus = getStatusInRecord(record);
    return new Promise(function (resolve) {
      mainStore.checkStatus(projectId, envId).then(function (res) {
        if (res && res.id) {
          res.failed = res.fail;
          var newStatus = getEnvStatus(res);
          resolve(newStatus === oldStatus);
        }
      })["catch"](function () {
        return resolve(false);
      });
    });
  }

  function openEffectModal(_x4) {
    return _openEffectModal.apply(this, arguments);
  }

  function _openEffectModal() {
    _openEffectModal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(record) {
      var envId, envName, effectModal, res, result;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              envId = record.get('id');
              envName = record.get('name');
              effectModal = _Modal.open({
                key: effectKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".stop.title")
                }, {
                  name: envName
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                footer: null,
                movable: false
              });
              _context5.next = 5;
              return checkStatus(record);

            case 5:
              res = _context5.sent;

              if (!res) {
                _context5.next = 20;
                break;
              }

              _context5.prev = 7;
              _context5.next = 10;
              return mainStore.checkStop(projectId, envId);

            case 10:
              result = _context5.sent;

              if (handlePromptError(result)) {
                effectModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".stop.des")
                  }),
                  okText: formatMessage({
                    id: 'ok'
                  }),
                  okCancel: true,
                  onOk: function onOk() {
                    return handleEffect(envId, false);
                  },
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn, cancelBtn);
                  }
                });
              } else if (!result.failed) {
                effectModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".no.stop.des")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn);
                  }
                });
              } else {
                effectModal.close();
              }

              _context5.next = 18;
              break;

            case 14:
              _context5.prev = 14;
              _context5.t0 = _context5["catch"](7);
              Choerodon.handleResponseError(_context5.t0);
              effectModal.close();

            case 18:
              _context5.next = 21;
              break;

            case 20:
              effectModal.update({
                children: formatMessage({
                  id: "".concat(intlPrefix, ".status.change")
                }),
                onOk: refresh,
                footer: function footer(okBtn, cancelBtn) {
                  return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn);
                }
              });

            case 21:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5, null, [[7, 14]]);
    }));
    return _openEffectModal.apply(this, arguments);
  }

  function openModifyModal(_x5) {
    return _openModifyModal.apply(this, arguments);
  }

  function _openModifyModal() {
    _openModifyModal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(record) {
      var modifyModal, res;
      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              modifyModal = _Modal.open({
                key: formKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".modify")
                }),
                style: modalStyle,
                children: /*#__PURE__*/React.createElement(_Spin, null),
                drawer: true,
                okCancel: false,
                okText: formatMessage({
                  id: 'close'
                })
              });
              _context6.prev = 1;
              _context6.next = 4;
              return checkStatus(record);

            case 4:
              res = _context6.sent;

              if (res) {
                modifyModal.update({
                  okCancel: true,
                  children: /*#__PURE__*/React.createElement(EnvModifyForm, {
                    intlPrefix: intlPrefix,
                    refresh: refresh,
                    record: record,
                    store: envStore
                  }),
                  okText: formatMessage({
                    id: 'save'
                  })
                });
              } else {
                modifyModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".status.change")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  onOk: refresh
                });
              }

              _context6.next = 12;
              break;

            case 8:
              _context6.prev = 8;
              _context6.t0 = _context6["catch"](1);
              Choerodon.handlePromptError(_context6.t0);
              modifyModal.close();

            case 12:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6, null, [[1, 8]]);
    }));
    return _openModifyModal.apply(this, arguments);
  }

  function getStatusInRecord(record) {
    var active = record.get('active');
    var connect = record.get('connect');
    var failed = record.get('failed');
    var synchronize = record.get('synchro');
    return getEnvStatus({
      active: active,
      connect: connect,
      failed: failed,
      synchronize: synchronize
    });
  }

  function openSagaDetails(id) {
    _Modal.open({
      title: formatMessage({
        id: 'global.saga-instance.detail'
      }),
      key: _Modal.key(),
      children: /*#__PURE__*/React.createElement(SagaDetails, {
        sagaInstanceId: id,
        instance: true
      }),
      drawer: true,
      okCancel: false,
      okText: formatMessage({
        id: 'close'
      }),
      style: {
        width: 'calc(100% - 3.5rem)'
      }
    });
  }

  function renderName(_ref) {
    var value = _ref.value,
        record = _ref.record;
    var RUNNING = statusMappings.RUNNING,
        DISCONNECTED = statusMappings.DISCONNECTED;
    var status = getStatusInRecord(record);
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StatusTag, {
      colorCode: status,
      name: formatMessage({
        id: status
      })
    }), /*#__PURE__*/React.createElement(ClickText, {
      value: value,
      clickAble: (status === RUNNING || status === DISCONNECTED) && canDetail,
      onClick: function onClick() {
        return openModifyModal(record);
      },
      record: record
    }), record.get('sagaInstanceId') ? /*#__PURE__*/React.createElement(_Icon, {
      className: "".concat(prefixCls, "-dashBoard"),
      type: "developer_board",
      onClick: function onClick() {
        return openSagaDetails(record.get('sagaInstanceId'));
      }
    }) : '');
  }

  function renderActions(_ref2) {
    var record = _ref2.record;
    var RUNNING = statusMappings.RUNNING,
        DISCONNECTED = statusMappings.DISCONNECTED,
        FAILED = statusMappings.FAILED,
        OPERATING = statusMappings.OPERATING,
        STOPPED = statusMappings.STOPPED;
    var status = getStatusInRecord(record);
    var envId = record.get('id');
    var hasSagaInstanceId = record.get('sagaInstanceId');
    if (status === OPERATING) return null;
    var actionData = [];

    if (hasSagaInstanceId) {
      actionData = [{
        service: ['choerodon.code.project.deploy.environment.ps.delete'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".modal.detail.delete")
        }),
        action: function action() {
          return openDelete(record);
        }
      }];
    } else {
      switch (status) {
        case RUNNING:
          actionData = [{
            service: ['choerodon.code.project.deploy.environment.ps.modify'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.modify")
            }),
            action: openModifyModal.bind(this, record)
          }, {
            service: ['choerodon.code.project.deploy.environment.ps.stop'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.stop")
            }),
            action: function action() {
              return openEffectModal(record);
            }
          }];
          break;

        case DISCONNECTED:
          actionData = [{
            service: ['choerodon.code.project.deploy.environment.ps.modify'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.modify")
            }),
            action: function action() {
              return openModifyModal(record);
            }
          }, {
            service: ['choerodon.code.project.deploy.environment.ps.delete'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.delete")
            }),
            action: function action() {
              return openDelete(record);
            }
          }];
          break;

        case STOPPED:
          actionData = [{
            service: ['choerodon.code.project.deploy.environment.ps.stop'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.start")
            }),
            action: function action() {
              return handleEffect(envId, true);
            }
          }, {
            service: ['choerodon.code.project.deploy.environment.ps.delete'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.delete")
            }),
            action: function action() {
              return openDelete(record);
            }
          }];
          break;

        case FAILED:
          actionData = [{
            service: ['choerodon.code.project.deploy.environment.ps.delete'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".modal.detail.delete")
            }),
            action: function action() {
              return openDelete(record);
            }
          }];
          break;

        default:
      }
    }

    return /*#__PURE__*/React.createElement(Action, {
      placement: "bottomRight",
      data: actionData,
      onClick: eventStopProp
    });
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, name), /*#__PURE__*/React.createElement(_Table, {
    dataSet: groupDs,
    border: false,
    queryBar: "none"
  }, /*#__PURE__*/React.createElement(Column, {
    name: "name",
    renderer: renderName
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderActions,
    width: 100
  }), /*#__PURE__*/React.createElement(Column, {
    name: "description"
  }), /*#__PURE__*/React.createElement(Column, {
    name: "clusterName"
  })), /*#__PURE__*/React.createElement(Modals, null));
});
export default Group;