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 { injectIntl } from 'react-intl';
import { forEach, isEmpty, map } from 'lodash';
import CreateFormDataSet, { transFormData } from "./CreateFormDataSet";
import PortDataSet from "./PortDataSet";
import AppInstanceOptionsDataSet from "./AppInstanceOptionsDataSet";
import KeyOptionsDataSet from "./KeyOptionsDataSet";
import TargetLabelsDataSet from "./TargetLabelsDataSet";
import NetworkInfoDataSet from "./NetworkInfoDataSet";
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,
      appId = props.appId,
      networkStore = props.networkStore,
      networkId = props.networkId;
  var appInstanceOptionsDs = useMemo(function () {
    return new _DataSet(AppInstanceOptionsDataSet(projectId, envId, appId, formatMessage));
  }, [projectId, envId, appId]);
  var keyOptionsDs = useMemo(function () {
    return new _DataSet(KeyOptionsDataSet(projectId, envId, appId));
  }, [projectId, envId, appId]);
  var portDs = useMemo(function () {
    return new _DataSet(PortDataSet({
      formatMessage: formatMessage,
      projectId: projectId,
      envId: envId,
      appId: appId
    }));
  }, [projectId, envId, appId]);
  var targetLabelsDs = useMemo(function () {
    return new _DataSet(TargetLabelsDataSet({
      formatMessage: formatMessage,
      keyOptionsDs: keyOptionsDs
    }));
  }, [keyOptionsDs]);
  var networkInfoDs = useMemo(function () {
    return new _DataSet(NetworkInfoDataSet(projectId, networkId));
  }, [networkId]);
  var formDs = useMemo(function () {
    return new _DataSet(CreateFormDataSet({
      formatMessage: formatMessage,
      portDs: portDs,
      targetLabelsDs: targetLabelsDs,
      appInstanceOptionsDs: appInstanceOptionsDs,
      networkStore: networkStore,
      projectId: projectId,
      envId: envId,
      appId: appId,
      networkEdit: {
        networkInfoDs: networkInfoDs,
        networkId: networkId,
        initTargetLabel: initTargetLabel,
        initPorts: initPorts
      }
    }));
  }, [projectId, envId, appId]);
  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, appId, envId)
        };
      };

      networkInfoDs.query().then(function (res) {
        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,
          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);
            }
          });
        }
      });
    }
  }, [networkId, formDs.current]);
  useEffect(function () {
    if (!networkId) {
      portDs.create();
      targetLabelsDs.create();
    }
  }, []);

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

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

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

  var targetType = 'param';

  if (targetAppServiceId || instances && instances.length) {
    targetType = 'instance';
  }

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

function initTargetLabel(_ref3) {
  var targetLabelsDs = _ref3.targetLabelsDs,
      type = _ref3.type,
      record = _ref3.record,
      networkInfoDs = _ref3.networkInfoDs,
      formatMessage = _ref3.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(_ref4) {
  var portDs = _ref4.portDs,
      type = _ref4.type,
      networkInfoDs = _ref4.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;
    }
  }
}

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