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 CodeManagerApis from "../../../../apis";
export default (function (_ref) {
  var projectId = _ref.projectId,
      appServiceId = _ref.appServiceId,
      formatMessage = _ref.formatMessage,
      contentStore = _ref.contentStore,
      projectOptionsDs = _ref.projectOptionsDs,
      currentProjectData = _ref.currentProjectData;

  function checkBranchName(_x) {
    return _checkBranchName.apply(this, arguments);
  }

  function _checkBranchName() {
    _checkBranchName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {
      var endWith, contain, single, mess, prefix, branchName;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              endWith = /(\/|\.|\.lock)$/;
              contain = /(\s|~|\^|:|\?|\*|\[|\\|\.\.|@\{|\/{2,}){1}/;
              single = /^@+$/;
              mess = true;
              prefix = contentStore.getBranchPrefix;
              branchName = '';

              if (prefix) {
                branchName = "".concat(prefix).concat(value);
              } else {
                branchName = value;
              }

              if (!endWith.test(branchName)) {
                _context.next = 11;
                break;
              }

              mess = formatMessage({
                id: 'branch.checkNameEnd'
              });
              _context.next = 17;
              break;

            case 11:
              if (!(contain.test(branchName) || single.test(branchName))) {
                _context.next = 15;
                break;
              }

              mess = formatMessage({
                id: 'branch.check'
              });
              _context.next = 17;
              break;

            case 15:
              _context.next = 17;
              return axios.get("/devops/v1/projects/".concat(projectId, "/app_service/").concat(appServiceId, "/git/check_branch_name?branch_name=").concat(branchName)).then(function (res) {
                if (res && res.failed || !res) {
                  mess = formatMessage({
                    id: 'branch.check.existence'
                  });
                }
              });

            case 17:
              return _context.abrupt("return", mess);

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

  return {
    autoCreate: true,
    fields: [{
      name: 'issue',
      type: 'object',
      textField: 'summary',
      valueField: 'issueId',
      label: formatMessage({
        id: 'branch.issueName'
      }),
      lookupAxiosConfig: function lookupAxiosConfig(_ref2) {
        var _project$id;

        var record = _ref2.record;
        var project = record === null || record === void 0 ? void 0 : record.get('project');
        var selectedProjectId = (_project$id = project === null || project === void 0 ? void 0 : project.id) !== null && _project$id !== void 0 ? _project$id : projectId;
        return {
          url: CodeManagerApis.loadSummaryData(selectedProjectId),
          method: 'get'
        };
      }
    }, {
      name: 'branchOrigin',
      type: 'string',
      label: formatMessage({
        id: 'branch.source'
      }),
      required: true
    }, {
      name: 'branchType',
      type: 'string',
      required: true,
      label: formatMessage({
        id: 'branch.type'
      })
    }, {
      name: 'branchName',
      label: formatMessage({
        id: 'branch.name'
      }),
      required: true,
      type: 'string',
      defaultValue: '',
      validator: checkBranchName
    }, {
      name: 'project',
      type: 'object',
      textField: 'name',
      valueField: 'id',
      defaultValue: currentProjectData,
      label: formatMessage({
        id: 'branch.issue.source'
      }),
      options: projectOptionsDs,
      ignore: 'always'
    }],
    transport: {
      create: function create(_ref3) {
        var _ref3$data = _slicedToArray(_ref3.data, 1),
            data = _ref3$data[0];

        return {
          url: "/devops/v1/projects/".concat(projectId, "/app_service/").concat(appServiceId, "/git/branch"),
          method: 'post',
          transformRequest: function transformRequest() {
            var _ref4 = data.issue || {},
                issueId = _ref4.issueId;

            var originBranch = data.branchOrigin;
            var type = data.branchType;
            var branchName = type === 'custom' ? data.branchName : "".concat(data.branchType, "-").concat(data.branchName);
            var postData = {
              branchName: branchName,
              issueId: issueId,
              originBranch: originBranch && originBranch.slice(0, -7),
              type: type
            };
            return JSON.stringify(postData);
          }
        };
      }
    },
    events: {
      update: function update(_ref5) {
        var name = _ref5.name,
            value = _ref5.value,
            record = _ref5.record;

        if (name === 'project') {
          var field = record.getField('issue');
          record.get('issue') && record.set('issue', null);
          field.reset();

          if (value) {
            field.fetchLookup();
          }
        }
      }
    }
  };
});