import "choerodon-ui/pro/lib/data-set/style";
import _DataSet from "choerodon-ui/pro/lib/data-set";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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, { createContext, useContext, useEffect, useMemo } from 'react';
import { inject } from 'mobx-react';
import { observer } from 'mobx-react-lite';
import { injectIntl } from 'react-intl';
import { forEach, isEmpty, map, keys } from 'lodash';
import { axios } from '@choerodon/boot';
import CreateFormDataSet, { transFormData } from "./CreateFormDataSet";
import PortDataSet from "./PortDataSet";
import AppInstanceOptionsDataSet from "./AppInstanceOptionsDataSet";
import TargetLabelsDataSet from "./TargetLabelsDataSet";
import NetworkInfoDataSet from "./NetworkInfoDataSet";
import EndPointsDataSet from "./EndPointsDataSet";
var NetWorkStore = /*#__PURE__*/createContext();

function useNetWorkStore() {
  return useContext(NetWorkStore);
}

function StoreProvider(props) {
  var projectId = props.AppState.currentMenuType.projectId,
      formatMessage = props.intl.formatMessage,
      children = props.children,
      envId = props.envId,
      networkStore = props.store,
      networkId = props.netId,
      appServiceId = props.appServiceId;
  var appInstanceOptionsDs = useMemo(function () {
    return new _DataSet(AppInstanceOptionsDataSet(projectId, envId, formatMessage));
  }, [projectId, envId]);
  var portDs = useMemo(function () {
    return new _DataSet(PortDataSet({
      formatMessage: formatMessage,
      projectId: projectId,
      envId: envId
    }));
  }, [projectId, envId]);
  var endPointsDs = useMemo(function () {
    return new _DataSet(EndPointsDataSet({
      formatMessage: formatMessage
    }));
  }, []);
  var targetLabelsDs = useMemo(function () {
    return new _DataSet(TargetLabelsDataSet({
      formatMessage: formatMessage
    }));
  }, []);
  var networkInfoDs = useMemo(function () {
    return new _DataSet(NetworkInfoDataSet(projectId, networkId));
  }, [networkId]);
  var formDs = useMemo(function () {
    return new _DataSet(CreateFormDataSet({
      formatMessage: formatMessage,
      portDs: portDs,
      endPointsDs: endPointsDs,
      targetLabelsDs: targetLabelsDs,
      appInstanceOptionsDs: appInstanceOptionsDs,
      networkStore: networkStore,
      projectId: projectId,
      envId: envId,
      networkEdit: {
        networkInfoDs: networkInfoDs,
        networkId: networkId,
        initTargetLabel: initTargetLabel,
        initPorts: initPorts,
        initEndPoints: initEndPoints
      }
    }));
  }, [projectId, envId]);
  useEffect(function () {
    if (networkId && formDs.current) {
      formDs.transport.create = function (_ref) {
        var _ref$data = _slicedToArray(_ref.data, 1),
            data = _ref$data[0];

        return {
          method: 'put',
          url: "/devops/v1/projects/".concat(projectId, "/service/").concat(networkId),
          data: transFormData(data, formatMessage, envId)
        };
      };

      if (appServiceId) {
        appInstanceOptionsDs.transport.read.url = "/devops/v1/projects/".concat(projectId, "/app_service_instances/list_running_instance?env_id=").concat(envId, "&app_service_id=").concat(appServiceId);
        axios.all([networkInfoDs.query(), appInstanceOptionsDs.query()]).then(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 1),
              res = _ref3[0];

          var type = res.type,
              target = res.target,
              _res$target = res.target,
              instances = _res$target.instances,
              targetAppServiceId = _res$target.targetAppServiceId;
          loadInfo({
            data: res,
            formatMessage: formatMessage,
            targetLabelsDs: targetLabelsDs,
            portDs: portDs,
            endPointsDs: endPointsDs,
            formDs: formDs,
            networkInfoDs: networkInfoDs
          }); // 这里做兼容旧数据的处理 一个网络对应部分实例

          if (!targetAppServiceId && instances && instances.length) {
            forEach(instances, function (item, index) {
              if (!appInstanceOptionsDs.find(function (record) {
                return record.get('code') === item.code;
              })) {
                var record = appInstanceOptionsDs.create(item);
                appInstanceOptionsDs.push(record);
              }
            });
          }
        });
      } else {
        networkInfoDs.query().then(function (res) {
          var type = res.type,
              target = res.target,
              _res$target2 = res.target,
              instances = _res$target2.instances,
              targetAppServiceId = _res$target2.targetAppServiceId,
              currentAppServiceId = res.appServiceId;
          loadInfo({
            data: res,
            formatMessage: formatMessage,
            targetLabelsDs: targetLabelsDs,
            portDs: portDs,
            endPointsDs: endPointsDs,
            formDs: formDs,
            networkInfoDs: networkInfoDs
          }); // 这里做兼容旧数据的处理 一个网络对应部分实例

          if (currentAppServiceId || targetAppServiceId) {
            appInstanceOptionsDs.transport.read.url = "/devops/v1/projects/".concat(projectId, "/app_service_instances/list_running_instance?env_id=").concat(envId, "&app_service_id=").concat(currentAppServiceId || targetAppServiceId);
            appInstanceOptionsDs.query().then(function () {
              if (!targetAppServiceId && instances && instances.length) {
                forEach(instances, function (item, index) {
                  if (!appInstanceOptionsDs.find(function (record) {
                    return record.get('code') === item.code;
                  })) {
                    var record = appInstanceOptionsDs.create(item);
                    appInstanceOptionsDs.push(record);
                  }
                });
              }
            });
          }
        });
      }
    }
  }, [networkId, formDs.current]);
  useEffect(function () {
    if (!networkId) {
      portDs.create();
      endPointsDs.create();
      targetLabelsDs.create();
    }
  }, []);

  var value = _objectSpread(_objectSpread({}, props), {}, {
    formDs: formDs,
    portDs: portDs,
    endPointsDs: endPointsDs,
    targetLabelsDs: targetLabelsDs,
    appInstanceOptionsDs: appInstanceOptionsDs,
    networkInfoDs: networkInfoDs,
    networkId: networkId
  });

  return /*#__PURE__*/React.createElement(NetWorkStore.Provider, {
    value: value
  }, children);
}

function loadInfo(_ref4) {
  var data = _ref4.data,
      formatMessage = _ref4.formatMessage,
      targetLabelsDs = _ref4.targetLabelsDs,
      portDs = _ref4.portDs,
      endPointsDs = _ref4.endPointsDs,
      formDs = _ref4.formDs,
      networkInfoDs = _ref4.networkInfoDs;
  var name = data.name,
      id = data.id,
      type = data.type,
      target = data.target,
      config = data.config,
      appServiceId = data.appServiceId;
  var instances = target.instances,
      targetAppServiceId = target.targetAppServiceId,
      selectors = target.selectors,
      endPoints = target.endPoints; // 判断目标对象类型  

  var targetType = 'param';

  if (targetAppServiceId || !isEmpty(instances)) {
    targetType = 'instance';
  }

  if (!isEmpty(endPoints)) {
    targetType = 'endPoints';
  }

  var appInstance = initTargetLabel({
    targetLabelsDs: targetLabelsDs,
    type: targetType,
    record: formDs.current,
    networkInfoDs: networkInfoDs,
    formatMessage: formatMessage
  });
  var externalIps = initPorts({
    portDs: portDs,
    type: type,
    networkInfoDs: networkInfoDs
  });
  var targetIps = initEndPoints({
    endPointsDs: endPointsDs,
    targetLabelsDs: targetLabelsDs,
    record: formDs.current,
    networkInfoDs: networkInfoDs
  });
  formDs.current.init('name', name);
  formDs.current.init('appServiceId', appServiceId);
  formDs.current.init('type', type);
  formDs.current.init('target', targetType);
  formDs.current.init('appInstance', appInstance);
  formDs.current.init('externalIps', externalIps);
  formDs.current.init('targetIps', targetIps);
}

function initTargetLabel(_ref5) {
  var targetLabelsDs = _ref5.targetLabelsDs,
      type = _ref5.type,
      record = _ref5.record,
      networkInfoDs = _ref5.networkInfoDs,
      formatMessage = _ref5.formatMessage;

  var _networkInfoDs$curren = networkInfoDs.current.get('target'),
      instances = _networkInfoDs$curren.instances,
      targetAppServiceId = _networkInfoDs$curren.targetAppServiceId,
      selectors = _networkInfoDs$curren.selectors;

  if (type === 'instance') {
    if (targetAppServiceId) {
      // 如果存在targetAppServiceId那么 实例的值为所有实例
      return formatMessage({
        id: 'all_instance'
      });
    } else if (instances && instances.length) {
      // 如果存在instances 且 有值 那么将appInstance设置为instances数组的第一项（暂且这么处理，后期要对旧数据做兼容处理）
      if (instances.length > 1) {
        return map(instances, function (item) {
          return item.code;
        }).join(',');
      }

      return instances[0].code;
    }
  } else {
    targetLabelsDs.reset();

    if (isEmpty(selectors)) {
      targetLabelsDs.create();
    } else {
      forEach(selectors, function (value, keyword) {
        return targetLabelsDs.create({
          keyword: keyword,
          value: value
        });
      });
    }

    return null;
  }
}

function initPorts(_ref6) {
  var portDs = _ref6.portDs,
      type = _ref6.type,
      networkInfoDs = _ref6.networkInfoDs;

  var _networkInfoDs$curren2 = networkInfoDs.current.get('config'),
      ips = _networkInfoDs$curren2.externalIps,
      ports = _networkInfoDs$curren2.ports;

  portDs.reset();

  if (type === networkInfoDs.current.get('type')) {
    forEach(ports, function (item) {
      portDs.create(item);
    });
  } else {
    portDs.create();
  }

  if (type === 'ClusterIP') {
    if (typeof externalIps === 'string') {
      return [ips];
    } else {
      return ips;
    }
  }
}

function initEndPoints(_ref7) {
  var endPointsDs = _ref7.endPointsDs,
      targetLabelsDs = _ref7.targetLabelsDs,
      record = _ref7.record,
      networkInfoDs = _ref7.networkInfoDs;

  var _networkInfoDs$curren3 = networkInfoDs.current.get('target'),
      endPoints = _networkInfoDs$curren3.endPoints;

  if (!isEmpty(endPoints)) {
    endPointsDs.reset();
    targetLabelsDs.reset();
    record.init('appServiceId', null);
    record.init('appInstance', null);
    var ipstr = keys(endPoints)[0];

    if (ipstr) {
      var targetPortObj = endPoints[ipstr];
      forEach(targetPortObj, function (item) {
        endPointsDs.create({
          targetPort: item.port
        });
      });
      return ipstr.split(',');
    }
  }
}

export var NetWorkStoreProvider = injectIntl(inject('AppState')(observer(StoreProvider)));
export default useNetWorkStore;