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 find from 'lodash/find';
import omit from 'lodash/omit';
import JSONbig from 'json-bigint';

function formatData(data) {
  var res = omit(data, ['__id', '__status']);
  var shareLevel = res.shareLevel;

  if (shareLevel.id !== 'all') {
    res.projectId = shareLevel.id;
    res.projectName = shareLevel.name;
    res.shareLevel = 'project';
  } else {
    res.projectId = null;
    res.projectName = null;
    res.shareLevel = 'organization';
  }

  return res;
}

function handleUpdate(_x) {
  return _handleUpdate.apply(this, arguments);
}

function _handleUpdate() {
  _handleUpdate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
    var name, record, field, res;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            name = _ref.name, record = _ref.record;

            if (name === 'versionType' || name === 'version') {
              record.set('hasFailed', false);
            }

            if (!(name === 'versionType')) {
              _context.next = 9;
              break;
            }

            field = record.getField('version');
            field.reset();
            _context.next = 7;
            return record.getField('version').fetchLookup();

          case 7:
            res = _context.sent;

            if (record.get('versionType') && record.get('version') && !find(res, function (_ref8) {
              var version = _ref8.version;
              return version === record.get('version');
            })) {
              record.set('version', null);
            }

          case 9:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _handleUpdate.apply(this, arguments);
}

export default (function (_ref2) {
  var intlPrefix = _ref2.intlPrefix,
      formatMessage = _ref2.formatMessage,
      projectId = _ref2.projectId,
      appServiceId = _ref2.appServiceId,
      shareId = _ref2.shareId;

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

    if (record.get('shareLevel') === 'organization') {
      record.init('shareLevel', {
        id: 'all',
        name: formatMessage({
          id: "".concat(intlPrefix, ".project.all")
        })
      });
    } else {
      record.init('shareLevel', {
        id: record.get('projectId'),
        name: record.get('projectName')
      });
    }
  }

  return {
    autoQuery: false,
    autoCreate: false,
    selection: false,
    paging: false,
    autoQueryAfterSubmit: false,
    transport: {
      read: {
        url: "/devops/v1/projects/".concat(projectId, "/app_service_share/").concat(shareId),
        method: 'get'
      },
      create: function create(_ref4) {
        var _ref4$data = _slicedToArray(_ref4.data, 1),
            data = _ref4$data[0];

        var res = formatData(data);
        res.appServiceId = appServiceId;
        return {
          url: "/devops/v1/projects/".concat(projectId, "/app_service_share"),
          method: 'post',
          data: res
        };
      },
      update: function update(_ref5) {
        var _ref5$data = _slicedToArray(_ref5.data, 1),
            data = _ref5$data[0];

        var res = formatData(data);
        return {
          url: "/devops/v1/projects/".concat(projectId, "/app_service_share"),
          method: 'put',
          data: res
        };
      }
    },
    fields: [{
      name: 'versionType',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".version.type")
      })
    }, {
      name: 'version',
      type: 'string',
      textField: 'version',
      valueField: 'version',
      dynamicProps: {
        lookupAxiosConfig: function lookupAxiosConfig(_ref6) {
          var record = _ref6.record;
          return {
            url: "/devops/v1/projects/".concat(projectId, "/app_service_versions/page_by_options?app_service_id=").concat(appServiceId, "&deploy_only=false&do_page=true&page=1&size=40"),
            method: 'post',
            data: {
              params: [],
              searchParam: {
                version: record.get('versionType')
              }
            }
          };
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".version.specific")
      })
    }, {
      name: 'shareLevel',
      type: 'object',
      textField: 'name',
      valueField: 'id',
      label: formatMessage({
        id: "".concat(intlPrefix, ".share.range")
      }),
      required: true,
      lookupAxiosConfig: function lookupAxiosConfig(_ref7) {
        var params = _ref7.params;
        return {
          method: 'get',
          url: "/iam/choerodon/v1/projects/".concat(projectId, "/except_self/with_limit"),
          data: params,
          transformResponse: function transformResponse(data) {
            try {
              var array = JSONbig.parse(data);

              if (array.length > 1) {
                var obj = {
                  id: 'all',
                  name: formatMessage({
                    id: "".concat(intlPrefix, ".project.all")
                  })
                };
                array.unshift(obj);
              }

              return array;
            } catch (e) {
              return data;
            }
          }
        };
      }
    }, {
      name: 'hasFailed',
      type: 'boolean',
      defaultValue: false,
      ignore: 'always'
    }],
    events: {
      load: handleLoad,
      update: handleUpdate
    }
  };
});