"use strict";
cc._RF.push(module, '771a32aQBNGVKd3+66gyTKA', 'HttpUtil');
// Script/module/Crypto/HttpUtil.ts

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __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 __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 _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var CryptoJS = require("./crypto-js.min.js"); //引用AES源码js
var BASE_URL = "https://api.sparkus.cn";
//只负责网络接口 次类只负责和后端交互，不负责处理数据 数据处理在GameTool
var HttpUtil = /** @class */ (function (_super) {
    __extends(HttpUtil, _super);
    function HttpUtil() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    HttpUtil_1 = HttpUtil;
    //排行榜
    HttpUtil.rankData = function (type, callback, data) {
        return __awaiter(this, void 0, Promise, function () {
            var time, url;
            return __generator(this, function (_a) {
                time = Math.floor((new Date().getTime()) / 1000);
                url = HttpUtil_1.apiSign("/api/get/rank/data?gameId=" + config.gameId + "&dataType=" + type + "&time=" + time, data);
                this.post(url, data, callback, 0);
                return [2 /*return*/];
            });
        });
    };
    HttpUtil.uploadUserLogData = function (data, callback) {
        return __awaiter(this, void 0, Promise, function () {
            var url;
            return __generator(this, function (_a) {
                url = '/log/collect/data';
                this.post(url, data, callback, 3);
                return [2 /*return*/];
            });
        });
    };
    //暂时用不到
    HttpUtil.getUserRecord = function (data, callback) {
        return __awaiter(this, void 0, Promise, function () {
            var time, url;
            return __generator(this, function (_a) {
                time = Math.floor((new Date().getTime()) / 1000);
                url = HttpUtil_1.apiSign("/api/get/user/data?gameId=" + config.gameId + "&time=" + time, data);
                this.post(url, data, callback, 0);
                return [2 /*return*/];
            });
        });
    };
    HttpUtil.get = function (url, callback, count) {
        return __awaiter(this, void 0, void 0, function () {
            var repeat, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        repeat = count ? count : 0;
                        return [4 /*yield*/, this.fetchData(url, null, 'GET', repeat)];
                    case 1:
                        response = _a.sent();
                        callback && callback(response);
                        return [2 /*return*/];
                }
            });
        });
    };
    HttpUtil.post = function (url, data, callback, count) {
        return __awaiter(this, void 0, void 0, function () {
            var repeat, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        repeat = count ? count : 0;
                        return [4 /*yield*/, this.fetchData(url, data, 'POST', repeat)];
                    case 1:
                        response = _a.sent();
                        callback && callback(response);
                        return [2 /*return*/];
                }
            });
        });
    };
    HttpUtil.fetchData = function (url, data, method, repeat) {
        return __awaiter(this, void 0, void 0, function () {
            var fullUrl, headers, options, response, error_1, timeOut;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        fullUrl = "" + BASE_URL + url;
                        headers = { 'Content-Type': 'application/json' };
                        options = {
                            method: method,
                            headers: headers,
                            body: data ? JSON.stringify(data) : null,
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4 /*yield*/, this.fetchWithTimeout(fullUrl, options)];
                    case 2:
                        response = _a.sent();
                        if (!response.ok) {
                            throw new Error("HTTP_______________error! status: " + response.status);
                        }
                        return [4 /*yield*/, response.json()];
                    case 3: return [2 /*return*/, _a.sent()];
                    case 4:
                        error_1 = _a.sent();
                        console.error('Fetch_______________error:', error_1);
                        if (repeat > 0) {
                            repeat -= 1;
                            timeOut = (3 - repeat) * 5000;
                            setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0: return [4 /*yield*/, this.fetchData(url, data, method, repeat)];
                                        case 1:
                                            response = _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            }); }, timeOut);
                        }
                        else {
                            return [2 /*return*/, null];
                        }
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    HttpUtil.fetchWithTimeout = function (resource, options) {
        if (options === void 0) { options = {}; }
        return __awaiter(this, void 0, void 0, function () {
            var controller, id, response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        controller = new AbortController();
                        id = setTimeout(function () { return controller.abort(); }, 5000);
                        return [4 /*yield*/, fetch(resource, __assign(__assign({}, options), { signal: controller.signal }))];
                    case 1:
                        response = _a.sent();
                        clearTimeout(id);
                        return [2 /*return*/, response];
                }
            });
        });
    };
    /**
   *
   * @param url {string} 接口地址
   * @param params {object} 需要加密的参数对象
   */
    HttpUtil.apiSign = function (url, params) {
        if (params === void 0) { params = {}; }
        var convertUrl = url.trim();
        if (convertUrl.indexOf('?') === -1) {
            convertUrl += '?';
        }
        // 传入参数转换拼接字符串
        var postStr = getQueryString(params);
        var signedStr = genSignStr(convertUrl, postStr);
        var encryptStr = "sign=" + signedStr;
        var encryptSignStr = fxCry.encryptByDES(encryptStr, config.secretKey);
        encryptSignStr = encodeURIComponent(encryptSignStr);
        return urlencode(convertUrl) + "&_p=" + encryptSignStr;
    };
    var HttpUtil_1;
    HttpUtil = HttpUtil_1 = __decorate([
        ccclass
    ], HttpUtil);
    return HttpUtil;
}(cc.Component));
exports.default = HttpUtil;
function responseHandler(response) {
    return response.data;
}
// 响应拦截器
// Rq.interceptors.response.use(responseHandler)
var config = {
    gameId: "100019",
    secretKey: "15ELeamO",
    EK: "hui231%1"
};
var Crypoto = /** @class */ (function () {
    function Crypoto() {
        // 加密的向明值，自己根据项目实际情况定，需要跟后端开发保持一致
        this.keyHex = this.getHetKey();
    }
    Crypoto.prototype.getHetKey = function () {
        return CryptoJS.enc.Utf8.parse(config.EK);
    };
    /** DES加密 */
    Crypoto.prototype.encryptByDES = function (message, secret) {
        if (!message) {
            return message;
        }
        var key = secret ? CryptoJS.enc.Utf8.parse(secret) : this.keyHex;
        var encrypted = CryptoJS.DES.encrypt(message, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    };
    /** DES解密 */
    Crypoto.prototype.decryptByDES = function (message, secret) {
        var key = secret ? CryptoJS.enc.Utf8.parse(secret) : this.keyHex;
        var decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Base64.parse(message)
        }, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    };
    /** hmacSHA256加密 */
    Crypoto.prototype.hmacSha256 = function (message, secret) {
        var keyHex = secret ? CryptoJS.enc.Utf8.parse(secret) : this.keyHex;
        var hash = CryptoJS.HmacSHA256(message, keyHex);
        return hash.toString();
    };
    /** hmacSHA256验证 */
    Crypoto.prototype.verifyHmacSha256 = function (message, signature) {
        var hash = CryptoJS.HmacSHA256(message, this.keyHex);
        return hash.toString() === signature;
    };
    /** CBC加密 */
    Crypoto.prototype.encryptCBC = function (word) {
        if (!word) {
            return word;
        }
        var srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, this.keyHex, {
            iv: this.keyHex,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });
        return encrypted.toString();
    };
    /** CBC解密 */
    Crypoto.prototype.decryptCBC = function (word) {
        if (!word) {
            return word;
        }
        var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
        var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        var decrypt = CryptoJS.AES.decrypt(srcs, this.keyHex, {
            iv: this.keyHex,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });
        var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    };
    return Crypoto;
}());
var fxCry = new Crypoto();
function isEmpty(data) {
    return data === "" || data === null || data === undefined || data.length === 0 || JSON.stringify(data) == "{}";
}
function getQueryString(obj) {
    // 首先对对象的键进行排序并过滤空值
    var sortedKeys = Object.keys(obj).sort();
    var sortedObj = {};
    for (var i = 0; i < sortedKeys.length; i++) {
        if (isEmpty(obj[sortedKeys[i]])) {
            continue;
        }
        sortedObj[sortedKeys[i]] = obj[sortedKeys[i]];
    }
    // 然后将排序后的对象转换为查询字符串
    var params = [];
    for (var key in sortedObj) {
        params.push(encodeURIComponent(key) + "=" + encodeURIComponent(sortedObj[key]));
    }
    return params.join('&');
}
/**
 * 组装签名字符串
 * @param string url: 请求地址
 * @param string postStr: post参数的a=1&b=2
 * @returns
 */
function genSignStr(url, postStr) {
    var lessUrl = url.replace('?', '');
    lessUrl = lessUrl + "&" + postStr;
    return encodeURIComponent(fxCry.hmacSha256(lessUrl));
}
// 对参数进行统一urlencode
function urlencode(url) {
    var _a = url.split("?", 2), baseUrl = _a[0], queryString = _a[1];
    var params = new URLSearchParams(queryString);
    return baseUrl + "?" + params.toString();
}

cc._RF.pop();