import "choerodon-ui/lib/popover/style";
import _Popover from "choerodon-ui/lib/popover";
import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

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, memo, useState, useCallback } from 'react';
import { FormattedMessage } from 'react-intl';
import { Action } from '@choerodon/boot';
import map from 'lodash/map';
import MouserOverWrapper from "../../../../../../components/MouseOverWrapper";
import TimePopover from "../../../../../../components/timePopover/TimePopover";
import StatusTags from "../../../../../../components/status-tag";
import { useResourceStore } from "../../../../stores";
import { useInstanceStore } from "../stores";
import LogSiderbar from "../../../../../../components/log-siderbar";
import TermSiderbar from "../../../../../../components/term-sidebar";
import "./index.less";
var Column = _Table.Column;
var ICON_CODE = {
  available: 'check_circle',
  unavailable: 'cancel',
  health: 'help'
};
var PodDetail = /*#__PURE__*/memo(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix,
      projectId = _useResourceStore.AppState.currentMenuType.projectId;

  var _useInstanceStore = useInstanceStore(),
      intl = _useInstanceStore.intl,
      podsDs = _useInstanceStore.podsDs; // eslint-disable-next-line no-unused-expressions


  shellVisible;

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

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

  function getStatusCode(record) {
    var ready = record.get('ready');
    var status = record.get('status');
    var statusCode = 'unavailable';

    if (ready) {
      statusCode = 'available';
    } else if (status === 'Running') {
      statusCode = 'health';
    }

    return statusCode;
  }

  function renderName(_ref) {
    var value = _ref.value,
        record = _ref.record;
    var statusCode = getStatusCode(record);
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Tooltip, {
      title: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ist.ready.".concat(statusCode)
      })
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: ICON_CODE[statusCode],
      className: "".concat(prefixCls, "-pod-ready-").concat(statusCode)
    })), /*#__PURE__*/React.createElement(MouserOverWrapper, {
      text: value,
      width: 0.2,
      style: {
        display: 'inline'
      }
    }, value));
  }

  function renderStatus(_ref2) {
    var value = _ref2.value,
        record = _ref2.record;
    var wrapStyle = {
      width: 54
    };
    var statusMap = {
      Completed: [true, '#00bf96'],
      Running: [false, '#00bf96'],
      Error: [false, '#f44336'],
      Pending: [false, '#ff9915']
    };

    var _ref3 = statusMap[value] || [true, 'rgba(0, 0, 0, 0.36)'],
        _ref4 = _slicedToArray(_ref3, 2),
        wrap = _ref4[0],
        color = _ref4[1];

    var newColor = getStatusCode(record) === 'health' ? '#ffb100' : color;
    return /*#__PURE__*/React.createElement(StatusTags, {
      ellipsis: wrap,
      color: newColor,
      name: value,
      style: wrapStyle
    });
  }

  function renderContainers(_ref5) {
    var value = _ref5.value;
    var node = [];
    var item;

    if (value && value.length) {
      // eslint-disable-next-line prefer-destructuring
      item = value[0];
      map(value, function (_ref6, index) {
        var ready = _ref6.ready,
            name = _ref6.name;
        node.push( /*#__PURE__*/React.createElement("div", {
          className: "column-container-mt",
          key: index
        }, /*#__PURE__*/React.createElement(_Tooltip, {
          title: /*#__PURE__*/React.createElement(FormattedMessage, {
            id: "ist.".concat(ready ? 'y' : 'n')
          })
        }, /*#__PURE__*/React.createElement(_Icon, {
          type: ready ? 'check_circle' : 'cancel',
          className: "".concat(prefixCls, "-pod-ready-").concat(ready ? 'check' : 'cancel')
        })), /*#__PURE__*/React.createElement("span", null, name)));
      });
    }

    return /*#__PURE__*/React.createElement("div", {
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    }, item && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Tooltip, {
      title: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "ist.".concat(item.ready ? 'y' : 'n')
      })
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: item.ready ? 'check_circle' : 'cancel',
      className: "".concat(prefixCls, "-pod-ready-").concat(item.ready ? 'check' : 'cancel')
    })), /*#__PURE__*/React.createElement(MouserOverWrapper, {
      text: item.name,
      width: 0.1,
      style: {
        display: 'inline'
      }
    }, item.name)), node.length > 1 && /*#__PURE__*/React.createElement(_Popover, {
      arrowPointAtCenter: true,
      placement: "bottomRight",
      content: /*#__PURE__*/React.createElement(React.Fragment, null, node),
      overlayClassName: "".concat(prefixCls, "-pods-popover")
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "expand_more",
      className: "container-expend-icon"
    })));
  }

  var renderDate = useCallback(function (_ref7) {
    var value = _ref7.value;
    return /*#__PURE__*/React.createElement(TimePopover, {
      content: value
    });
  }, []);

  function renderAction(_ref8) {
    var _record$get;

    var value = _ref8.value,
        record = _ref8.record;
    var buttons = [{
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.pod.delete'],
      text: intl.formatMessage({
        id: 'delete'
      }),
      action: function action() {
        return deletePod();
      }
    }];

    if ((_record$get = record.get('containers')) === null || _record$get === void 0 ? void 0 : _record$get.length) {
      buttons.unshift({
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.pod.log'],
        text: intl.formatMessage({
          id: "".concat(intlPrefix, ".instance.log")
        }),
        action: function action() {
          return openLog();
        }
      }, {
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.pod.shell'],
        text: intl.formatMessage({
          id: "".concat(intlPrefix, ".instance.term")
        }),
        action: function action() {
          return openShell();
        }
      });
    }

    return /*#__PURE__*/React.createElement(Action, {
      data: buttons
    });
  }
  /**
   * 控制Log侧边窗的可见性
   */


  function openLog() {
    setVisible(true);
  }

  function closeLog() {
    setVisible(false);
  }
  /**
   * 控制Shell侧边窗的可见性
   */


  function openShell() {
    setShellVisible(true);
  }

  function closeShell() {
    setShellVisible(false);
  }
  /**
   * 删除Pod
   */


  function deletePod() {
    var modalProps = {
      title: intl.formatMessage({
        id: "".concat(intlPrefix, ".instance.pod.delete.title")
      }),
      children: intl.formatMessage({
        id: "".concat(intlPrefix, ".instance.pod.delete.des")
      }),
      okText: intl.formatMessage({
        id: 'delete'
      }),
      okProps: {
        color: 'red'
      },
      cancelProps: {
        color: 'dark'
      }
    };
    podsDs["delete"](podsDs.current, modalProps);
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tab-table"
  }, /*#__PURE__*/React.createElement(_Table, {
    dataSet: podsDs,
    border: false,
    queryBar: "bar",
    className: "".concat(prefixCls, "-instance-pods")
  }, /*#__PURE__*/React.createElement(Column, {
    name: "name",
    renderer: renderName
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    name: "containers",
    renderer: renderContainers
  }), /*#__PURE__*/React.createElement(Column, {
    name: "ip",
    width: "1.2rem"
  }), /*#__PURE__*/React.createElement(Column, {
    name: "creationDate",
    sortable: true,
    renderer: renderDate,
    width: 105
  }), /*#__PURE__*/React.createElement(Column, {
    name: "status",
    renderer: renderStatus,
    width: "1rem"
  }))), visible && /*#__PURE__*/React.createElement(LogSiderbar, {
    visible: visible,
    onClose: closeLog,
    record: podsDs.current.toData(),
    projectId: projectId
  }), shellVisible && /*#__PURE__*/React.createElement(TermSiderbar, {
    visible: shellVisible,
    onClose: closeShell,
    record: podsDs.current.toData(),
    projectId: projectId
  }));
});
export default PodDetail;