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 MouserOverWrapper from "../../../../../../components/MouseOverWrapper/MouserOverWrapper";
import StatusIcon from "../../../../../../components/StatusIcon";
import { useResourceStore } from "../../../../stores";
import { useApplicationStore } from "../stores";
import EditNetwork from "../modals/network2";
import { useMainStore } from "../../../stores";
import DomainForm from "../../../components/domain-form";
import "./index.less";
var Column = _Table.Column;

var editNetWorkKey = _Modal.key();

var editDomainKey = _Modal.key();

var modalStyle = {
  width: 740
};
var Networking = observer(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix,
      _useResourceStore$res = _useResourceStore.resourceStore.getSelectedMenu,
      id = _useResourceStore$res.id,
      parentId = _useResourceStore$res.parentId,
      formatMessage = _useResourceStore.intl.formatMessage,
      projectId = _useResourceStore.AppState.currentMenuType.id,
      treeDs = _useResourceStore.treeDs;

  var _useApplicationStore = useApplicationStore(),
      netDs = _useApplicationStore.netDs,
      domainStore = _useApplicationStore.domainStore,
      networkStore = _useApplicationStore.networkStore;

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

  function refresh() {
    treeDs.query();
    netDs.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 value = _ref.value,
        record = _ref.record;
    var status = record.get('status');
    var error = record.get('error');
    var disabled = getEnvIsNotRunning() || status === 'operating';
    return /*#__PURE__*/React.createElement(StatusIcon, {
      name: value,
      status: status || '',
      error: error || '',
      clickAble: !disabled,
      onClick: openNetworkEdit,
      permissionCode: ['choerodon.code.project.deploy.app-deployment.resource.ps.net-detail']
    });
  }

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

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

    var appId = record.get('appServiceId');
    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,
        targetAppServiceId = _ref5.targetAppServiceId,
        targetAppServiceName = _ref5.targetAppServiceName;

    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, // eslint-disable-next-line consistent-return
    _.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, "-application-net")
        }, /*#__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 netId = record.get('id');
    var name = record.get('name');
    var disabled = getEnvIsNotRunning() || status === 'operating';

    if (disabled) {
      return null;
    }

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

  function openDomainEdit(itemId) {
    _Modal.open({
      key: editDomainKey,
      style: modalStyle,
      drawer: true,
      title: formatMessage({
        id: 'domain.update.head'
      }),
      children: /*#__PURE__*/React.createElement(DomainForm, {
        envId: parentId,
        appServiceId: id,
        ingressId: itemId,
        ingressStore: domainStore,
        refresh: refresh,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls
      }),
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function openNetworkEdit() {
    _Modal.open({
      key: editNetWorkKey,
      title: formatMessage({
        id: 'network.header.create'
      }),
      style: {
        width: 740
      },
      okText: formatMessage({
        id: 'edit'
      }),
      drawer: true,
      children: /*#__PURE__*/React.createElement(EditNetwork, {
        envId: parentId,
        appId: id,
        networkStore: networkStore,
        refresh: refresh,
        networkId: netDs.current.get('id')
      })
    });
  }

  function renderExpandedRow(_ref11) {
    var record = _ref11.record;
    var devopsIngressDTOS = record.get('devopsIngressVOS');
    var content = devopsIngressDTOS && devopsIngressDTOS.length ? _.map(devopsIngressDTOS, function (_ref12) {
      var itemId = _ref12.id,
          name = _ref12.name,
          domain = _ref12.domain,
          error = _ref12.error,
          status = _ref12.status,
          pathList = _ref12.pathList;
      var buttons = [{
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.delete-domain'],
        text: formatMessage({
          id: 'delete'
        }),
        action: function action() {
          return openDeleteModal(parentId, itemId, name, 'ingress', refresh);
        }
      }];
      var disabled = getEnvIsNotRunning() || status === 'operating';
      return /*#__PURE__*/React.createElement("div", {
        key: itemId,
        className: "net-expandedRow-detail"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".application.net.ingress")
      }), "\uFF1A", /*#__PURE__*/React.createElement("div", {
        className: "net-ingress-text"
      }, /*#__PURE__*/React.createElement(StatusIcon, {
        name: name,
        status: status,
        error: error,
        clickAble: !disabled,
        onClick: function onClick() {
          return openDomainEdit(itemId);
        },
        permissionCode: ['choerodon.code.project.deploy.app-deployment.resource.ps.domain-detail']
      })), !disabled && /*#__PURE__*/React.createElement("div", {
        className: "net-ingress-action"
      }, /*#__PURE__*/React.createElement(Action, {
        data: buttons
      })), /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "address"
      }), "\uFF1A", /*#__PURE__*/React.createElement("div", {
        className: "net-ingress-text"
      }, /*#__PURE__*/React.createElement(MouserOverWrapper, {
        text: domain,
        width: 0.2,
        style: {
          display: 'block'
        }
      }, domain)), /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "path"
      }), "\uFF1A", /*#__PURE__*/React.createElement("div", {
        className: "net-ingress-text net-ingress-path"
      }, /*#__PURE__*/React.createElement(MouserOverWrapper, {
        text: pathList[0] ? pathList[0].path : '',
        width: 0.2
      }, pathList[0] ? pathList[0].path : ''), pathList.length > 1 && /*#__PURE__*/React.createElement(_Tooltip, {
        title: _.map(pathList, function (_ref13) {
          var path = _ref13.path;
          return /*#__PURE__*/React.createElement("div", null, path);
        })
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "expand_more",
        className: "net-expend-icon"
      }))));
    }) : /*#__PURE__*/React.createElement("span", {
      className: "net-no-ingress"
    }, formatMessage({
      id: "".concat(intlPrefix, ".application.net.empty")
    }));
    return /*#__PURE__*/React.createElement("div", {
      className: "net-expandedRow-content"
    }, content);
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-application-net")
  }, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tab-table"
  }, /*#__PURE__*/React.createElement(_Table, {
    dataSet: netDs,
    border: false,
    queryBar: "none",
    expandedRowRenderer: renderExpandedRow
  }, /*#__PURE__*/React.createElement(Column, {
    name: "name",
    renderer: renderName
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderAction,
    width: 70
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderTargetType,
    header: formatMessage({
      id: "".concat(intlPrefix, ".application.net.targetType")
    })
  }), /*#__PURE__*/React.createElement(Column, {
    renderer: renderTarget,
    header: formatMessage({
      id: "".concat(intlPrefix, ".application.net.target")
    })
  }), /*#__PURE__*/React.createElement(Column, {
    name: "type",
    renderer: renderConfigType
  }))));
});
export default Networking;