"use strict";
/**
 * 国际化模块,属于业务层
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.translateNsData = exports.i18n = exports.GlobalService = void 0;
var typescript_ioc_1 = require("typescript-ioc");
var mslib_1 = require("mslib");
var TyGlobalApi_1 = require("./TyGlobalApi");
var nslib_1 = require("refs/nslib");
var I18n = require('i18n').I18n;
/**
 * 国际化服务类
 */
var GlobalService = /** @class */ (function () {
    function GlobalService() {
    }
    /**
     * 获取语言包
     */
    GlobalService.prototype.getLanguagePacks = function (args) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var languagePack, apiResponse, _i, _b, item, pack;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        languagePack = new Map();
                        return [4 /*yield*/, this.tyGlobalApiClient.get({
                                token: args.token,
                                type: 1
                            })];
                    case 1:
                        apiResponse = _c.sent();
                        for (_i = 0, _b = (_a = apiResponse.data) === null || _a === void 0 ? void 0 : _a.data; _i < _b.length; _i++) {
                            item = _b[_i];
                            pack = languagePack.get(item.language);
                            if (!pack) {
                                pack = [];
                                languagePack.set(item.language, pack);
                            }
                            if (item.value.includes('${{')) {
                                mslib_1.logger.info(item.value);
                            }
                            pack.push({ key: item.key, value: item.value });
                        }
                        return [2 /*return*/, languagePack];
                }
            });
        });
    };
    /**
     * 同步后端语言包到redis
     */
    GlobalService.prototype.syncBackend = function () {
        return __awaiter(this, void 0, void 0, function () {
            var languagePacks, _i, _a, languagePack, value, obj, i, error_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.getLanguagePacks({ token: !nslib_1.Contants.IS_PROD ? TyGlobalApi_1.Token.keytop_nkc_pro_sg : TyGlobalApi_1.Token.nonstandard_back_end })];
                    case 1:
                        languagePacks = _b.sent();
                        _i = 0, _a = languagePacks.entries();
                        _b.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 8];
                        languagePack = _a[_i];
                        return [4 /*yield*/, nslib_1.redisClient.hset('translation_1102011', languagePack[0], JSON.stringify(languagePack[1]))];
                    case 3:
                        _b.sent();
                        mslib_1.logger.info("\u540C\u6B65\u975E\u6807/\u540E\u7AEF\u8BED\u8A00\u5305\u5230redis\u6210\u529F,lang:" + languagePack[0]);
                        console.log("\u540C\u6B65\u975E\u6807/\u540E\u7AEF\u8BED\u8A00\u5305\u5230redis\u6210\u529F,lang:" + languagePack[0]);
                        if (!nslib_1.Contants.IS_LOCAL_DEBUG) return [3 /*break*/, 7];
                        _b.label = 4;
                    case 4:
                        _b.trys.push([4, 6, , 7]);
                        return [4 /*yield*/, nslib_1.redisClient.hget('translation_1102011', languagePack[0])];
                    case 5:
                        value = _b.sent();
                        obj = JSON.parse(value);
                        i = 1;
                        mslib_1.logger.info("\u6821\u9A8Credis\u8BED\u8A00\u5305\u6210\u529F,lang:" + languagePack[0]);
                        return [3 /*break*/, 7];
                    case 6:
                        error_1 = _b.sent();
                        mslib_1.logger.error(error_1);
                        return [3 /*break*/, 7];
                    case 7:
                        _i++;
                        return [3 /*break*/, 2];
                    case 8: return [2 /*return*/];
                }
            });
        });
    };
    __decorate([
        typescript_ioc_1.Inject,
        __metadata("design:type", TyGlobalApi_1.TyGlobalApiClient)
    ], GlobalService.prototype, "tyGlobalApiClient", void 0);
    GlobalService = __decorate([
        typescript_ioc_1.Singleton
    ], GlobalService);
    return GlobalService;
}());
exports.GlobalService = GlobalService;
var config = typescript_ioc_1.Container.getValue('config.basic');
/**
 * 基于插件i18n开发,语种需要简写,例如：en(en-US)、zh(zh-TW)
 *
 * 需启用国际化开关config.basic.global=true
 *
 * i18n.__('Hello %s', 'Keytop')
 *
 * i18n.__('Hello {0}', ['Keytop'])
 *
 * i18n.__('Hello {name}', { name: 'Keytop' })
 *
 * i18n.setLocale('cn') //设置语种,语种需简写
 *
 * https://www.npmjs.com/package/i18n
 */
exports.i18n = null;
if (((_a = config === null || config === void 0 ? void 0 : config.global) === null || _a === void 0 ? void 0 : _a.toString().toUpperCase()) === 'TRUE') {
    exports.i18n = new I18n();
    setTimeout(function () { return __awaiter(void 0, void 0, void 0, function () {
        var error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, nslib_1.retry(function () { return __awaiter(void 0, void 0, void 0, function () {
                            var obj, staticCatalog, locales, _loop_1, key;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, nslib_1.redisClient.hgetall('translation_1102011')];
                                    case 1:
                                        obj = _a.sent();
                                        staticCatalog = {};
                                        locales = [];
                                        _loop_1 = function (key) {
                                            try {
                                                var locale = key.split('_')[0];
                                                var pack_1 = {};
                                                JSON.parse(obj[key]).forEach(function (s) {
                                                    pack_1[s.key] = s.value;
                                                });
                                                locales.push(locale);
                                                staticCatalog[locale] = pack_1;
                                            }
                                            catch (error) {
                                                mslib_1.logger.error("\u4ECEredis\u52A0\u8F7D\u8BED\u8A00\u5305\u5931\u8D25,lang:" + key, error);
                                            }
                                        };
                                        for (key in obj) {
                                            _loop_1(key);
                                        }
                                        mslib_1.logger.info("\u4ECEredis\u52A0\u8F7D\u8BED\u8A00\u5305\u6210\u529F,lang:" + locales.join(','));
                                        exports.i18n.configure({
                                            locales: locales,
                                            staticCatalog: staticCatalog,
                                            mustacheConfig: {
                                                tags: ['{', '}'],
                                                disable: false
                                            },
                                            logDebugFn: function (msg) {
                                                mslib_1.logger.debug(msg);
                                            },
                                            logWarnFn: function (msg) {
                                                // logger.warn(msg);
                                            },
                                            logErrorFn: function (msg) {
                                                mslib_1.logger.error(msg);
                                            },
                                            missingKeyFn: function (locale, value) {
                                                return value;
                                            },
                                        });
                                        return [2 /*return*/];
                                }
                            });
                        }); }, 5, 500)];
                case 1:
                    _a.sent();
                    return [3 /*break*/, 3];
                case 2:
                    error_2 = _a.sent();
                    mslib_1.logger.error("\u4ECEredis\u52A0\u8F7D\u8BED\u8A00\u5305\u5931\u8D25", error_2);
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    }); });
}
function translateObj(data, locale) {
    for (var key in data) {
        if (typeof data[key] === 'object') {
            translateObj(data[key], locale);
        }
        else {
            if (typeof data[key] === 'string' && data[key].startsWith('${{') && data[key].endsWith('}}')) {
                data[key] = exports.i18n.__({ phrase: data[key].substring(3, data[key].length - 2), locale: locale });
            }
        }
    }
}
/**
 * 翻译非标数据,翻译格式为${{xxx}}的字符串
 *
 * 使用的语言包是非标/后端
 */
function translateNsData(data, locale) {
    if (typeof data === 'object') {
        translateObj(data, locale);
        return data;
    }
    else {
        if (typeof data === 'string' && data.startsWith('${{') && data.endsWith('}}')) {
            return exports.i18n.__({ phrase: data.substring(3, data.length - 2), locale: locale });
        }
        else {
            return data;
        }
    }
}
exports.translateNsData = translateNsData;
//# sourceMappingURL=Global.js.map