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; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import { axios } from '@choerodon/boot';
import { omit, pick, map, compact, forEach, get, isEmpty } from 'lodash';

function getIpRequired(_ref) {
  var record = _ref.record;
  return record.get('type') === 'NFS';
}

function getNodeIpRequired(_ref2) {
  var record = _ref2.record;
  return record.get('type') === 'LocalPV';
}

export default (function (_ref3) {
  var intlPrefix = _ref3.intlPrefix,
      formatMessage = _ref3.formatMessage,
      projectId = _ref3.projectId,
      typeDs = _ref3.typeDs,
      modeDs = _ref3.modeDs,
      storageDs = _ref3.storageDs,
      clusterDs = _ref3.clusterDs,
      projectOptionsDs = _ref3.projectOptionsDs,
      projectTableDs = _ref3.projectTableDs,
      nodeNameDs = _ref3.nodeNameDs,
      labelDs = _ref3.labelDs;

  function checkName(_x, _x2, _x3) {
    return _checkName.apply(this, arguments);
  }

  function _checkName() {
    _checkName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value, name, record) {
      var pa, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              pa = /^[a-z]([-.a-z0-9]*[a-z0-9])?$/;

              if (value) {
                _context.next = 3;
                break;
              }

              return _context.abrupt("return", true);

            case 3:
              if (!pa.test(value)) {
                _context.next = 18;
                break;
              }

              _context.prev = 4;
              _context.next = 7;
              return axios.get("/devops/v1/projects/".concat(projectId, "/pvs/check_name?clusterId=").concat(record.get('clusterId'), "&pvName=").concat(value));

            case 7:
              res = _context.sent;

              if (!(res && res.failed || !res)) {
                _context.next = 10;
                break;
              }

              return _context.abrupt("return", formatMessage({
                id: 'checkNameExist'
              }));

            case 10:
              return _context.abrupt("return", true);

            case 13:
              _context.prev = 13;
              _context.t0 = _context["catch"](4);
              return _context.abrupt("return", formatMessage({
                id: 'checkNameFailed'
              }));

            case 16:
              _context.next = 19;
              break;

            case 18:
              return _context.abrupt("return", formatMessage({
                id: "".concat(intlPrefix, ".name.failed")
              }));

            case 19:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[4, 13]]);
    }));
    return _checkName.apply(this, arguments);
  }

  function checkIp(value) {
    var pa = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;

    if (value && !pa.test(value)) {
      return formatMessage({
        id: "".concat(intlPrefix, ".ip.failed")
      });
    }

    return true;
  }

  function checkPath(value) {
    var pa = /^\/([-\w]+[.]*[-\w]*[.]*\/?)+/;

    if (value && !pa.test(value)) {
      return formatMessage({
        id: "".concat(intlPrefix, ".path.failed")
      });
    }

    return true;
  }

  function handleUpdate(_ref4) {
    var value = _ref4.value,
        record = _ref4.record,
        name = _ref4.name;

    if (name === 'clusterId' && value) {
      var cluster = clusterDs.find(function (clusterRecord) {
        return clusterRecord.get('id') === value;
      });

      if (cluster) {
        if (cluster.get('skipCheckProjectPermission')) {
          // eslint-disable-next-line no-param-reassign
          projectOptionsDs.transport.read.url = "/devops/v1/projects/".concat(projectId, "/page_projects");
        } else {
          // eslint-disable-next-line no-param-reassign
          projectOptionsDs.transport.read.url = "/devops/v1/projects/".concat(projectId, "/clusters/").concat(value, "/permission/page_related");
        }
      }

      nodeNameDs.removeAll();
      nodeNameDs.setQueryParameter('clusterId', value);
      nodeNameDs.query();
    }
  }

  return {
    autoCreate: true,
    autoQuery: false,
    selection: false,
    children: {
      projects: projectTableDs,
      labels: labelDs
    },
    transport: {
      create: function create(_ref5) {
        var _ref5$data = _slicedToArray(_ref5.data, 1),
            data = _ref5$data[0];

        // eslint-disable-next-line no-param-reassign
        data.nodeName = data.clusterNodeName;
        var res = omit(data, ['__id', '__status', 'storage', 'unit', 'server', 'path', 'projects', 'nodeName']);
        var arr = ['path'];
        var labels = {};

        if (data.type === 'NFS') {
          arr.push('server');
        } else if (data.type === 'LocalPV') {
          arr.push('nodeName');
        }

        res.requestResource = "".concat(data.storage).concat(data.unit);
        res.valueConfig = JSON.stringify(pick(data, arr));
        res.projectIds = data.skipCheckProjectPermission ? [] : compact(map(data.projects, 'projectId') || []);
        forEach(data.labels || [], function (item) {
          var labelKey = get(item, 'key');
          var labelValue = get(item, 'value');

          if (labelKey && labelValue) {
            labels[labelKey] = labelValue;
          }
        });
        res.labels = isEmpty(labels) ? null : JSON.stringify(labels);
        return {
          url: "/devops/v1/projects/".concat(projectId, "/pvs"),
          method: 'post',
          data: res
        };
      }
    },
    fields: [{
      name: 'clusterId',
      type: 'string',
      textField: 'name',
      valueField: 'id',
      label: formatMessage({
        id: "".concat(intlPrefix, ".cluster")
      }),
      required: true,
      options: clusterDs
    }, {
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: 'name'
      }),
      required: true,
      maxLength: 30,
      validator: checkName
    }, {
      name: 'description',
      type: 'string',
      label: formatMessage({
        id: 'description'
      }),
      maxLength: 40
    }, {
      name: 'type',
      type: 'string',
      textField: 'value',
      defaultValue: 'NFS',
      label: formatMessage({
        id: "".concat(intlPrefix, ".type")
      }),
      required: true,
      options: typeDs
    }, {
      name: 'accessModes',
      type: 'string',
      textField: 'value',
      label: formatMessage({
        id: "".concat(intlPrefix, ".mode")
      }),
      required: true,
      options: modeDs,
      defaultValue: 'ReadWriteMany'
    }, {
      name: 'storage',
      type: 'number',
      label: formatMessage({
        id: "".concat(intlPrefix, ".storage")
      }),
      required: true,
      min: 1
    }, {
      name: 'unit',
      type: 'string',
      textField: 'value',
      defaultValue: 'Gi',
      options: storageDs
    }, {
      name: 'path',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".path")
      }),
      required: true,
      validator: checkPath
    }, {
      name: 'server',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".ip")
      }),
      validator: checkIp,
      dynamicProps: {
        required: getIpRequired
      }
    }, {
      name: 'clusterNodeName',
      type: 'string',
      textField: 'value',
      valueField: 'value',
      label: formatMessage({
        id: "".concat(intlPrefix, ".node.name")
      }),
      dynamicProps: {
        required: getNodeIpRequired
      },
      options: nodeNameDs
    }, {
      name: 'skipCheckProjectPermission',
      type: 'boolean',
      defaultValue: true
    }],
    events: {
      update: handleUpdate
    }
  };
});