import Vue from 'vue'
import VueI18n from './vue-i18n/vue-i18n.common'
// import {getLocale} from '@/util/db'
Vue.use(VueI18n)

const i18n = new VueI18n({
    locale: uni.getStorageSync('locale')|| 'zh-Hans',
    formatFallbackMessages: false,
    fallbackLocale: 'zh-Hans',
    messages: {
        'en': require('./languages/en_US.json'),
        'zh-Hans': require('./languages/zh_CN.json')
    }
})

/*
用法
$l('title')         => titleZh
$l(item, 'title')   => item.titleZh
$l(null, 'title')   => titleZh
$l()                => Zh
*/
Vue.prototype.$l = i18n.l = (object, field = '') => {
    let prefix = i18n.locale.split(/[-_]/g)[0] // 改成正则让他同时支持-和_，否则$l取值可能会异常
    let append = prefix.charAt(0).toUpperCase() + prefix.toLowerCase().substr(1)
    if(typeof object == 'string'){
        return object + append
    }
    // 如果object是null或者字符串则返回字段名
    if(!object) return field + append

    return object[field + append] || object[field]
}
/* Vue.filter('$t', Vue.$i18n)
 */
// 重新console.warn来捕获未翻译的内容
/* console.wareOrig = console.warn
console.warn = (...data) => {
    console.log('warn', typeof data)
    console.wareOrig(data)
} */
export default i18n
