"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Encrypt3DS = void 0;
var mslib_1 = require("mslib");
var Config_1 = require("./Config");
var jwt = require('jsonwebtoken');
var ApiResponse_1 = require("./ApiResponse"); // 假设存在API响应工具
var memberapi_config = Config_1.IocConfigProvider.getMemberConfig();
/**
 * 3DS加密服务装饰器（使用JWT实现）
 *
 * 对方法返回结果进行JWT加密处理，将加密结果存入返回参数的ExtParam.token中
 * 同时保留原始明文数据，支持日志记录和环境配置
 *
 * @param description 服务描述，仅为日志输出
 * @param config 配置选项
 * @param config.isLog 是否记录日志，默认true
 * @param config.isEncrypt 是否启用加密，默认true
 * @param config.expiresIn JWT过期时间，默认'1h'
 */
function Encrypt3DS(description, config) {
    // 设置默认配置
    var defaultConfig = __assign({ isLog: true, isEncrypt: true, expiresIn: '1h' }, config);
    return function (target, propertyKey, descriptor) {
        var _a;
        // 记录装饰器初始化信息
        var tapdId = ((_a = Config_1.IocConfigProvider.getBasicConfig()) === null || _a === void 0 ? void 0 : _a.tapdId) || '';
        mslib_1.logger.info(tapdId + "." + target.constructor.name + "/1.0", "JWT\u52A0\u5BC6\u88C5\u9970\u5668 - " + (description || '未提供描述'));
        // 保存原始方法
        var originalMethod = descriptor.value;
        // 重写方法
        descriptor.value = function () {
            var _a;
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return __awaiter(this, void 0, void 0, function () {
                var tapdId, serviceName, result, token, error_1;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            tapdId = ((_a = Config_1.IocConfigProvider.getBasicConfig()) === null || _a === void 0 ? void 0 : _a.tapdId) || '';
                            serviceName = description || target.constructor.name + "." + propertyKey;
                            // 记录请求日志
                            if (defaultConfig.isLog) {
                                mslib_1.logger.info("tapd:" + tapdId + " JWT\u52A0\u5BC6\u670D\u52A1 " + serviceName + " \u8BF7\u6C42\u53C2\u6570:" + JSON.stringify(args));
                            }
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, originalMethod.apply(this, args)];
                        case 2:
                            // 调用原始方法获取结果
                            result = _b.sent();
                            // 如果需要加密且结果有效，则进行JWT加密处理
                            if (defaultConfig.isEncrypt && result && typeof result === 'object') {
                                // 确保有JWT密钥
                                if (!memberapi_config.jwtSecret) {
                                    throw new Error('JWT加密失败：未配置jwtSecret');
                                }
                                token = jwt.sign(result, // 要加密的原始数据
                                memberapi_config.jwtSecret, // 从配置获取密钥
                                { expiresIn: defaultConfig.expiresIn } // 设置过期时间
                                );
                                // 确保ExtParam对象存在
                                if (!result.ExtParam) {
                                    result.ExtParam = {};
                                }
                                // 将JWT token存入ExtParam.token字段
                                result.ExtParam.token = token;
                            }
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _b.sent();
                            // 捕获并处理异常
                            mslib_1.logger.error("tapd:" + tapdId + " JWT\u52A0\u5BC6\u670D\u52A1 " + serviceName + " \u51FA\u73B0\u5F02\u5E38", error_1);
                            // 返回统一的失败响应
                            result = error_1 instanceof Error
                                ? ApiResponse_1.ApiResponse.successResult(1, "\u52A0\u5BC6\u5904\u7406\u5931\u8D25: " + error_1.message, '', "\u767B\u5F55(MemberLogin) ")
                                : ApiResponse_1.ApiResponse.successResult(1, "\u52A0\u5BC6\u5904\u7406\u5931\u8D25: " + String(error_1), '', "\u767B\u5F55(MemberLogin) ");
                            return [3 /*break*/, 4];
                        case 4:
                            // 记录响应日志
                            if (defaultConfig.isLog) {
                                mslib_1.logger.info("tapd:" + tapdId + " JWT\u52A0\u5BC6\u670D\u52A1 " + serviceName + " \u54CD\u5E94\u7ED3\u679C:" + JSON.stringify(result));
                            }
                            return [2 /*return*/, result];
                    }
                });
            });
        };
        return descriptor;
    };
}
exports.Encrypt3DS = Encrypt3DS;
//# sourceMappingURL=MemberLogin.js.map