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

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 { DataSet } from "../../../../../interface";
import TemplateApis from "../../../apis";
import TemplateServices from "../../../services";

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

            if (!(value && !templateId)) {
              _context.next = 17;
              break;
            }

            if (!pa.test(value)) {
              _context.next = 16;
              break;
            }

            _context.prev = 4;
            _context.next = 7;
            return TemplateServices.checkNameOrCode({
              type: 'code',
              value: value,
              organizationId: organizationId
            });

          case 7:
            res = _context.sent;

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

            return _context.abrupt("return", '编码已存在');

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

          case 13:
            _context.prev = 13;
            _context.t0 = _context["catch"](4);
            return _context.abrupt("return", '编码重名校验失败，请稍后再试');

          case 16:
            return _context.abrupt("return", '编码只能由小写字母、数字、"-"组成，且以小写字母开头，不能以"-"结尾');

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

          case 18:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[4, 13]]);
  }));

  return function codeValidator(_x) {
    return _ref2.apply(this, arguments);
  };
}();

var checkName = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref3) {
    var value, name, record, templateId, organizationId, res;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            value = _ref3.value, name = _ref3.name, record = _ref3.record, templateId = _ref3.templateId, organizationId = _ref3.organizationId;

            if (!(value && record && value !== record.getPristineValue(name))) {
              _context2.next = 14;
              break;
            }

            _context2.prev = 2;
            _context2.next = 5;
            return TemplateServices.checkNameOrCode({
              type: 'name',
              value: value,
              templateId: templateId,
              organizationId: organizationId
            });

          case 5:
            res = _context2.sent;

            if (!(res && res.failed || !res)) {
              _context2.next = 8;
              break;
            }

            return _context2.abrupt("return", '名称已存在');

          case 8:
            return _context2.abrupt("return", true);

          case 11:
            _context2.prev = 11;
            _context2.t0 = _context2["catch"](2);
            return _context2.abrupt("return", '名称重名校验失败，请稍后再试');

          case 14:
            return _context2.abrupt("return", true);

          case 15:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[2, 11]]);
  }));

  return function checkName(_x2) {
    return _ref4.apply(this, arguments);
  };
}();

var mapping = {
  templateName: {
    name: 'name',
    type: 'string',
    label: '模板名称',
    required: true,
    maxLength: 40
  },
  templateCode: {
    name: 'code',
    type: 'string',
    label: '模板编码',
    required: true,
    maxLength: 30
  },
  createWay: {
    name: 'createType',
    type: 'string',
    label: '创建方式',
    textField: 'text',
    valueField: 'value',
    defaultValue: 'template',
    options: new DataSet({
      data: [{
        value: 'template',
        text: '基于已有模板创建'
      }, {
        value: 'gitlab',
        text: '从GitLab导入模板'
      }, {
        value: 'github',
        text: '从Github导入模板'
      }]
    })
  },
  templateSource: {
    name: 'templateSource',
    type: 'string',
    label: '模板来源',
    textField: 'text',
    valueField: 'value',
    defaultValue: 'site',
    options: new DataSet({
      data: [{
        value: 'site',
        text: '平台层已有模板'
      }, {
        value: 'organization',
        text: '组织层已有模板'
      }]
    })
  },
  appTemplate: {
    name: 'selectedTemplateId',
    type: 'string',
    label: '应用模板',
    textField: 'name',
    valueField: 'id'
  },
  gitlabAddress: {
    name: 'gitlab',
    type: 'string',
    label: 'GitLab仓库克隆地址'
  },
  token: {
    name: 'token',
    type: 'string',
    label: '私有Token'
  },
  githubAddress: {
    name: 'github',
    type: 'string',
    label: 'GitHub仓库克隆地址'
  }
};
export { mapping };
export default (function (_ref5) {
  var templateId = _ref5.templateId,
      organizationId = _ref5.organizationId,
      randomString = _ref5.randomString;
  return {
    autoCreate: false,
    autoQuery: false,
    autoQueryAfterSubmit: false,
    transport: {
      read: {
        url: TemplateApis.getTemplateDetail(templateId, organizationId),
        method: 'get'
      },
      create: function create(_ref6) {
        var _ref6$data = _slicedToArray(_ref6.data, 1),
            data = _ref6$data[0];

        var postData = _objectSpread({}, data);

        if (data[mapping.createWay.name] === 'template') {
          postData.repoUrl = null;
        } else {
          postData.repoUrl = data[data[mapping.createWay.name]];
          postData[mapping.appTemplate.name] = null;
        }

        return {
          url: TemplateApis.createTemplate(organizationId),
          method: 'post',
          data: postData
        };
      },
      update: function update(_ref7) {
        var _ref7$data = _slicedToArray(_ref7.data, 1),
            data = _ref7$data[0];

        return {
          url: TemplateApis.updateTemplateName(data.id, data.name, organizationId),
          method: 'put'
        };
      }
    },
    fields: Object.keys(mapping).map(function (key) {
      // @ts-ignore
      var item = mapping[key];

      switch (key) {
        case 'createWay':
          item.required = !templateId;
          break;

        case 'templateSource':
          item.dynamicProps = {
            required: function required(_ref8) {
              var record = _ref8.record;
              return !templateId && organizationId && record.get(mapping.createWay.name) === 'template';
            }
          };
          break;
        // 应用模板

        case 'appTemplate':
          item.dynamicProps = {
            required: function required(_ref9) {
              var record = _ref9.record;
              return !templateId && record.get(mapping.createWay.name) === 'template';
            },
            lookupAxiosConfig: function lookupAxiosConfig(_ref10) {
              var record = _ref10.record;
              return !templateId ? {
                // eslint-disable-next-line no-nested-ternary
                url: !organizationId ? TemplateApis.getTemplateList(randomString) : TemplateApis.getOrgTemplateList(record.get('templateSource'), organizationId, randomString),
                method: 'get'
              } : null;
            }
          };
          break;
        //  gitlab地址

        case 'gitlabAddress':
          item.dynamicProps = {
            required: function required(_ref11) {
              var record = _ref11.record;
              return !templateId && record.get(mapping.createWay.name) === 'gitlab';
            }
          };
          break;
        //  私有Token

        case 'token':
          item.dynamicProps = {
            required: function required(_ref12) {
              var record = _ref12.record;
              return !templateId && record.get(mapping.createWay.name) === 'gitlab';
            }
          };
          break;

        case 'githubAddress':
          item.dynamicProps = {
            required: function required(_ref13) {
              var record = _ref13.record;
              return !templateId && record.get(mapping.createWay.name) === 'github';
            }
          };
          break;

        case 'templateName':
          item.validator = function (value, name, record) {
            return checkName({
              value: value,
              name: name,
              record: record,
              templateId: templateId,
              organizationId: organizationId
            });
          };

          break;

        case 'templateCode':
          item.validator = function (value) {
            return codeValidator({
              value: value,
              organizationId: organizationId,
              templateId: templateId
            });
          };

          break;

        default:
          break;
      }

      return item;
    }),
    events: {
      update: function update(_ref14) {
        var name = _ref14.name,
            record = _ref14.record;

        if (name === mapping.templateSource.name && record.get(mapping.appTemplate.name)) {
          record.set(mapping.appTemplate.name, null);
        }
      }
    }
  };
});