"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.LovCodeStore = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _tslib = require("tslib");

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _mobx = require("mobx");

var _utils = require("../utils");

var _DataSet = _interopRequireDefault(require("../data-set/DataSet"));

var _axios = _interopRequireDefault(require("../axios"));

var _enum = require("../data-set/enum");

var _enum2 = require("../enum");

var _utils2 = require("./utils");

var _utils3 = require("../data-set/utils");

var _promiseMerger = _interopRequireDefault(require("../promise-merger"));

var _configure = require("../configure");

function getFieldType(conditionFieldType) {
  switch (conditionFieldType) {
    case _enum2.LovFieldType.INT:
      return _enum.FieldType.number;

    case _enum2.LovFieldType.TEXT:
      return _enum.FieldType.string;

    case _enum2.LovFieldType.DATE:
      return _enum.FieldType.date;

    case _enum2.LovFieldType.DATETIME:
      return _enum.FieldType.dateTime;

    case _enum2.LovFieldType.POPUP:
      return _enum.FieldType.object;

    default:
      return conditionFieldType || _enum.FieldType.string;
  }
}

function generateConditionField(fields, _ref) {
  var conditionField = _ref.conditionField,
      conditionFieldType = _ref.conditionFieldType,
      conditionFieldName = _ref.conditionFieldName,
      gridFieldName = _ref.gridFieldName,
      display = _ref.display,
      conditionFieldLovCode = _ref.conditionFieldLovCode,
      conditionFieldSelectCode = _ref.conditionFieldSelectCode,
      conditionFieldSelectUrl = _ref.conditionFieldSelectUrl,
      conditionFieldSelectTf = _ref.conditionFieldSelectTf,
      conditionFieldSelectVf = _ref.conditionFieldSelectVf,
      conditionFieldRequired = _ref.conditionFieldRequired,
      fieldProps = _ref.fieldProps;

  if (conditionField === 'Y') {
    var name = conditionFieldName || gridFieldName;
    var field = (0, _objectSpread2["default"])({
      name: name,
      type: getFieldType(conditionFieldType),
      label: display,
      lovCode: conditionFieldLovCode || undefined,
      lookupCode: conditionFieldSelectCode || undefined,
      lookupUrl: conditionFieldSelectUrl || undefined,
      textField: conditionFieldSelectTf || undefined,
      valueField: conditionFieldSelectVf || undefined,
      required: conditionFieldRequired || undefined
    }, fieldProps);
    fields.push(field);

    if (conditionFieldType === _enum2.LovFieldType.POPUP) {
      var aliasName = "__lov__".concat(name);
      field.name = aliasName;
      fields.push({
        name: name,
        bind: "".concat(aliasName, ".").concat(conditionFieldSelectVf)
      });
    }
  }
}

function generateGridField(fields, _ref2) {
  var gridField = _ref2.gridField,
      gridFieldName = _ref2.gridFieldName,
      display = _ref2.display,
      fieldProps = _ref2.fieldProps;

  if (gridField === 'Y') {
    fields.push((0, _objectSpread2["default"])({
      name: gridFieldName,
      label: display
    }, fieldProps));
  }
}

var LovCodeStore = /*#__PURE__*/function () {
  function LovCodeStore() {
    var _this = this;

    (0, _classCallCheck2["default"])(this, LovCodeStore);
    this.pendings = {};

    this.batchCallback = function (codes, args) {
      var _args = (0, _slicedToArray2["default"])(args, 2),
          lovDefineBatchAxiosConfig = _args[0],
          field = _args[1];

      if (lovDefineBatchAxiosConfig) {
        return _this.getAxios(field)(lovDefineBatchAxiosConfig(codes));
      }

      return Promise.resolve({});
    };

    this.merger = new _promiseMerger["default"](this.batchCallback, {
      maxAge: 60000,
      max: 100
    });

    this.fetchDefineInBatch = function (code, lovDefineBatchAxiosConfig, field) {
      var getBatchKey = function getBatchKey(defaultKey) {
        var _lovDefineBatchAxiosC = lovDefineBatchAxiosConfig([code]),
            url = _lovDefineBatchAxiosC.url;

        return url ? url.split('?')[0] : defaultKey;
      };

      return _this.merger.add(code, getBatchKey, [lovDefineBatchAxiosConfig, field]);
    };

    this.init();
  }

  (0, _createClass2["default"])(LovCodeStore, [{
    key: "getAxios",
    value: function getAxios(field) {
      return (0, _utils2.getGlobalConfig)('axios', field) || _axios["default"];
    }
  }, {
    key: "init",
    value: function init() {
      this.lovCodes = _mobx.observable.map();
    }
  }, {
    key: "getDefineAxiosConfig",
    value: function getDefineAxiosConfig(code, field, record) {
      var lovDefineAxiosConfig = field && field.get('lovDefineAxiosConfig', record) || (0, _utils2.getGlobalConfig)('lovDefineAxiosConfig', field);
      var config = (0, _utils2.processAxiosConfig)(lovDefineAxiosConfig, code, field);
      return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, config), {}, {
        url: config.url || this.getConfigUrl(code, field, record),
        method: config.method || 'post'
      });
    }
  }, {
    key: "getConfig",
    value: function getConfig(code) {
      return this.lovCodes.get(code);
    }
  }, {
    key: "fetchConfig",
    value: function () {
      var _fetchConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(code, field, record) {
        var _this2 = this;

        var config, defineBatch, useLovDefineBatch, axiosConfig, pending;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                config = this.getConfig(code); // SSR do not fetch the lookup

                if (!(!config && typeof window !== 'undefined')) {
                  _context.next = 23;
                  break;
                }

                defineBatch = field ? field.get('lovDefineBatchAxiosConfig', record) || field.dataSet.getConfig('lovDefineBatchAxiosConfig') : (0, _configure.getConfig)('lovDefineBatchAxiosConfig');
                useLovDefineBatch = code && (field ? field.dataSet.getConfig('useLovDefineBatch') : (0, _configure.getConfig)('useLovDefineBatch'))(code, field) !== false;

                if (!(defineBatch && useLovDefineBatch)) {
                  _context.next = 11;
                  break;
                }

                _context.next = 7;
                return this.fetchDefineInBatch(code, defineBatch, field);

              case 7:
                config = _context.sent;
                (0, _mobx.runInAction)(function () {
                  if (config) {
                    _this2.lovCodes.set(code, config);
                  }
                });
                _context.next = 23;
                break;

              case 11:
                axiosConfig = this.getDefineAxiosConfig(code, field, record);

                if (!axiosConfig) {
                  _context.next = 23;
                  break;
                }

                _context.prev = 13;
                pending = this.pendings[code] || this.getAxios(field)(axiosConfig);
                this.pendings[code] = pending;
                _context.next = 18;
                return pending;

              case 18:
                config = _context.sent;
                (0, _mobx.runInAction)(function () {
                  if (config) {
                    _this2.lovCodes.set(code, config);
                  }
                });

              case 20:
                _context.prev = 20;
                delete this.pendings[code];
                return _context.finish(20);

              case 23:
                return _context.abrupt("return", config);

              case 24:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[13,, 20, 23]]);
      }));

      function fetchConfig(_x, _x2, _x3) {
        return _fetchConfig.apply(this, arguments);
      }

      return fetchConfig;
    }() // lovCode 作为key 缓存了 ds

  }, {
    key: "getLovDataSet",
    value: function getLovDataSet(code, field, dataSetProps, record) {
      var config = this.getConfig(code);

      if (config) {
        var lovPageSize = config.lovPageSize,
            lovItems = config.lovItems,
            parentIdField = config.parentIdField,
            idField = config.idField,
            treeFlag = config.treeFlag,
            configDataSetProps = config.dataSetProps;
        var valueField = field ? field.get('valueField', record) : config.valueField;
        var dsProps = {
          transport: {
            read: this.getQueryAxiosConfig(code, field, config, record)
          },
          primaryKey: valueField,
          cacheSelection: true
        };

        if (!(0, _isNil["default"])(lovPageSize) && !isNaN(Number(lovPageSize))) {
          dsProps.pageSize = Number(lovPageSize);
        } else {
          dsProps.paging = false;
        }

        if (treeFlag === 'Y' && parentIdField && idField) {
          dsProps.parentField = parentIdField;
          dsProps.idField = idField;
        }

        if (lovItems && lovItems.length) {
          var _lovItems$sort$reduce = lovItems.sort(function (_ref3, _ref4) {
            var conditionFieldSequence = _ref3.conditionFieldSequence;
            var conditionFieldSequence2 = _ref4.conditionFieldSequence;
            return conditionFieldSequence - conditionFieldSequence2;
          }).reduce(function (obj, configItem) {
            generateConditionField(obj.querys, configItem);
            generateGridField(obj.fields, configItem);
            return obj;
          }, {
            querys: [],
            fields: []
          }),
              querys = _lovItems$sort$reduce.querys,
              fields = _lovItems$sort$reduce.fields;

          if (querys.length) {
            dsProps.queryFields = querys;
          }

          if (fields.length) {
            dsProps.fields = fields;
          }
        }

        return new _DataSet["default"]((0, _utils3.mergeDataSetProps)((0, _utils3.mergeDataSetProps)(dsProps, configDataSetProps), dataSetProps), field && field.dataSet.context);
      }

      (0, _utils.warning)(false, "LOV: code<".concat(code, "> is not exists"));
      return undefined;
    }
  }, {
    key: "getConfigUrl",
    value: function getConfigUrl(code, field, record) {
      var lovDefineUrl = field && field.get('lovDefineUrl', record) || (0, _utils2.getGlobalConfig)('lovDefineUrl', field);

      if (typeof lovDefineUrl === 'function') {
        return lovDefineUrl(code);
      }

      return lovDefineUrl;
    }
  }, {
    key: "getQueryAxiosConfig",
    value: function getQueryAxiosConfig(code, field, config, record) {
      var _this3 = this;

      return function (props) {
        var lovQueryAxiosConfig = field && field.get('lovQueryAxiosConfig', record) || (0, _utils2.getGlobalConfig)('lovQueryAxiosConfig', field);

        var lovQueryUrl = _this3.getQueryUrl(code, field, props, record);

        var axiosConfig = (0, _utils2.processAxiosConfig)(lovQueryAxiosConfig, code, config, props, lovQueryUrl);
        return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, axiosConfig), {}, {
          url: axiosConfig.url || lovQueryUrl,
          method: axiosConfig.method || 'post'
        });
      };
    }
  }, {
    key: "getQueryUrl",
    value: function getQueryUrl(code, field, props, record) {
      var config = this.getConfig(code);

      if (config) {
        var customUrl = config.customUrl;

        if (customUrl) {
          return customUrl;
        }
      }

      var lovQueryUrl = field && field.get('lovQueryUrl', record) || (0, _utils2.getGlobalConfig)('lovQueryUrl', field);

      if (typeof lovQueryUrl === 'function') {
        return lovQueryUrl(code, config, props);
      }

      return lovQueryUrl;
    }
  }, {
    key: "clearCache",
    value: function clearCache(codes) {
      var _this4 = this;

      if (codes) {
        codes.forEach(function (code) {
          _this4.lovCodes["delete"](code);

          _this4.merger.cache.del(code);
        });
      } else {
        this.lovCodes.clear();
        this.merger.cache.reset();
      }
    }
  }]);
  return LovCodeStore;
}();

exports.LovCodeStore = LovCodeStore;
(0, _tslib.__decorate)([_mobx.observable], LovCodeStore.prototype, "lovCodes", void 0);
(0, _tslib.__decorate)([_mobx.action], LovCodeStore.prototype, "init", null);
(0, _tslib.__decorate)([_mobx.action], LovCodeStore.prototype, "clearCache", null);

var _default = new LovCodeStore();

exports["default"] = _default;
//# sourceMappingURL=LovCodeStore.js.map
