import _typeof from "@babel/runtime-corejs3/helpers/typeof";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _classCallCheck from "@babel/runtime-corejs3/helpers/classCallCheck";
import _createClass from "@babel/runtime-corejs3/helpers/createClass";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, 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 o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context2; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context2 = {}.toString.call(r)).call(_context2, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
import React from 'react';
import zhCNData from './zh-CN';
var LocaleCache = /*#__PURE__*/function () {
  function LocaleCache(localesData, locale) {
    _classCallCheck(this, LocaleCache);
    this.locale = locale || zhCNData.locale;
    this.localesData = localesData;
  }
  /**
   * 设置语言包并切换当前语言
   * @param {LocaleDataType | string} localeData 语言数据集合 | 语言类型
   * @returns 设置后的语言对应的语言包
   */
  return _createClass(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;
    }
  }]);
}();
var localeCacher = new LocaleCache(_defineProperty({}, zhCNData.locale, zhCNData));
export default localeCacher;
export var getLangMsg = function getLangMsg(componentName, labelName, params) {
  var _context;
  var localData = localeCacher.getLocalData();
  var msg = localData[_concatInstanceProperty(_context = "".concat(componentName, ".")).call(_context, labelName)] || localData["global.".concat(labelName)] || '';
  return analysVariables(msg, params);
};
/**
 * 解析模板字符串中的变量
 * @param {*} msg
 * @param {*} variables
 */
function analysVariables(msg, variables) {
  var reg = /{[\w\W]*?}/g;
  var matchArr = msg.match(reg) || [];
  var isObject = function isObject(value) {
    return _typeof(value) === 'object' || typeof value === 'function';
  };
  var getVarName = function getVarName(str) {
    var len = str.length;
    return _sliceInstanceProperty(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.createElement("span", {
        key: index
      }, v));
    } else if (t === 1) {
      elements.push(/*#__PURE__*/React.cloneElement(variables[v], {
        key: index
      }));
    }
  });
  return elements;
}
export var getCompLangMsg = function getCompLangMsg(compLangMsgParams, customGetLangMsg, localeDate) {
  var componentName = compLangMsgParams.componentName,
    labels = compLangMsgParams.labels,
    labelParams = compLangMsgParams.labelParams;
  labels = labels || [];
  labelParams = labelParams || {};
  localeDate = localeDate || zhCNData;
  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;
};