"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 };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var common_1 = __importDefault(require("@hypgame/common"));
var child_process_1 = __importDefault(require("child_process"));
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var request_1 = __importDefault(require("request"));
var FileUtil_1 = __importDefault(require("../util/FileUtil"));
var PlatformUpLoadTool = /** @class */ (function () {
    function PlatformUpLoadTool(data) {
        /** 构建配置数据 */
        this.buildCfgData = null;
        /** 构建配置数据 */
        this.platformBuildData = null;
        /** 当前平台构建配置数据 */
        this.platformCfg = null;
        /** 当前平台名字 */
        this.platformName = null;
        /** 游戏总配置 */
        this.appCfgData = null;
        /** 游戏版本配置 */
        this.appVersionCfg = null;
        /** 项目目录 */
        this.PROJECT_DIR = null;
        /** api地址 */
        this.baseUrl = "https://yhapi.hanyougame.com";
        /**刷新历史 */
        this.refreshHistory = {};
        this.platformBuildData = data;
    }
    /** 获取json数据 */
    PlatformUpLoadTool.prototype.getJsonData = function (jsonPath) {
        var jsonStr = fs_1["default"].readFileSync(jsonPath, 'utf8');
        return JSON.parse(jsonStr);
    };
    /** 刷新Url地址 */
    PlatformUpLoadTool.prototype.refreshUrl = function (url, isPath) {
        if (isPath === void 0) { isPath = false; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        var refreshUrl = _this.appCfgData.cdnRootUrl + "/" + url;
                        console.log("刷新地址", refreshUrl);
                        request_1["default"].get(_this.baseUrl + (isPath ? '/cosUitls/refreshPath' : '/cosUitls/refresh'), {
                            method: "GET",
                            json: true,
                            headers: {
                                "content-type": "application/json"
                            },
                            body: {
                                url: refreshUrl
                            }
                        }, function (err, rep, body) {
                            if (err) {
                                console.log(" request 请求get请求出现错误 err:", err);
                                return false;
                            }
                            // body表示返回的数据
                            if (body) {
                                // 请求成功
                                // console.log(body)
                                try {
                                    var jsonData = body;
                                    if (jsonData.data && jsonData.data && jsonData.data.TaskId) {
                                        _this.refreshHistory[url] = jsonData.data.TaskId;
                                    }
                                }
                                catch (error) {
                                    console.log(error);
                                }
                            }
                            resolve(true);
                        });
                    })];
            });
        });
    };
    /** 获取刷新结果 */
    PlatformUpLoadTool.prototype.getRefreshResult = function (taskId) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        request_1["default"].get(_this.baseUrl + "/cosUitls/history", {
                            method: "GET",
                            // formData: { "taskId": taskId },
                            json: true,
                            headers: {
                                "content-type": "application/json"
                            },
                            body: {
                                taskId: taskId
                            }
                        }, function (err, rep, body) {
                            if (err) {
                                console.log(" request 请求get请求出现错误 err:", err);
                                resolve(false);
                                return false;
                            }
                            // body表示返回的数据
                            if (body) {
                                // 请求成功
                                // console.log(body)
                                var jsonData = body;
                                if (jsonData.data && jsonData.data && jsonData.data.PurgeLogs && jsonData.data.PurgeLogs[0] && jsonData.data.PurgeLogs[0].Status == "done") {
                                    resolve(true);
                                }
                                else {
                                    resolve(false);
                                }
                            }
                        });
                    })];
            });
        });
    };
    /** 检查刷新结果 */
    PlatformUpLoadTool.prototype.getRefreshResultList = function (count) {
        if (count === void 0) { count = 1; }
        return __awaiter(this, void 0, void 0, function () {
            var repeatFlag, _a, _b, _i, key, taskId, flag;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        console.log("\n\n=========== 查询刷新结果 第" + count + " 次 ==========");
                        repeatFlag = false;
                        _a = [];
                        for (_b in this.refreshHistory)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        key = _a[_i];
                        taskId = this.refreshHistory[key];
                        return [4 /*yield*/, this.getRefreshResult(taskId)];
                    case 2:
                        flag = _c.sent();
                        console.log("刷新记录:", "【" + (flag ? "已完成" : "未完成") + "】", key);
                        if (!flag) {
                            repeatFlag = true;
                        }
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4:
                        if (!repeatFlag) return [3 /*break*/, 6];
                        return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                                var _this = this;
                                return __generator(this, function (_a) {
                                    setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
                                        var flag;
                                        return __generator(this, function (_a) {
                                            switch (_a.label) {
                                                case 0: return [4 /*yield*/, this.getRefreshResultList(++count)];
                                                case 1:
                                                    flag = _a.sent();
                                                    resolve(flag);
                                                    return [2 /*return*/];
                                            }
                                        });
                                    }); }, 2000);
                                    return [2 /*return*/];
                                });
                            }); })];
                    case 5: return [2 /*return*/, _c.sent()];
                    case 6: return [2 /*return*/, true];
                }
            });
        });
    };
    PlatformUpLoadTool.prototype.init = function (projectDir, channelName, platformName, uploadType) {
        return __awaiter(this, void 0, void 0, function () {
            var curCmdTitle, buildCmd, DebugMode, buildStartTime, dealRes, staticUrl, remoteRes, _a, _b, _i, key, refreshUrl;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        this.PROJECT_DIR = projectDir;
                        this.buildCfgData = this.getJsonData(this.PROJECT_DIR + '\\PlatformBuildCfg.json');
                        this.appCfgData = this.getJsonData(this.PROJECT_DIR + '\\assets\\AppVersionCfg.json');
                        this.platformCfg = this.buildCfgData[platformName];
                        this.appVersionCfg = common_1["default"].curChannelData;
                        this.platformName = platformName;
                        curCmdTitle = "YHCfg快速上传工具_" + this.platformName + (uploadType || "");
                        buildCmd = null;
                        buildCmd = 'taskkill /FI  "WINDOWTITLE eq ' + curCmdTitle + '" /IM cmd.exe /F';
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        buildCmd = "title " + curCmdTitle;
                        child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                        console.log("===================== 快速上传小程序Cfg工具 YH =====================");
                        console.log("上传小程序平台:", this.platformName);
                        console.log("上传小程序版本:", this.appVersionCfg.version);
                        DebugMode = this.appVersionCfg.DebugMode;
                        console.log("是否开启debug模式:", DebugMode);
                        buildStartTime = new Date().getTime();
                        dealRes = function (dealData, remotePath) { return __awaiter(_this, void 0, void 0, function () {
                            var remoteRes, key, localFolder, remoteFolderUrl, stat, is_direc, deleteRes, key, localFolder, is_direc, refreshUrl, _a, _b, _i, key;
                            return __generator(this, function (_c) {
                                switch (_c.label) {
                                    case 0:
                                        remoteRes = dealData.remoteRes;
                                        /** 上传远程文件夹 */
                                        for (key in remoteRes) {
                                            localFolder = path_1["default"].join(projectDir, key);
                                            if (!fs_1["default"].existsSync(localFolder))
                                                continue;
                                            remoteFolderUrl = remotePath;
                                            if (remoteRes[key] && remoteRes[key].length) {
                                                remoteFolderUrl += "/" + remoteRes[key];
                                            }
                                            buildCmd = "coscmd upload  ";
                                            stat = fs_1["default"].lstatSync(localFolder);
                                            is_direc = stat.isDirectory();
                                            if (is_direc) {
                                                buildCmd += " -r ";
                                                if (this.appVersionCfg.deleteNoMatch) { //删除云上存在，本地无的内容
                                                    buildCmd += " --delete ";
                                                }
                                            }
                                            buildCmd += localFolder + " " + remoteFolderUrl;
                                            console.log("buildCmd", buildCmd);
                                            child_process_1["default"].execSync(buildCmd, { stdio: [0, 1, 2] });
                                        }
                                        deleteRes = dealData.deleteRes;
                                        for (key in deleteRes) {
                                            localFolder = path_1["default"].join(projectDir, key);
                                            if (!fs_1["default"].existsSync(localFolder))
                                                continue;
                                            is_direc = stat.isDirectory();
                                            if (is_direc) {
                                                FileUtil_1["default"].removeDirsSync(localFolder);
                                            }
                                            else {
                                                FileUtil_1["default"].removeDirsSync(localFolder);
                                            }
                                        }
                                        refreshUrl = dealData.refreshUrl;
                                        if (!refreshUrl) return [3 /*break*/, 6];
                                        _a = [];
                                        for (_b in refreshUrl)
                                            _a.push(_b);
                                        _i = 0;
                                        _c.label = 1;
                                    case 1:
                                        if (!(_i < _a.length)) return [3 /*break*/, 6];
                                        key = _a[_i];
                                        if (!key.includes(".")) return [3 /*break*/, 3];
                                        //刷新配置文件地址
                                        return [4 /*yield*/, this.refreshUrl(remotePath + "/" + key)];
                                    case 2:
                                        //刷新配置文件地址
                                        _c.sent();
                                        return [3 /*break*/, 5];
                                    case 3: 
                                    //刷新配置文件地址
                                    return [4 /*yield*/, this.refreshUrl(remotePath + "/" + key, true)];
                                    case 4:
                                        //刷新配置文件地址
                                        _c.sent();
                                        _c.label = 5;
                                    case 5:
                                        _i++;
                                        return [3 /*break*/, 1];
                                    case 6: return [2 /*return*/];
                                }
                            });
                        }); };
                        if (!uploadType) return [3 /*break*/, 9];
                        staticUrl = this.platformBuildData.channelBuildCfg.staticUrl;
                        if (!(staticUrl && staticUrl.length > 1)) return [3 /*break*/, 7];
                        return [4 /*yield*/, dealRes(this.platformBuildData.channelBuildCfg.buildRes, staticUrl)
                            //刷新固定网站地址
                        ];
                    case 1:
                        _c.sent();
                        //刷新固定网站地址
                        return [4 /*yield*/, this.refreshUrl(staticUrl)
                            //刷新H5链接
                        ];
                    case 2:
                        //刷新固定网站地址
                        _c.sent();
                        remoteRes = this.platformBuildData.channelBuildCfg.buildRes.remoteRes;
                        _a = [];
                        for (_b in remoteRes)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 3;
                    case 3:
                        if (!(_i < _a.length)) return [3 /*break*/, 6];
                        key = _a[_i];
                        refreshUrl = staticUrl;
                        if (remoteRes[key] && remoteRes[key].length) {
                            refreshUrl += "/" + remoteRes[key];
                        }
                        refreshUrl += "/index.html";
                        //刷新固定网站地址
                        return [4 /*yield*/, this.refreshUrl(refreshUrl)];
                    case 4:
                        //刷新固定网站地址
                        _c.sent();
                        _c.label = 5;
                    case 5:
                        _i++;
                        return [3 /*break*/, 3];
                    case 6: return [3 /*break*/, 9];
                    case 7: return [4 /*yield*/, dealRes(this.platformBuildData.channelBuildCfg.buildRes, this.platformBuildData.resRemoteHost)];
                    case 8:
                        _c.sent();
                        _c.label = 9;
                    case 9: return [4 /*yield*/, dealRes(this.platformBuildData.channelBuildCfg.gameCfg, this.platformBuildData.otherResRemoteHost)];
                    case 10:
                        _c.sent();
                        console.log("===================== " + platformName + " 上传任务完成 YH =====================");
                        console.log("\u4EFB\u52A1\u5B8C\u6210\u65F6\u95F4:" + ((new Date().getTime() - buildStartTime) / 1000).toFixed(1) + "s \n");
                        console.log("===============================================================================");
                        return [2 /*return*/];
                }
            });
        });
    };
    return PlatformUpLoadTool;
}());
exports["default"] = PlatformUpLoadTool;
