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 no-underscore-dangle */
import React, { useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import uuidv1 from 'uuid/v1';
import Cookies from 'universal-cookie';
import Loading from "../../../../../components/loading";
import ResourceTitle from "../../components/resource-title";
import { removeEndsChar } from "../../../../../utils";
import { useResourceStore } from "../../../stores";
import { useCustomDetailStore } from "./stores";
import Modals from "./modals";
import "./index.less";
var TIMEOUT_TIME = 50000;
var cookies = new Cookies();

var getAccessToken = function getAccessToken() {
  return cookies.get('access_token');
};

var Content = observer(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      projectId = _useResourceStore.AppState.currentMenuType.projectId;

  var _useState = useState('暂无数据'),
      _useState2 = _slicedToArray(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  var _useState3 = useState(true),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var _useCustomDetailStore = useCustomDetailStore(),
      detailDs = _useCustomDetailStore.detailDs;

  var ws;
  var retry = false;
  useEffect(function () {
    initSocket();
    return function () {
      if (ws) {
        destroySocket();
      }
    };
  }, [detailDs.current]);

  function destroySocket() {
    ws.removeEventListener('message', handleMessage);
    ws.removeEventListener('error', handleError);
    ws.close();
  }

  function initSocket() {
    setLoading(true);
    var record = detailDs.current;

    if (record) {
      var id = record.get('id');
      var clusterId = record.get('clusterId');
      var name = record.get('name');
      var kind = record.get('k8sKind');
      var env = record.get('envCode');

      try {
        var wsHost = removeEndsChar(window._env_.DEVOPS_HOST, '/');
        var key = "cluster:".concat(clusterId, ".describe:").concat(uuidv1());
        var secretKey = window._env_.DEVOPS_WEBSOCKET_SECRET_KEY;
        var url = "".concat(wsHost, "/websocket?key=").concat(key, "&group=from_front:").concat(key, "&processor=front_describe&secret_key=").concat(secretKey, "&env=").concat(env, "&kind=").concat(kind, "&name=").concat(name, "&describeId=").concat(id, "&clusterId=").concat(clusterId, "&oauthToken=").concat(getAccessToken(), "&projectId=").concat(projectId);
        ws = new WebSocket(url);
        ws.addEventListener('message', handleMessage);
        ws.addEventListener('error', handleError);
      } catch (e) {
        setValue('请求失败，请稍后重试！');
      }
    }
  }

  function handleMessage(_ref) {
    var data = _ref.data;

    try {
      var _ref2 = JSON.parse(data) || {},
          message = _ref2.message;

      var newMessage = message && JSON.parse(message) ? JSON.parse(message).payload || '' : '';
      setValue(newMessage);
      setLoading(false);
      destroySocket();
    } catch (e) {
      setValue('请求失败，请稍后重试！');
    }
  }

  function handleError(e) {
    setValue(JSON.stringify(e));

    if (!retry) {
      retry = true;
      setTimeout(function () {
        retry = false;
        destroySocket();
        initSocket();
      }, TIMEOUT_TIME);
    }
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-custom-detail")
  }, /*#__PURE__*/React.createElement(ResourceTitle, {
    iconType: "filter_b_and_w",
    record: detailDs.current,
    statusKey: "commandStatus",
    errorKey: "commandErrors"
  }), /*#__PURE__*/React.createElement("pre", {
    className: "custom-detail-section-content"
  }, loading ? /*#__PURE__*/React.createElement(Loading, {
    display: true
  }) : value), /*#__PURE__*/React.createElement(Modals, null));
});
export default Content;