// import { deepAssign } from 'press-ui/common/utils/object-assign';

import { template } from './string-format';

const defaultLang = {};

let lang: Record<string, any> = defaultLang;

let i18nHandler = function (this: Object, ...args: any[]) {
  try {
    if (typeof (window as any).app?.$t === 'function') {
      return (window as any).app?.$t.apply(this, args);
    }
  } catch (err) {}
  return;
};

export const use = function (l?: Record<string, any>) {
  lang = l || lang;
  console.log('use', lang);
};

export const i18n = function (fn?: any) {
  i18nHandler = fn || i18nHandler;
};

// export const add = function (messages = {}) {
//   deepAssign(lang, messages);
// };

export const getLang = function () {
  return lang;
};


export const t = function (this: any, path = '', ...options: Array<any>): any {
  let value = i18nHandler.apply(this, [path, ...options]);
  if (value !== null && value !== undefined) return value;

  const array = path.split('.');
  let current = lang;

  for (let i = 0, j = array.length; i < j; i++) {
    const property = array[i];
    value = current[property];

    if (i === j - 1) {
      // 如果没有找到value，就从第一层找
      if (!value) {
        return lang[property] || '';
      }
      if (typeof value === 'function') {
        return value(...options);
      }
      return value;
      // return format(value, options);
    }
    if (!value) {
      return lang[array[array.length - 1]] || '';
    }
    current = value;
  }
  return '';
};

/**
 * @docgen
 * @function $t
 */
export function $t(this: any, path = '', ...options: Array<any>) {
  // return (window as any).app?.$t?.(...args) || template(...args as Parameters<typeof template>);
  const result = t.call(this, path, ...options);
  if (result) {
    return result;
  }
  let value = path;
  if (!options?.[1]?.ignoreDot) {
    const list = path.split('.');
    value = list[list.length - 1] || '';
  }


  return template(value, ...options);
}
