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";
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";
import React, { Fragment, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { observer } from 'mobx-react-lite';
import { Action } from '@choerodon/boot';
import _ from 'lodash';
import classnames from 'classnames';
import StatusIcon from "../../../../../components/StatusIcon";
import ResourceListTitle from "../../components/resource-list-title";
import { useResourceStore } from "../../../stores";
import { useNetworkStore } from "./stores";
import Modals from "./modals";
import EditNetwork from "./modals/network-operation";
import { useMainStore } from "../../stores";
import "./index.less";
var Column = _Table.Column;

var modalKey = _Modal.key();

var modalStyle = {
  width: 740
};
var NetworkContent = observer(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix,
      parentId = _useResourceStore.resourceStore.getSelectedMenu.parentId,
      treeDs = _useResourceStore.treeDs;

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

  var _useNetworkStore = useNetworkStore(),
      networkDs = _useNetworkStore.networkDs,
      formatMessage = _useNetworkStore.intl.formatMessage;

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

  function getEnvIsNotRunning() {
    var envRecord = treeDs.find(function (record) {
      return record.get('key') === parentId;
    });
    var connect = envRecord.get('connect');
    return !connect;
  }

  function renderName(_ref) {
    var record = _ref.record;
    var name = record.get('name');
    var status = record.get('status');
    var error = record.get('error');
    return /*#__PURE__*/React.createElement(StatusIcon, {
      name: name,
      status: status || '',
      error: error || ''
    });
  }

  function renderTargetType(_ref2) {
    var record = _ref2.record;

    var _ref3 = record.get('target') || {},
        instances = _ref3.instances,
        selectors = _ref3.selectors,
        targetAppServiceId = _ref3.targetAppServiceId;

    var type = 'EndPoints';

    if (targetAppServiceId) {
      type = formatMessage({
        id: 'all_instance'
      });
    } else if (instances && instances.length) {
      type = formatMessage({
        id: 'instance'
      });
    } else if (selectors) {
      type = formatMessage({
        id: 'label'
      });
    }

    return /*#__PURE__*/React.createElement("span", null, type);
  }

  function renderTarget(_ref4) {
    var record = _ref4.record;

    var _ref5 = record.get('target') || {},
        instances = _ref5.instances,
        selectors = _ref5.selectors,
        endPoints = _ref5.endPoints,
        targetAppServiceName = _ref5.targetAppServiceName,
        targetAppServiceId = _ref5.targetAppServiceId;

    var node = [];
    var port = [];
    var len = endPoints ? 2 : 1;

    if (targetAppServiceId && targetAppServiceName) {
      node.push( /*#__PURE__*/React.createElement("div", {
        className: "net-target-item"
      }, /*#__PURE__*/React.createElement("span", null, targetAppServiceName)));
    } else if (instances && instances.length) {
      _.forEach(instances, function (_ref6) {
        var itemId = _ref6.id,
            code = _ref6.code,
            status = _ref6.status;
        var targetClass = classnames({
          'net-target-item': true,
          'net-target-item-failed': status !== 'operating' && status !== 'running'
        });

        if (code) {
          node.push( /*#__PURE__*/React.createElement("div", {
            className: targetClass,
            key: itemId
          }, /*#__PURE__*/React.createElement(_Tooltip, {
            title: formatMessage({
              id: status || "".concat(intlPrefix, ".application.net.deleted")
            }),
            placement: "top"
          }, code)));
        }
      });
    }

    if (!_.isEmpty(selectors)) {
      _.forEach(selectors, function (value, key) {
        return node.push( /*#__PURE__*/React.createElement("div", {
          className: "net-target-item",
          key: key
        }, /*#__PURE__*/React.createElement("span", null, key), "=", /*#__PURE__*/React.createElement("span", null, value)));
      });
    }

    if (endPoints) {
      var targetIps = _.split(_.keys(endPoints)[0], ',');

      var portList = _.values(endPoints)[0];

      _.map(targetIps, function (item, index) {
        return node.push( /*#__PURE__*/React.createElement("div", {
          className: "net-target-item",
          key: index
        }, /*#__PURE__*/React.createElement("span", null, item)));
      });

      _.map(portList, function (item, index) {
        port.push( /*#__PURE__*/React.createElement("div", {
          className: "net-target-item",
          key: index
        }, /*#__PURE__*/React.createElement("span", null, item.port)));
      });
    }

    return /*#__PURE__*/React.createElement(React.Fragment, null, _.map([node, port], function (item, index) {
      if (item.length) {
        return /*#__PURE__*/React.createElement("div", {
          className: "net-target-wrap",
          key: index
        }, item[0], endPoints && /*#__PURE__*/React.createElement("div", {
          className: "net-target-Ip"
        }, item[1] || null), item.length > len && /*#__PURE__*/React.createElement(_Popover, {
          arrowPointAtCenter: true,
          placement: "bottomRight",
          content: /*#__PURE__*/React.createElement(React.Fragment, null, item),
          overlayClassName: "".concat(prefixCls, "-network-table")
        }, /*#__PURE__*/React.createElement(_Icon, {
          type: "expand_more",
          className: "net-expend-icon"
        })));
      }
    }));
  }

  function renderConfigType(_ref7) {
    var record = _ref7.record;

    var _ref8 = record.get('config') || {},
        externalIps = _ref8.externalIps,
        ports = _ref8.ports;

    var loadBalanceIp = record.get('loadBalanceIp');
    var type = record.get('type');
    var iPArr = [];
    var portArr = [];

    if (externalIps && externalIps.length) {
      _.forEach(externalIps, function (item) {
        return iPArr.push( /*#__PURE__*/React.createElement("div", {
          key: item,
          className: "net-config-item"
        }, item));
      });
    }

    if (ports && ports.length) {
      _.forEach(ports, function (_ref9) {
        var nodePort = _ref9.nodePort,
            port = _ref9.port,
            targetPort = _ref9.targetPort;
        portArr.push( /*#__PURE__*/React.createElement("div", {
          key: port,
          className: "net-config-item"
        }, nodePort || type !== 'ClusterIP' && formatMessage({
          id: 'null'
        }), ' ', port, ' ', targetPort));
      });
    }

    var content = null;

    switch (type) {
      case 'ClusterIP':
        content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: "net-config-wrap"
        }, /*#__PURE__*/React.createElement("div", {
          className: "net-type-title"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".application.net.ip")
        })), /*#__PURE__*/React.createElement("div", null, externalIps ? iPArr : '-')), /*#__PURE__*/React.createElement("div", {
          className: "net-config-wrap"
        }, /*#__PURE__*/React.createElement("div", {
          className: "net-type-title"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".application.net.port")
        })), /*#__PURE__*/React.createElement("div", null, portArr)));
        break;

      case 'NodePort':
        content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: "net-config-item"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".application.net.nport")
        })), /*#__PURE__*/React.createElement("div", null, portArr));
        break;

      case 'LoadBalancer':
        content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: "net-config-wrap"
        }, /*#__PURE__*/React.createElement("div", {
          className: "net-type-title"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "".concat(intlPrefix, ".application.net.nport")
        })), /*#__PURE__*/React.createElement("div", null, portArr)), loadBalanceIp && /*#__PURE__*/React.createElement("div", {
          className: "net-config-wrap"
        }, /*#__PURE__*/React.createElement("div", {
          className: "net-type-title"
        }, /*#__PURE__*/React.createElement("span", null, "LoadBalancer IP")), /*#__PURE__*/React.createElement("div", null, loadBalanceIp)));
        break;

      default:
        break;
    }

    return /*#__PURE__*/React.createElement("div", {
      className: "net-config-content"
    }, /*#__PURE__*/React.createElement("span", {
      className: "net-config-type"
    }, type), /*#__PURE__*/React.createElement(_Tooltip, {
      arrowPointAtCenter: true,
      placement: "bottomRight",
      title: content
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "expand_more",
      className: "net-expend-icon"
    })));
  }

  function renderAction(_ref10) {
    var record = _ref10.record;
    var status = record.get('status');
    var disabled = getEnvIsNotRunning() || status === 'operating';

    if (disabled) {
      return null;
    }

    var id = record.get('id');
    var name = record.get('name');
    var buttons = [{
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.update-net'],
      text: formatMessage({
        id: 'edit'
      }),
      action: openModal
    }, {
      service: ['choerodon.code.project.deploy.app-deployment.resource.ps.delete-net'],
      text: formatMessage({
        id: 'delete'
      }),
      action: function action() {
        return openDeleteModal(parentId, id, name, 'service', refresh);
      }
    }];
    return /*#__PURE__*/React.createElement(Action, {
      data: buttons
    });
  }

  function openModal() {
    _Modal.open({
      key: modalKey,
      style: modalStyle,
      drawer: true,
      title: formatMessage({
        id: 'network.header.update'
      }),
      children: /*#__PURE__*/React.createElement(EditNetwork, {
        netId: networkDs.current.get('id'),
        envId: parentId,
        appServiceId: networkDs.current.get('appServiceId'),
        store: networkStore,
        refresh: refresh
      }),
      okText: formatMessage({
        id: 'save'
      }),
      afterClose: function afterClose() {
        return networkStore.setSingleData([]);
      }
    });
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-network-table")
  }, /*#__PURE__*/React.createElement(Modals, null), /*#__PURE__*/React.createElement(ResourceListTitle, {
    type: "services"
  }), /*#__PURE__*/React.createElement(_Table, {
    dataSet: networkDs,
    border: false,
    queryBar: "bar"
  }, /*#__PURE__*/React.createElement(Column, {
    name: "name",
    renderer: renderName,
    sortable: true
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderTargetType,
    header: formatMessage({
      id: "".concat(intlPrefix, ".application.net.targetType")
    }),
    width: "1.2rem"
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderTarget,
    header: formatMessage({
      id: "".concat(intlPrefix, ".application.net.target")
    })
  }), /*#__PURE__*/React.createElement(Column, {
    name: "type",
    renderer: renderConfigType,
    width: "1.5rem"
  })));
});
export default NetworkContent;