"use strict";

var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");

var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");

var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");

var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getLangMsg = exports.getCompLangMsg = exports.default = void 0;

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));

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

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

var _react = _interopRequireDefault(require("react"));

var _zhCN = _interopRequireDefault(require("./zh-CN"));

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context2; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty2(_context2 = Object.prototype.toString.call(o)).call(_context2, 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; }

var LocaleCache = /*#__PURE__*/function () {
  function LocaleCache(localesData, locale) {
    (0, _classCallCheck2.default)(this, LocaleCache);
    this.locale = locale || _zhCN.default.locale;
    this.localesData = localesData;
  }
  /**
   * 设置语言包并切换当前语言
   * @param {LocaleDataType | string} localeData 语言数据集合 | 语言类型
   * @returns 设置后的语言对应的语言包
   */


  (0, _createClass2.default)(LocaleCache, [{
    key: "setLocalesData",
    value: function setLocalesData(locale, localeData) {
      var newLocaleData = localeData || this.localesData[locale];

      if (!newLocaleData) {
        console.error("\u7F3A\u5C11\u8BED\u8A00".concat(locale, "\u5BF9\u5E94\u7684\u8BED\u8A00\u5305\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u65B0\u8BBE\u7F6E"));
        return;
      }

      this.locale = locale;
      this.localesData[locale] = newLocaleData;
      return localeData;
    }
    /**
     * 获取当前语言包数据
     */

  }, {
    key: "getLocalData",
    value: function getLocalData() {
      return this.localesData[this.locale];
    }
    /**
     * 获取当前语言类型
     */

  }, {
    key: "getLocal",
    value: function getLocal() {
      return this.locale;
    }
    /**
     * 获取所有语言包数据
     */

  }, {
    key: "getLocalesData",
    value: function getLocalesData() {
      return this.localesData;
    }
  }]);
  return LocaleCache;
}();

var localeCacher = new LocaleCache((0, _defineProperty2.default)({}, _zhCN.default.locale, _zhCN.default));
var _default = localeCacher;
exports.default = _default;

var getLangMsg = function getLangMsg(componentName, labelName, params) {
  var _context;

  var localData = localeCacher.getLocalData();
  var msg = localData[(0, _concat.default)(_context = "".concat(componentName, ".")).call(_context, labelName)] || localData["global.".concat(labelName)] || '';
  return analysVariables(msg, params);
};
/**
 * 解析模板字符串中的变量
 * @param {*} msg
 * @param {*} variables
 */


exports.getLangMsg = getLangMsg;

function analysVariables(msg, variables) {
  var reg = /{[\w\W]*?}/g;
  var matchArr = msg.match(reg) || [];

  var isObject = function isObject(value) {
    return (0, _typeof2.default)(value) === 'object' || typeof value === 'function';
  };

  var getVarName = function getVarName(str) {
    var len = str.length;
    return (0, _slice.default)(str).call(str, 1, len - 1);
  };

  var stringVar = [];
  var eleVar = [];

  var _iterator = _createForOfIteratorHelper(matchArr),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      var varName = getVarName(item);
      var value = variables[varName];

      if (isObject(value)) {
        eleVar.push({
          k: varName,
          v: value
        });
      } else {
        stringVar.push({
          k: varName,
          v: value
        });
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  msg = formatText(msg, stringVar);
  var msgArr = [];

  if (eleVar.length > 0) {
    msgArr = formatElement(msg, variables);
  }

  return eleVar.length > 0 ? msgArr : msg;
}
/**
 * 替换基本类型的变量
 * @param {*} msg
 * @param {*} stringVar
 */


function formatText(msg, stringVar) {
  stringVar.forEach(function (item) {
    var k = item.k,
        v = item.v;
    var reg = new RegExp('{' + k + '}', 'g');
    msg = msg.replace(reg, v);
  });
  return msg;
}
/**
 * 替换React元素类型的变量
 * @param {*} msg
 * @param {*} eleVar
 * @param {*} variables
 */


function formatElement(msg, variables) {
  var splitByElement = function splitByElement(msg) {
    var array = [];
    var item = {
      t: 0,
      v: ''
    }; // 0-string 1-react

    var len = msg.length;
    msg.split('').forEach(function (c, i) {
      if (c === '{') {
        array.push(item);
        item = {
          t: 1,
          v: ''
        };
      } else if (c === '}') {
        array.push(item);
        item = {
          t: 0,
          v: ''
        };
      } else {
        item.v = item.v + c;
      }

      if (i === len - 1) {
        array.push(item);
      }
    });
    return array;
  };

  var elements = [];
  var eleArr = splitByElement(msg);
  eleArr.forEach(function (item, index) {
    var t = item.t,
        v = item.v;

    if (t === 0 && v !== '') {
      elements.push( /*#__PURE__*/_react.default.createElement("span", {
        key: index
      }, v));
    } else if (t === 1) {
      elements.push( /*#__PURE__*/_react.default.cloneElement(variables[v], {
        key: index
      }));
    }
  });
  return elements;
}

var getCompLangMsg = function getCompLangMsg(compLangMsgParams, customGetLangMsg, localeDate) {
  var componentName = compLangMsgParams.componentName,
      labels = compLangMsgParams.labels,
      labelParams = compLangMsgParams.labelParams;
  labels = labels || [];
  labelParams = labelParams || {};
  localeDate = localeDate || _zhCN.default;

  if (!labels.length) {
    for (var key in localeDate) {
      var componentNameAndLabel = key.split('.');

      if (componentName === componentNameAndLabel[0] && componentNameAndLabel[1]) {
        labels.push(componentNameAndLabel[1]);
      }
    }
  }

  var componentLangMsg = {};
  labels.forEach(function (label) {
    if (customGetLangMsg && typeof customGetLangMsg === 'function') {
      componentLangMsg[label] = customGetLangMsg(componentName, label, labelParams[label] || {});
    } else {
      componentLangMsg[label] = getLangMsg(componentName, label, labelParams[label] || {});
    }
  });
  return componentLangMsg;
};

exports.getCompLangMsg = getCompLangMsg;