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/popover/style";
import _Popover from "choerodon-ui/lib/popover";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";

var _class, _class2, _temp;

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 { FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react';
import _ from 'lodash';
import TimeAgo from 'timeago-react';
import { Choerodon } from '@choerodon/boot';
import { formatDate } from "../../../../../../utils";
import Store from "../stores";
import Pods from "./pods";
import DetailsSidebar from "./sidebar";
import "./index.less";

var Label = function Label(_ref) {
  var name = _ref.name,
      value = _ref.value;
  return /*#__PURE__*/React.createElement(_Tooltip, {
    title: "\u952E-".concat(name, " \u503C-").concat(value)
  }, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-deployment-popover-labels"
  }, /*#__PURE__*/React.createElement("span", null, "\u952E-", name), /*#__PURE__*/React.createElement("span", null, "\u503C-", value)));
};

var Details = observer(_class = (_temp = _class2 = /*#__PURE__*/function (_Component) {
  _inherits(Details, _Component);

  var _super = _createSuper(Details);

  function Details() {
    var _this;

    _classCallCheck(this, Details);

    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 = {
      visible: false,
      isDisabled: false
    };

    _this.refresh = function () {
      var _this$context = _this.context,
          baseDs = _this$context.baseDs,
          treeDs = _this$context.treeDs,
          detailsStore = _this$context.detailsStore,
          instanceId = _this$context.instanceId,
          projectId = _this$context.AppState.currentMenuType.projectId;
      baseDs.query();
      treeDs.query();
      detailsStore.loadResource(projectId, instanceId);
    };

    _this.changeTargetCount = function (count) {
      var detailsStore = _this.context.detailsStore;
      detailsStore.setTargetCount(count);
    };

    _this.handleClick = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(type, id, name) {
        var _this$context2, detailsStore, projectId, result;

        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this.setState({
                  isDisabled: true
                });

                _this$context2 = _this.context, detailsStore = _this$context2.detailsStore, projectId = _this$context2.AppState.currentMenuType.id;
                _context.next = 4;
                return detailsStore.loadDeploymentsJson(type, projectId, id, name);

              case 4:
                result = _context.sent;
                detailsStore.loadDeploymentsYaml(type, projectId, id, name);

                if (result) {
                  _this.setState({
                    visible: true
                  });
                }

                _this.setState({
                  isDisabled: false
                });

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

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

    _this.getDeployContent = function (podType) {
      var _this$context3 = _this.context,
          detailsStore = _this$context3.detailsStore,
          baseDs = _this$context3.baseDs,
          instanceId = _this$context3.instanceId,
          envId = _this$context3.envId;
      var status;
      var connect;
      var instanceStatus;
      var record = baseDs.current;

      if (record) {
        status = record.get('effectCommandStatus');
        connect = record.get('connect');
        instanceStatus = record.get('status');
      }

      var isDisabled = _this.state.isDisabled;
      var getResources = detailsStore.getResources,
          targetCount = detailsStore.getTargetCount;
      var POD_TYPE = {
        // 确保“当前/需要/可提供”的顺序
        deploymentVOS: ['current', 'desired', 'available'],
        daemonSetVOS: ['currentScheduled', 'desiredScheduled', 'numberAvailable'],
        statefulSetVOS: ['currentReplicas', 'desiredReplicas', 'readyReplicas']
      };

      var _POD_TYPE$podType = _slicedToArray(POD_TYPE[podType], 3),
          current = _POD_TYPE$podType[0],
          desired = _POD_TYPE$podType[1],
          available = _POD_TYPE$podType[2];

      var deployments = getResources[podType];
      if (!deployments || !deployments.length) return null;

      var getDeploy = function getDeploy(item) {
        var name = item.name,
            age = item.age,
            devopsEnvPodVOS = item.devopsEnvPodVOS,
            ports = item.ports,
            labels = item.labels;
        var replica = "".concat(item[available] || 0, " available / ").concat(item[current] || 0, " current / ").concat(item[desired] || 0, " desired");
        var podCount = computedPodCount(devopsEnvPodVOS);
        var portValues = null;
        var labelValues = null;

        if (ports && ports.length) {
          portValues = /*#__PURE__*/React.createElement("div", {
            className: "c7ncd-instance-details-port"
          }, /*#__PURE__*/React.createElement("span", {
            className: "c7ncd-instance-details-value"
          }, _.head(ports)), ports.length > 1 && /*#__PURE__*/React.createElement(_Popover, {
            arrowPointAtCenter: true,
            placement: "bottom",
            getPopupContainer: function getPopupContainer(triggerNode) {
              return triggerNode.parentNode;
            },
            content: _.map(_.tail(ports), function (port) {
              return /*#__PURE__*/React.createElement("div", {
                className: "c7ncd-deployment-popover-port",
                key: port
              }, port);
            })
          }, /*#__PURE__*/React.createElement(_Icon, {
            type: "expand_more",
            className: "c7ncd-deployment-icon-more"
          })));
        }

        if (!_.isEmpty(labels)) {
          var keys = Object.keys(labels);
          var firstKey = keys[0];
          labelValues = /*#__PURE__*/React.createElement("div", {
            className: "c7ncd-instance-details-label"
          }, /*#__PURE__*/React.createElement(Label, {
            name: firstKey,
            value: labels[firstKey]
          }), keys.length > 1 && /*#__PURE__*/React.createElement(_Popover, {
            arrowPointAtCenter: true,
            placement: "bottom",
            getPopupContainer: function getPopupContainer(triggerNode) {
              return triggerNode.parentNode;
            },
            content: _.map(_.tail(keys), function (key) {
              return /*#__PURE__*/React.createElement(Label, {
                key: key,
                name: key,
                value: labels[key]
              });
            })
          }, /*#__PURE__*/React.createElement(_Icon, {
            type: "expand_more",
            className: "c7ncd-deployment-icon-more"
          })));
        }

        return /*#__PURE__*/React.createElement("div", {
          key: name,
          className: "c7ncd-instance-details-grid"
        }, /*#__PURE__*/React.createElement("div", null, getName(name), /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-item"
        }, /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-inline"
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-key"
        }, podType === 'deploymentVOS' ? 'ReplicaSet' : /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "status"
        }), "\uFF1A"), /*#__PURE__*/React.createElement(_Tooltip, {
          title: replica
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-value"
        }, replica))), /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-inline"
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-key"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "ist.expand.date"
        }), "\uFF1A"), /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-value"
        }, /*#__PURE__*/React.createElement(_Tooltip, {
          title: formatDate(age)
        }, /*#__PURE__*/React.createElement(TimeAgo, {
          datetime: age,
          locale: Choerodon.getMessage('zh_CN', 'en')
        })))), _.has(item, 'labels') && /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-inline"
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-key"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "label"
        }), "\uFF1A"), labelValues), _.has(item, 'ports') && /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-inline"
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7ncd-instance-details-key"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "c7ncd.deployment.port.number"
        }), "\uFF1A"), portValues)), /*#__PURE__*/React.createElement(_Button, {
          className: "c7ncd-detail-btn",
          type: "primary",
          onClick: isDisabled ? null : function () {
            return _this.handleClick(podType, instanceId, name);
          }
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "detailMore"
        }))), /*#__PURE__*/React.createElement(Pods, {
          podType: podType,
          connect: connect,
          name: name,
          count: podCount,
          targetCount: targetCount,
          status: status,
          instanceStatus: instanceStatus,
          handleChangeCount: _this.changeTargetCount,
          store: detailsStore,
          envId: envId,
          refresh: _this.refresh
        }));
      };

      return _.map(deployments, getDeploy);
    };

    _this.getNoPodContent = function (type) {
      var getResources = _this.context.detailsStore.getResources;
      var resources = getResources[type];
      if (!resources || !resources.length) return null;
      var TYPE_KEY = {
        serviceVOS: ['type', 'age', 'externalIp', 'port', 'clusterIp'],
        ingressVOS: ['hosts', 'age', 'address', 'ports', 'services'],
        persistentVolumeClaimVOS: ['status', 'age', 'accessModes', 'capacity']
      };
      return _.map(resources, function (data) {
        var content = function content(key) {
          var text = null;

          switch (key) {
            case 'age':
              text = /*#__PURE__*/React.createElement(_Tooltip, {
                title: formatDate(data[key])
              }, /*#__PURE__*/React.createElement(TimeAgo, {
                datetime: data[key],
                locale: Choerodon.getMessage('zh_CN', 'en')
              }));
              break;

            case 'status':
              text = /*#__PURE__*/React.createElement("span", {
                className: "c7ncd-deploy-pvc c7ncd-deploy-pvc_".concat(data[key])
              }, data[key]);
              break;

            case 'services':
              text = /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement("span", {
                className: "c7ncd-instance-details-value"
              }, _.head(data[key])), data[key].length > 1 && /*#__PURE__*/React.createElement(_Popover, {
                arrowPointAtCenter: true,
                placement: "bottom",
                getPopupContainer: function getPopupContainer(triggerNode) {
                  return triggerNode.parentNode;
                },
                content: _.map(_.tail(data[key]), function (ingress) {
                  return /*#__PURE__*/React.createElement("div", {
                    className: "c7ncd-deployment-popover-port",
                    key: ingress
                  }, ingress);
                })
              }, /*#__PURE__*/React.createElement(_Icon, {
                type: "expand_more",
                className: "c7ncd-deployment-icon-more"
              })));
              break;

            case 'hosts':
              text = /*#__PURE__*/React.createElement(_Tooltip, {
                title: data[key]
              }, /*#__PURE__*/React.createElement("span", null, data[key]));
              break;

            default:
              text = data[key];
              break;
          }

          return /*#__PURE__*/React.createElement("li", {
            className: "c7ncd-instance-details-inline"
          }, /*#__PURE__*/React.createElement("span", {
            className: "c7ncd-instance-details-key"
          }, /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "ist.expand.net.".concat(key)
          }), "\uFF1A"), /*#__PURE__*/React.createElement("span", {
            className: "c7ncd-instance-details-value"
          }, text));
        };

        return /*#__PURE__*/React.createElement("div", {
          key: data.name,
          className: "c7ncd-instance-details-grid"
        }, /*#__PURE__*/React.createElement("div", null, getName(data.name), /*#__PURE__*/React.createElement("div", {
          className: "c7ncd-instance-details-item"
        }, _.map(TYPE_KEY[type], function (item) {
          return content(item);
        }))));
      });
    };

    _this.hideSidebar = function () {
      var detailsStore = _this.context.detailsStore;

      _this.setState({
        visible: false
      });

      detailsStore.setDeployments([]);
    };

    return _this;
  }

  _createClass(Details, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var detailsStore = this.context.detailsStore;
      detailsStore.setResources({});
    }
  }, {
    key: "render",
    value: function render() {
      var _this$context4 = this.context,
          getLoading = _this$context4.detailsStore.getLoading,
          intlPrefix = _this$context4.intlPrefix;
      var visible = this.state.visible;
      var contentList = [{
        title: 'Deployments',
        main: this.getDeployContent('deploymentVOS')
      }, {
        title: 'Stateful Set',
        main: this.getDeployContent('statefulSetVOS')
      }, {
        title: 'Daemon Set',
        main: this.getDeployContent('daemonSetVOS')
      }, {
        title: 'PVC',
        main: this.getNoPodContent('persistentVolumeClaimVOS')
      }, {
        title: 'Service',
        main: this.getNoPodContent('serviceVOS')
      }, {
        title: 'Ingress',
        main: this.getNoPodContent('ingressVOS')
      }];

      var hasContent = _.find(contentList, function (item) {
        return item.main && item.main.length;
      });

      return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(_Spin, {
        spinning: getLoading
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-instance-details"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-instance-details-inner"
      }, !hasContent ? /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-instance-details-empty"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".instance.detail.empty")
      })) : getContent(contentList)))), visible && /*#__PURE__*/React.createElement(DetailsSidebar, {
        visible: visible,
        onClose: this.hideSidebar
      }));
    }
  }]);

  return Details;
}(Component), _class2.contextType = Store, _temp)) || _class;

export { Details as default };

function computedPodCount(collection) {
  // 计算 pod 数量和环形图占比
  var count = _.countBy(collection, function (pod) {
    return !!pod.ready;
  }); // 通过 ready 字段进行分类计数，分类结果是 true 和 false 的数量


  var correctCount = count["true"] || 0;
  var errorCount = count["false"] || 0;
  var sum = correctCount + errorCount;
  var correct = sum > 0 ? correctCount / sum * (Math.PI * 2 * 30) : 0;
  return {
    sum: sum,
    correct: correct,
    correctCount: correctCount
  };
}

function getContent(data) {
  return _.map(data, function (_ref2) {
    var main = _ref2.main,
        title = _ref2.title;
    return main && main.length ? /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-instance-details-panel",
      key: title
    }, /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-instance-details-title"
    }, /*#__PURE__*/React.createElement("span", null, title)), main) : null;
  });
}

function getName(name) {
  return /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-instance-details-block"
  }, /*#__PURE__*/React.createElement("span", {
    className: "c7ncd-instance-details-item-keys"
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "name"
  }), "\uFF1A"), /*#__PURE__*/React.createElement("span", {
    title: name,
    className: "c7ncd-instance-details-item-values c7ncd-expanded-text_bold"
  }, name));
}