import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/lib/spin/style";
import _Spin from "@hzero-front-ui/c7n-ui/lib/Spin";
import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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 */
import React, { Fragment, useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { FormattedMessage } from 'react-intl';
import _ from 'lodash';
import ReactCodeMirror from 'react-codemirror';
import Operation from "./op-record";
import { useResourceStore } from "../../../../stores";
import { useInstanceStore } from "../stores";
import EmptyPage from "../../../../../../components/empty-page";
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/base16-dark.css';
import "./index.less";

var logKey = _Modal.key();

var logOptions = {
  theme: 'base16-dark',
  mode: 'textile',
  readOnly: true,
  lineNumbers: true,
  lineWrapping: true
};

var InstanceEvent = function InstanceEvent(_ref) {
  var index = _ref.index,
      jobPodStatus = _ref.jobPodStatus,
      name = _ref.name,
      log = _ref.log,
      flag = _ref.flag,
      event = _ref.event,
      intlPrefix = _ref.intlPrefix,
      formatMessage = _ref.formatMessage,
      showMore = _ref.showMore;

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

  var editorLog;
  /**
   *  全屏查看日志
   */

  function openFullScreen() {
    var cm = editorLog.getCodeMirror();
    var wrap = cm.getWrapperElement();
    cm.state.fullScreenRestore = {
      scrollTop: window.pageYOffset,
      scrollLeft: window.pageXOffset,
      width: wrap.style.width,
      height: wrap.style.height
    };
    wrap.style.width = '';
    wrap.style.height = 'auto';
    wrap.className += ' CodeMirror-fullScreen';
    setFullScreen(true);
    document.documentElement.style.overflow = 'hidden';
    cm.refresh();
    window.addEventListener('keydown', function (e) {
      setNormal();
    });
  }
  /**
   * 任意键退出全屏查看
   */


  function setNormal() {
    if (!editorLog) return;
    var cm = editorLog.getCodeMirror();
    var wrap = cm.getWrapperElement();
    wrap.className = wrap.className.replace(/\s*CodeMirror-fullScreen\b/, '');
    setFullScreen(false);
    document.documentElement.style.overflow = '';
    var info = cm.state.fullScreenRestore;
    wrap.style.width = info.width;
    wrap.style.height = info.height;
    window.scrollTo(info.scrollLeft, info.scrollTop);
    cm.refresh();
    window.removeEventListener('keydown', function (e) {
      setNormal();
    });
  }

  function openLogDetail() {
    _Modal.open({
      key: logKey,
      title: formatMessage({
        id: 'container.log.header.title'
      }),
      drawer: true,
      okText: formatMessage({
        id: 'close'
      }),
      okCancel: false,
      style: {
        width: 1000
      },
      children: /*#__PURE__*/React.createElement("div", {
        className: fullScreen ? 'c7ncd-log-sidebar-content_full' : 'c7ncd-log-sidebar-content'
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-term-fullscreen"
      }, /*#__PURE__*/React.createElement(_Tooltip, {
        title: formatMessage({
          id: "".concat(intlPrefix, ".instance.cases.fullScreen")
        })
      }, /*#__PURE__*/React.createElement(_Button, {
        className: "c7ncd-term-fullscreen-button",
        type: "primary",
        funcType: "flat",
        shape: "circle",
        icon: "fullscreen",
        onClick: openFullScreen
      }))), /*#__PURE__*/React.createElement("div", {
        className: "c7n-term-wrap"
      }, /*#__PURE__*/React.createElement(ReactCodeMirror, {
        ref: function ref(editor) {
          editorLog = editor;
        },
        value: log,
        options: logOptions,
        className: "c7n-log-editor"
      })))
    });
  }

  function handleClick() {
    showMore("".concat(index, "-").concat(name));
  }

  return /*#__PURE__*/React.createElement("div", {
    key: index,
    className: "operation-content-step"
  }, /*#__PURE__*/React.createElement("div", {
    className: "content-step-title"
  }, jobPodStatus === 'running' ? /*#__PURE__*/React.createElement(_Spin, {
    spinning: true,
    className: "content-step-title-spin"
  }) : /*#__PURE__*/React.createElement(_Icon, {
    type: "wait_circle",
    className: "content-step-icon-".concat(jobPodStatus)
  }), /*#__PURE__*/React.createElement("span", {
    className: "content-step-title-text"
  }, name), log && /*#__PURE__*/React.createElement(_Tooltip, {
    title: formatMessage({
      id: "".concat(intlPrefix, ".instance.cases.log")
    }),
    placement: "bottom"
  }, /*#__PURE__*/React.createElement(_Icon, {
    type: "find_in_page",
    onClick: openLogDetail
  }))), /*#__PURE__*/React.createElement("div", {
    className: "content-step-des"
  }, /*#__PURE__*/React.createElement("pre", {
    className: !flag ? 'content-step-des-hidden' : ''
  }, event), event && event.split('\n').length > 4 ? /*#__PURE__*/React.createElement("a", {
    onClick: handleClick
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: flag ? 'shrink' : 'expand'
  })) : null));
};

var Cases = observer(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix,
      _useResourceStore$res = _useResourceStore.resourceStore.getSelectedMenu,
      id = _useResourceStore$res.id,
      parentId = _useResourceStore$res.parentId;

  var _useInstanceStore = useInstanceStore(),
      formatMessage = _useInstanceStore.intl.formatMessage,
      casesDs = _useInstanceStore.casesDs;

  var _useState3 = useState(null),
      _useState4 = _slicedToArray(_useState3, 2),
      currentCommandId = _useState4[0],
      setCurrentCommandId = _useState4[1];

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      expandKeys = _useState6[0],
      setExpandKeys = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      ignore = _useState8[0],
      setIgnore = _useState8[1];

  var loading = casesDs.status === 'loading';
  useEffect(function () {
    setCurrentCommandId(null);
  }, [id, parentId]);

  function changeEvent(data, isIgnore) {
    setCurrentCommandId(data);
    setIgnore(isIgnore);
  }
  /**
   * 展开更多
   * @param item
   */


  function showMore(item) {
    var data = _toConsumableArray(expandKeys);

    var flag = _.includes(data, item);

    if (flag) {
      var index = _.indexOf(data, item);

      data.splice(index, 1);
    } else {
      data.push(item);
    }

    setExpandKeys(data);
  }

  function istEventDom(data) {
    if (ignore) {
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-instance-cases-empty")
      }, formatMessage({
        id: "".concat(intlPrefix, ".instance.cases.ignore")
      }));
    }

    var podEventVO = data.get('podEventVO');

    var events = _.map(podEventVO, function (_ref2, index) {
      var name = _ref2.name,
          log = _ref2.log,
          event = _ref2.event,
          jobPodStatus = _ref2.jobPodStatus;

      var flag = _.includes(expandKeys, "".concat(index, "-").concat(name));

      var eventData = {
        index: index,
        jobPodStatus: jobPodStatus,
        name: name,
        log: log,
        flag: flag,
        event: event,
        intlPrefix: intlPrefix,
        formatMessage: formatMessage,
        showMore: showMore
      };
      return /*#__PURE__*/React.createElement(InstanceEvent, eventData);
    });

    return events.length ? events : /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-instance-cases-empty")
    }, formatMessage({
      id: "".concat(intlPrefix, ".instance.cases.none")
    }));
  }

  function getContent() {
    var record = casesDs.data;

    if (record.length) {
      var currentPod = casesDs.find(function (data) {
        var commandId = data.get('commandId');
        return commandId === currentCommandId;
      });
      var data = currentPod || casesDs.get(0);
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Operation, {
        handleClick: changeEvent,
        active: currentCommandId
      }), /*#__PURE__*/React.createElement("div", {
        className: "cases-operation-content"
      }, /*#__PURE__*/React.createElement("div", {
        className: "case-operation-main"
      }, istEventDom(data))));
    }

    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-event-empty")
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "info",
      className: "".concat(prefixCls, "-event-empty-icon")
    }), /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-event-empty-text")
    }, formatMessage({
      id: "".concat(intlPrefix, ".instance.cases.empty")
    })));
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-instance-cases")
  }, /*#__PURE__*/React.createElement(_Spin, {
    spinning: loading
  }, getContent()));
});
export default Cases;