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 pick from 'lodash/pick';
import isEmpty from 'lodash/isEmpty';

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

  switch (name) {
    case 'chartType':
      if (value === 'default') {
        record.set('chartStatus', '');
      }

      break;

    case 'url':
    case 'userName':
    case 'password':
      record.set('chartStatus', '');
      break;

    default:
      break;
  }
}

function handleLoad(_ref2) {
  var dataSet = _ref2.dataSet;
  var record = dataSet.current;

  if (!record) {
    return;
  }

  var chart = record.get('chart');

  if (!isEmpty(chart)) {
    var _ref3 = chart.config || {},
        url = _ref3.url,
        userName = _ref3.userName,
        password = _ref3.password;

    record.init('chartCustom', 'custom');
    record.init('url', url);
    record.init('userName', userName);
    record.init('password', password);
  } else {
    record.init('chartCustom', 'default');
  }
}

function getRequestData(data, res) {
  var url = data.url,
      userName = data.userName,
      password = data.password,
      chartType = data.chartType;

  if (chartType === 'custom') {
    if (isEmpty(res.chart)) {
      res.chart = {
        type: 'chart',
        config: {}
      };
    }

    res.chart.custom = true;
    res.chart.config.url = url;
    res.chart.config.userName = userName;
    res.chart.config.password = password;
  } else {
    res.chart = null;
  }
}

function getChartRequired(_ref4) {
  var record = _ref4.record;
  return record.status !== 'add' && record.get('chartType') === 'custom';
}

export default (function (_ref5) {
  var intlPrefix = _ref5.intlPrefix,
      formatMessage = _ref5.formatMessage,
      projectId = _ref5.projectId,
      appServiceId = _ref5.appServiceId,
      dockerDs = _ref5.dockerDs;

  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 = /^\S+$/;

              if (!(value && value === record.getPristineValue('name'))) {
                _context.next = 3;
                break;
              }

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

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

              _context.prev = 4;
              _context.next = 7;
              return axios.get("/devops/v1/projects/".concat(projectId, "/app_service/check_name?name=").concat(encodeURIComponent(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: "".concat(intlPrefix, ".name.failed")
              }));

            case 16:
              _context.next = 19;
              break;

            case 18:
              return _context.abrupt("return", formatMessage({
                id: 'nameCanNotHasSpaces'
              }));

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

  function checkUserName(value, name, record) {
    if (!value && record.get('password')) {
      return formatMessage({
        id: "".concat(intlPrefix, ".chart.check.failed")
      });
    }

    return true;
  }

  function checkPassword(value, name, record) {
    if (!value && record.get('userName')) {
      return formatMessage({
        id: "".concat(intlPrefix, ".chart.check.failed")
      });
    }

    return true;
  }

  function checkPom(value, name, record) {
    var pa = /^[A-Za-z0-9_\-.]+$/;

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

    return true;
  }

  return {
    autoCreate: false,
    autoQuery: false,
    selection: false,
    dataKey: null,
    paging: false,
    transport: {
      read: {
        url: "/devops/v1/projects/".concat(projectId, "/app_service/").concat(appServiceId),
        method: 'get'
      },
      update: function update(_ref6) {
        var _ref6$data = _slicedToArray(_ref6.data, 1),
            data = _ref6$data[0];

        var res = pick(data, ['id', 'name', 'chart', 'objectVersionNumber', 'imgUrl', 'harborRepoConfigDTO', 'artifactId', 'groupId']);
        getRequestData(data, res);
        return {
          url: "/devops/v1/projects/".concat(projectId, "/app_service"),
          method: 'put',
          data: res
        };
      }
    },
    fields: [{
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".name")
      }),
      required: true,
      validator: checkName,
      maxLength: 40
    }, {
      name: 'code',
      type: 'string'
    }, {
      name: 'type',
      type: 'string'
    }, {
      name: 'imgUrl',
      type: 'string'
    }, {
      name: 'objectVersionNumber',
      type: 'number'
    }, {
      name: 'chart',
      type: 'object'
    }, {
      name: 'url',
      type: 'url',
      label: formatMessage({
        id: 'address'
      }),
      dynamicProps: {
        required: getChartRequired
      }
    }, {
      name: 'userName',
      type: 'string',
      label: formatMessage({
        id: 'userName'
      }),
      validator: checkUserName
    }, {
      name: 'password',
      type: 'string',
      label: formatMessage({
        id: 'password'
      }),
      validator: checkPassword
    }, {
      name: 'chartStatus',
      type: 'string',
      defaultValue: ''
    }, {
      name: 'chartType',
      type: 'string',
      defaultValue: 'default',
      label: formatMessage({
        id: "".concat(intlPrefix, ".helm")
      })
    }, {
      name: 'harborRepoConfigDTO',
      type: 'object',
      textField: 'repoName',
      valueField: 'repoId',
      label: formatMessage({
        id: "".concat(intlPrefix, ".docker")
      }),
      options: dockerDs
    }, {
      name: 'artifactId',
      label: 'artifactId',
      validator: checkPom,
      maxLength: 512
    }, {
      name: 'groupId',
      label: 'groupId',
      validator: checkPom,
      maxLength: 512
    }],
    events: {
      update: handleUpdate,
      load: handleLoad
    }
  };
});