"use strict";
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 });
var mslib_1 = require("mslib");
var crypto = require("crypto");
var uuid_1 = require("uuid");
/**
 * 统一平台对接接口
 * @date 2021-01-07 08:08:08
 * @author 周勇强
 */
var TyptApi = /** @class */ (function () {
    /**
     * 初始化统一平台参数
     */
    function TyptApi(appId, appSecret, url, version) {
        this.appId = appId;
        this.appSecret = appSecret;
        this.url = url;
        this.version = version;
    }
    /**
     * 统一平台接口调用入口
     * @param uri           请求地址uri（除ip和端口）例：/api/wec/GetCarCardList
     * @param serviceCode   例：getCarCardList
     * @param params        请求参数(appId、key、serviceCode、ts、reqId不用传)
     */
    TyptApi.prototype.call = function (uri, serviceCode, params) {
        return __awaiter(this, void 0, void 0, function () {
            var url, headers, callObj, result, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        url = "" + this.url + uri;
                        // params.serviceCode = serviceCode;
                        // params = params || {};
                        params.reqId = uuid_1.v4();
                        params.ts = new Date().getTime();
                        params.key = this.sign(params, this.appSecret);
                        //appId不能参与加密
                        params.appId = Number(this.appId);
                        headers = {};
                        headers['kt-lotcodes'] = params && params['parkId'] ? params['parkId'] : "";
                        headers['version'] = this.version;
                        callObj = {
                            url: url,
                            key: params.key,
                            ts: params.ts,
                            data: params,
                            headers: headers
                        };
                        mslib_1.logger.info("\n\u8C03\u7528\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\uFF0C\u4F20\u5165\u53C2\u6570======>\n" + JSON.stringify(callObj) + "\n=======\n");
                        return [4 /*yield*/, this.postJson(url, params, headers)];
                    case 1:
                        result = _a.sent();
                        mslib_1.logger.info("\n\u8C03\u7528\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\uFF0C\u8FD4\u56DE\u7ED3\u679C======>"
                            + ("\nstatus=" + result.status + "\nstatusText=" + result.statusText)
                            + ("\ndata=" + JSON.stringify(result.data) + "\n=======\n"));
                        if (result.status != 200) {
                            return [2 /*return*/, TyptApiOpResult.opError("\u8C03\u7528\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\uFF0C\u8C03\u7528\u5931\u8D25: " + result.statusText)];
                        }
                        if (!result.data) {
                            return [2 /*return*/, TyptApiOpResult.opError("\u8C03\u7528\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\u8FD4\u56DE\u6570\u636E\u4E3A\u7A7A!")];
                        }
                        if (result.data.resCode && result.data.resCode != "0" && result.data.resCode != 0 && result.data.resCode != "200") {
                            return [2 /*return*/, TyptApiOpResult.opError(result.data.resCode + "/" + result.data.resMsg)];
                        }
                        if (result.data.respCode && result.data.respCode != "0" && result.data.respCode != 0 && result.data.respCode != "200") {
                            return [2 /*return*/, TyptApiOpResult.opError(result.data.respCode + "/" + result.data.respMsg)];
                        }
                        return [2 /*return*/, TyptApiOpResult.opSuccess("调用统一平台接口成功!", result.data.data instanceof Object ? result.data.data : JSON.parse(result.data.data))];
                    case 2:
                        e_1 = _a.sent();
                        return [2 /*return*/, TyptApiOpResult.opError(e_1.toString())];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 对数据进行签名
     */
    TyptApi.prototype.sign = function (data, secret) {
        mslib_1.logger.info("\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\u7B7E\u540D\uFF0C\u4F20\u5165\u7684\u6570\u636E\u5B57\u6BB5\n=======sign-data=======\n" + JSON.stringify(data) + "\n====================\n");
        var result = "";
        var keys = [];
        for (var k in data) {
            if (k == 'sign') {
                continue;
            }
            keys.push(k);
        }
        keys.sort();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var valueObj = data[key];
            if (valueObj instanceof Array || valueObj instanceof Object) {
                //忽略复杂对象
                mslib_1.logger.info("统一平台接口签名，当前key为复杂对象，不能够参与加密。。。key:%s,valueObj:%s", key, valueObj);
            }
            else {
                var valueStr = valueObj;
                result = "" + result + key + "=" + valueStr + "&";
            }
        }
        result = "" + result + secret;
        mslib_1.logger.info("\u7EDF\u4E00\u5E73\u53F0\u63A5\u53E3\u7B7E\u540D\u6E90\u5B57\u6BB5\uFF1A\n=======sign-src=======\n" + result + "\n=====================\n");
        return this.md5(result);
    };
    /**
     * md5加密并转大写
     */
    TyptApi.prototype.md5 = function (txt) {
        var hash = crypto.createHash('md5');
        hash.update(txt);
        return hash.digest('hex').toUpperCase();
    };
    /**
     * http请求统一平台，设置headers
     */
    TyptApi.prototype.postJson = function (url, bodyObj, headers) {
        if (bodyObj === void 0) { bodyObj = {}; }
        if (headers === void 0) { headers = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var config, requestUrl, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        config = {}, requestUrl = url;
                        config['headers'] = headers;
                        config['headers']['content-type'] = 'application/json;charset=utf-8';
                        mslib_1.logger.info("最终请求：requestUrl:【%s】,bodyObj:【%s】,config:【%s】", requestUrl, JSON.stringify(bodyObj), JSON.stringify(config));
                        return [4 /*yield*/, this.axios.post(requestUrl, bodyObj, config)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.info("最终返回：" + JSON.stringify(response.data));
                        return [2 /*return*/, response];
                }
            });
        });
    };
    return TyptApi;
}());
exports.TyptApi = TyptApi;
var TyptApiOpResult = /** @class */ (function () {
    function TyptApiOpResult() {
    }
    TyptApiOpResult.prototype.success = function () {
        return this.code == 2000;
    };
    TyptApiOpResult.opSuccess = function (message, data) {
        var result = new TyptApiOpResult();
        result.code = 2000;
        result.message = message;
        result.data = data;
        return result;
    };
    TyptApiOpResult.opError = function (message) {
        var result = new TyptApiOpResult();
        result.code = 5000;
        result.message = message;
        return result;
    };
    return TyptApiOpResult;
}());
exports.TyptApiOpResult = TyptApiOpResult;
//# sourceMappingURL=TyptApi.js.map