"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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisService = void 0;
var ioredis_1 = require("ioredis");
var uid_1 = require("uid");
var fs = require("fs");
var path = require("path");
var sqlite3 = require("sqlite3");
var moment = require("moment");
var ssh_service_1 = require("./ssh.service");
var stringSplit = require('string-split-by');
// console.log('stringSplit', stringSplit('  set asd "a b  c"  ', /\s/))
var clients = {};
var subscribe_clients = {};
function sleep(ms) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            resolve();
        }, ms);
    });
}
function splitByFirstSpace(command) {
    return stringSplit(command, /\s/)
        .filter(function (item) { return item; })
        .map(function (item) { return item.replace(/^"/, '').replace(/"$/, ''); });
    // const _command = command.trim()
    // const m = _command.match(/\s+/)
    // if (m) {
    //     return [
    //         _command.substring(0, m.index),
    //         _command.substring(m.index + m[0].length),
    //     ]
    // }
    // else {
    //     return [_command]
    // }
    // return command.split(/\s/).filter(item => item)
}
// console.log('splitByFirstSpace', splitByFirstSpace(' get  a b  ccd '))
// console.log('splitByFirstSpace', splitByFirstSpace('  set asd "a b  c"  '))
var USER_HOME = process.env.HOME || process.env.USERPROFILE;
var yunserFolder = path.resolve(USER_HOME, '.yunser'); // TODO package，npm install cmd-core
if (!fs.existsSync(yunserFolder)) {
    fs.mkdirSync(yunserFolder);
}
var appFolder = path.resolve(yunserFolder, 'dms-cli'); // TODO package，npm install cmd-core
if (!fs.existsSync(appFolder)) {
    fs.mkdirSync(appFolder);
}
// let sqlDbFilePath = path.resolve(appFolder, 'sqls.json')
// if (!fs.existsSync(sqlDbFilePath)) {
//     // fs.mkdirSync(yunserFolder)
//     fs.writeFileSync(sqlDbFilePath, '', 'utf8')
// }
// let sqlContentText = fs.readFileSync(sqlDbFilePath, 'utf-8')
// if (sqlContentText) {
//     g_sqls = JSON.parse(sqlContentText)
// }
var historyDbFilePath = path.resolve(appFolder, 'redis-v0.5.db');
if (!fs.existsSync(historyDbFilePath)) {
    // fs.mkdirSync(yunserFolder)
    // fs.writeFileSync(historyDbFilePath, '', 'utf8')
}
var shouldInit = false;
if (!fs.existsSync(historyDbFilePath)) {
    shouldInit = true;
}
var hdb = new sqlite3.Database(historyDbFilePath);
if (shouldInit) {
    hdb.run("CREATE TABLE redis_key (id TEXT, key TEXT, create_time DATETIME)");
    hdb.run("CREATE TABLE redis_history (id TEXT, db INTEGER, command TEXT, create_time DATETIME)");
}
var redisConnectionFilePath = path.resolve(appFolder, 'redis.connection.json');
if (!fs.existsSync(redisConnectionFilePath)) {
    fs.writeFileSync(redisConnectionFilePath, '[]', 'utf8');
}
function dbQueryList(sql) {
    return new Promise(function (resolve, reject) {
        var list = [];
        hdb.all(sql, function (err, rows) {
            // console.log('row', err, rows)
            if (err) {
                return reject(err);
            }
            // console.log(row.id + ": " + row.info);
            // list.push(row)
            resolve(rows);
        });
        // resolve(list)
    });
}
function dbInsertCommands(commands) {
    return __awaiter(this, void 0, void 0, function () {
        var _i, commands_1, command, historyId, sql;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _i = 0, commands_1 = commands;
                    _a.label = 1;
                case 1:
                    if (!(_i < commands_1.length)) return [3 /*break*/, 4];
                    command = commands_1[_i];
                    historyId = (0, uid_1.uid)(32);
                    // slepp，防止查询时排序不对
                    return [4 /*yield*/, sleep(1)];
                case 2:
                    // slepp，防止查询时排序不对
                    _a.sent();
                    sql = "INSERT INTO redis_history (id, command, create_time) VALUES('".concat(historyId, "',  '").concat(command, "', '").concat(moment().format('YYYY-MM-DD HH:mm:ss.SSS'), "')");
                    // console.log('sql', sql)
                    hdb.run(sql, function (result, err) {
                        console.log('insert result', result, err);
                    });
                    _a.label = 3;
                case 3:
                    _i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function insertCommandsPro(_a) {
    var commands = _a.commands, db = _a.db;
    return __awaiter(this, void 0, void 0, function () {
        var _i, commands_2, command, historyId, sql;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _i = 0, commands_2 = commands;
                    _b.label = 1;
                case 1:
                    if (!(_i < commands_2.length)) return [3 /*break*/, 4];
                    command = commands_2[_i];
                    historyId = (0, uid_1.uid)(32);
                    // slepp，防止查询时排序不对
                    return [4 /*yield*/, sleep(1)];
                case 2:
                    // slepp，防止查询时排序不对
                    _b.sent();
                    sql = "INSERT INTO redis_history (id, db, command, create_time) VALUES('".concat(historyId, "', ").concat(db, ", '").concat(command, "', '").concat(moment().format('YYYY-MM-DD HH:mm:ss.SSS'), "')");
                    // console.log('sql', sql)
                    hdb.run(sql, function (result, err) {
                        console.log('insert result', result, err);
                    });
                    _b.label = 3;
                case 3:
                    _i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function historyClear() {
    return __awaiter(this, void 0, void 0, function () {
        var dbId, sql;
        return __generator(this, function (_a) {
            dbId = (0, uid_1.uid)(32);
            sql = "DELETE FROM redis_history";
            // console.log('sql', sql)
            hdb.run(sql, function (result, err) {
                // console.log('historyClear result', result, err)
            });
            return [2 /*return*/];
        });
    });
}
function dbInsertKey(key) {
    return __awaiter(this, void 0, void 0, function () {
        var dbId, sql;
        return __generator(this, function (_a) {
            dbId = (0, uid_1.uid)(32);
            sql = "INSERT INTO redis_key VALUES('".concat(dbId, "', '").concat(key, "', '").concat(moment().format('YYYY-MM-DD HH:mm:ss'), "')");
            // console.log('sql', sql)
            hdb.run(sql, function (result, err) {
                // console.log('insert result', result, err)
            });
            return [2 /*return*/];
        });
    });
}
function dbRemoveKey(id) {
    return __awaiter(this, void 0, void 0, function () {
        var dbId, sql;
        return __generator(this, function (_a) {
            dbId = (0, uid_1.uid)(32);
            sql = "DELETE FROM redis_key WHERE id = '".concat(id, "'");
            // console.log('sql', sql)
            hdb.run(sql, function (result, err) {
                // console.log('insert result', result, err)
            });
            return [2 /*return*/];
        });
    });
}
// let g_redis: Redis
// redis.set("mykey", "value"); // Returns a promise which resolves to "OK" when the command succeeds.
// ioredis supports the node.js callback style
// redis.get("mykey", (err, result) => {
//   if (err) {
//     console.error(err);
//   } else {
//     console.log(result); // Prints "value"
//   }
// });
function getRedis(data) {
    return __awaiter(this, void 0, void 0, function () {
        var connectionId;
        return __generator(this, function (_a) {
            connectionId = data.connectionId;
            if (!connectionId) {
                throw new Error('No connection');
            }
            return [2 /*return*/, clients[connectionId].redis];
        });
    });
}
function getRedisKeys(g_redis, keyword, _a) {
    var page = _a.page, pageSize = _a.pageSize, _b = _a.cursor, cursor = _b === void 0 ? 0 : _b;
    return new Promise(function (resolve, reject) {
        var keys = [];
        // https://github.com/luin/ioredis/issues/1160
        // https://github.com/luin/ioredis/issues/1360
        var useStream = false;
        if (useStream) {
            var opts = {
                // only returns keys following the pattern of `user:*`
                // match: "user:*",
                // only return objects that match a given type,
                // (requires Redis >= 6.0)
                // type: "zset",
                // returns approximately 100 elements per call
                count: pageSize,
            };
            if (keyword) {
                opts.match = keyword;
            }
            var stream = g_redis.scanStream(opts);
            stream.on("data", function (resultKeys) {
                // `resultKeys` is an array of strings representing key names.
                // Note that resultKeys may contain 0 keys, and that it will sometimes
                // contain duplicates due to SCAN's implementation in Redis.
                for (var i = 0; i < resultKeys.length; i++) {
                    // console.log(resultKeys[i]);
                }
                keys.push.apply(keys, resultKeys);
            });
            stream.on("end", function () {
                resolve(keys);
            });
        }
        else {
            // redis.scan(cursor, 'MATCH', pattern, 'COUNT', fetchCount, (err, res) => {
            g_redis.scan(cursor, 'MATCH', keyword || '*', 'COUNT', pageSize, function (err, res) {
                if (err) {
                    reject(err);
                    return;
                }
                // '2', [ 'gen:1595', 'gen:0541']
                var cursor = parseInt(res[0]);
                resolve({
                    cursor: cursor,
                    list: res[1],
                });
            });
        }
    });
}
function myCall(g_redis, cmd, params) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve) {
                    g_redis.call(cmd, params, function (err, result) {
                        // console.log('ab', err, result)
                        if (err) {
                            resolve({
                                success: false,
                                message: err.message || 'Unknown',
                            });
                        }
                        resolve({
                            success: true,
                            res: result,
                        });
                    });
                    // return {}
                })];
        });
    });
}
var RedisService = /** @class */ (function () {
    function RedisService() {
    }
    RedisService.prototype.index = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, 'redis home'];
            });
        });
    };
    RedisService.prototype.execCommands = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, commands, g_redis, results, _i, commands_3, command, listParams, cmd, params, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = data.key, commands = data.commands;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        results = [];
                        _i = 0, commands_3 = commands;
                        _a.label = 2;
                    case 2:
                        if (!(_i < commands_3.length)) return [3 /*break*/, 5];
                        command = commands_3[_i];
                        listParams = splitByFirstSpace(command);
                        cmd = listParams[0], params = listParams.slice(1);
                        // console.log('cmd, params', cmd, params)
                        // const getCommand = new Command(cmd, params)
                        dbInsertCommands([
                            command,
                        ]);
                        console.log('cmd, params', cmd, params);
                        return [4 /*yield*/, myCall(g_redis, cmd, params)];
                    case 3:
                        result = _a.sent();
                        results.push({
                            id: (0, uid_1.uid)(8),
                            command: command,
                            // result: await g_redis.sendCommand(getCommand)
                            result: result,
                            // result: await g_redis.call(command)
                        });
                        if (!result.success) {
                            return [3 /*break*/, 5];
                        }
                        _a.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5: return [2 /*return*/, {
                            results: results,
                        }];
                }
            });
        });
    };
    RedisService.prototype.clone = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, newKey, g_redis, buffer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = data.key, newKey = data.newKey;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        dbInsertCommands([
                            "DUMP ".concat(key),
                        ]);
                        return [4 /*yield*/, g_redis.dumpBuffer(key)
                            // const buffer = await g_redis.dump(key)
                            // console.log('buffer', buffer)
                        ];
                    case 2:
                        buffer = _a.sent();
                        // const buffer = await g_redis.dump(key)
                        // console.log('buffer', buffer)
                        dbInsertCommands([
                            "RESTORE ".concat(newKey, " 0 <bin>"),
                        ]);
                        return [4 /*yield*/, g_redis.restore(newKey, 0, buffer)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.lindex = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, index, g_redis;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key, index = data.index;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _b.sent();
                        _a = {};
                        return [4 /*yield*/, g_redis.lindex(key, index)];
                    case 2: return [2 /*return*/, (_a.value = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.zadd = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, score, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, score = data.score, value = data.value;
                        dbInsertCommands([
                            "ZADD ".concat(key, " ").concat(score, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.zadd(key, score, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.xadd = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, fields;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, fields = data.fields;
                        dbInsertCommands([
                            "XADD ".concat(key, " * ").concat(fields.join(' ')),
                        ]);
                        return [4 /*yield*/, g_redis.xadd.apply(g_redis, __spreadArray([key, '*'], fields, false))];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.xdel = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, id = data.id;
                        dbInsertCommands([
                            "XDEL ".concat(key, " ").concat(id),
                        ]);
                        return [4 /*yield*/, g_redis.xdel(key, id)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.zrem = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, value = data.value;
                        dbInsertCommands([
                            "ZREM ".concat(key, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.zrem(key, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.sadd = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, value = data.value;
                        dbInsertCommands([
                            "SADD ".concat(key, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.sadd(key, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.sreplace = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, value, newValue;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, value = data.value, newValue = data.newValue;
                        dbInsertCommands([
                            "SADD ".concat(key, " ").concat(newValue),
                            "SREM ".concat(key, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.sadd(key, newValue)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, g_redis.srem(key, value)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.hreplace = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, field, newField, value, newValue;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, field = data.field, newField = data.newField, value = data.value, newValue = data.newValue;
                        if (!(newField != field)) return [3 /*break*/, 4];
                        dbInsertCommands([
                            "HSETNX ".concat(key, " ").concat(newField, " ").concat(newValue),
                            "HDEL ".concat(key, " ").concat(field),
                        ]);
                        return [4 /*yield*/, g_redis.hsetnx(key, newField, newValue)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, g_redis.hdel(key, field)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 6];
                    case 4:
                        dbInsertCommands([
                            "HSET ".concat(key, " ").concat(field, " ").concat(newValue),
                        ]);
                        return [4 /*yield*/, g_redis.hset(key, field, newValue)];
                    case 5:
                        _a.sent();
                        _a.label = 6;
                    case 6: return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.zreplace = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, score, newScore, value, newValue;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, score = data.score, newScore = data.newScore, value = data.value, newValue = data.newValue;
                        // await g_redis.sadd(key, newValue)
                        // await g_redis.srem(key, value)
                        // await g_redis.hsetnx(key, newField, newValue)
                        // await g_redis.hdel(key, field)
                        dbInsertCommands([
                            "ZREM ".concat(key, " ").concat(value),
                            "ZADD ".concat(key, " ").concat(newScore, " ").concat(newValue),
                        ]);
                        return [4 /*yield*/, g_redis.zrem(key, value)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, g_redis.zadd(key, newScore, newValue)
                            // if (value != newValue) {
                            // }
                            // else {
                            //     await g_redis.zscore(key, value, newValue)
                            // }
                        ];
                    case 3:
                        _a.sent();
                        // if (value != newValue) {
                        // }
                        // else {
                        //     await g_redis.zscore(key, value, newValue)
                        // }
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.srem = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, value, position;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, value = data.value, position = data.position;
                        dbInsertCommands([
                            "SREM ".concat(key, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.srem(key, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.rpush = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, value, _a, position;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _b.sent();
                        key = data.key, value = data.value, _a = data.position, position = _a === void 0 ? 'last' : _a;
                        dbInsertCommands([
                            "".concat(position == 'last' ? 'RPUSH' : 'LPUSH', " ").concat(key, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis[position == 'last' ? 'rpush' : 'lpush'](key, value)];
                    case 2:
                        _b.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.hset = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, field, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, field = data.field, value = data.value;
                        dbInsertCommands([
                            "HSET ".concat(key, " ").concat(field, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.hset(key, field, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.hdel = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, field;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, field = data.field;
                        return [4 /*yield*/, g_redis.hdel(key, field)];
                    case 2:
                        _a.sent();
                        dbInsertCommands([
                            "HDEL ".concat(key, " ").concat(field),
                        ]);
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.lset = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, index, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, index = data.index, value = data.value;
                        dbInsertCommands([
                            "LSET ".concat(key, " ").concat(index, " ").concat(value),
                        ]);
                        return [4 /*yield*/, g_redis.lset(key, index, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.lremove = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // const g_redis = await getRedis(data)
                // const { key, index } = data
                // // await g_redis.lrem(key, 1, )
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.lremIndex = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, key, index, removed_key;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        key = data.key, index = data.index;
                        removed_key = '__delete_' + (0, uid_1.uid)(32);
                        dbInsertCommands([
                            "LSET ".concat(key, " ").concat(index, " ").concat(removed_key),
                            "LREM ".concat(key, " ").concat(-1, " ").concat(removed_key),
                        ]);
                        return [4 /*yield*/, g_redis.lset(key, index, removed_key)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, g_redis.lrem(key, -1, removed_key)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.get = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, g_redis, debug, type, size, value, items, exists, commands, length_1, kvs_1, length_2, _items, idx, length_3, range;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _b.sent();
                        if (!key) {
                            throw new Error('key 不能为空');
                        }
                        debug = null;
                        return [4 /*yield*/, g_redis.type(key)];
                    case 2:
                        type = _b.sent();
                        size = null;
                        value = null;
                        items = null;
                        return [4 /*yield*/, g_redis.exists(key)];
                    case 3:
                        exists = _b.sent();
                        commands = [];
                        if (!(type == 'string')) return [3 /*break*/, 6];
                        return [4 /*yield*/, g_redis.get(key)];
                    case 4:
                        value = _b.sent();
                        return [4 /*yield*/, g_redis.strlen(key)];
                    case 5:
                        size = _b.sent();
                        commands.push("GET ".concat(key));
                        return [3 /*break*/, 20];
                    case 6:
                        if (!(type == 'list')) return [3 /*break*/, 9];
                        return [4 /*yield*/, g_redis.llen(key)];
                    case 7:
                        length_1 = _b.sent();
                        commands.push("LLEN ".concat(key));
                        return [4 /*yield*/, g_redis.lrange(key, 0, length_1 - 1)];
                    case 8:
                        items = _b.sent();
                        commands.push("LRANGE ".concat(key, " 0 ").concat(length_1 - 1));
                        return [3 /*break*/, 20];
                    case 9:
                        if (!(type == 'set')) return [3 /*break*/, 11];
                        return [4 /*yield*/, g_redis.smembers(key)];
                    case 10:
                        items = _b.sent();
                        commands.push("SMEMBERS ".concat(key));
                        return [3 /*break*/, 20];
                    case 11:
                        if (!(type == 'hash')) return [3 /*break*/, 13];
                        return [4 /*yield*/, g_redis.hgetall(key)];
                    case 12:
                        kvs_1 = _b.sent();
                        commands.push("HGETALL ".concat(key));
                        items = Object.keys(kvs_1).map(function (k) {
                            return {
                                key: k,
                                value: kvs_1[k],
                            };
                        });
                        return [3 /*break*/, 20];
                    case 13:
                        if (!(type == 'zset')) return [3 /*break*/, 16];
                        commands.push("ZCARD ".concat(key));
                        return [4 /*yield*/, g_redis.zcard(key)];
                    case 14:
                        length_2 = _b.sent();
                        commands.push("ZRANGE ".concat(key, " 0 ").concat(length_2 - 1, " WITHSCORES"));
                        return [4 /*yield*/, g_redis.zrange(key, 0, length_2 - 1, 'WITHSCORES')
                            // console.log('zrange/_items', _items)
                            // const pipeline = g_redis.pipeline()
                            // _items.forEach(_key => pipeline.zscore(key, _key))
                            // const scores = await pipeline.exec()
                            // debug = scores
                        ];
                    case 15:
                        _items = _b.sent();
                        // console.log('zrange/_items', _items)
                        // const pipeline = g_redis.pipeline()
                        // _items.forEach(_key => pipeline.zscore(key, _key))
                        // const scores = await pipeline.exec()
                        // debug = scores
                        items = [];
                        for (idx = 0; idx < _items.length; idx += 2) {
                            items.push({
                                member: _items[idx],
                                score: parseFloat(_items[idx + 1])
                            });
                        }
                        return [3 /*break*/, 20];
                    case 16:
                        if (!(type == 'stream')) return [3 /*break*/, 19];
                        // const length = await g_redis.llen(key)
                        // commands.push(`LLEN ${key}`)
                        // items = await g_redis.lrange(key, 0, length - 1)
                        // commands.push(`LRANGE ${key} 0 ${length - 1}`)
                        commands.push("XLEN ".concat(key));
                        return [4 /*yield*/, g_redis.xlen(key)];
                    case 17:
                        length_3 = _b.sent();
                        return [4 /*yield*/, g_redis.xrange(key, '-', '+')];
                    case 18:
                        range = _b.sent();
                        console.log('range', range);
                        // [
                        //     [ '1676710397017-0', [ '', '' ] ],
                        //     [ '1676710630887-0', [ 'f1', 'v1', 'f2', 'v2' ] ],
                        //     [ '1676710701227-0', [ 'f3', 'v3' ] ],
                        //     [ '1676711299032-0', [ 'f4', 'v4', 'f5', 'v5' ] ]
                        //   ]
                        items = range.map(function (item) {
                            return {
                                id: item[0],
                                fields: item[1],
                            };
                        });
                        return [3 /*break*/, 20];
                    case 19: throw new Error('unknown type');
                    case 20:
                        insertCommandsPro({
                            commands: commands,
                            db: g_redis.__db,
                        });
                        _a = {
                            exists: !!exists,
                            type: type,
                            value: value
                        };
                        return [4 /*yield*/, g_redis.pttl(key)];
                    case 21:
                        _a.ttl = _b.sent(),
                            _a.size = size,
                            _a.items = items;
                        return [4 /*yield*/, g_redis.object('ENCODING', key)];
                    case 22: return [2 /*return*/, (
                        // debug,
                        _a.encoding = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.ping = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, g_redis;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key;
                        return [4 /*yield*/, getRedis(data)
                            // if (!key) {
                            //     throw new Error('key 不能为空')
                            // }
                            // dbInsertCommands([
                            //     `PING`
                            // ])
                        ];
                    case 1:
                        g_redis = _b.sent();
                        _a = {};
                        return [4 /*yield*/, g_redis.ping()];
                    case 2: 
                    // if (!key) {
                    //     throw new Error('key 不能为空')
                    // }
                    // dbInsertCommands([
                    //     `PING`
                    // ])
                    return [2 /*return*/, (_a.res = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.publish = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var channel, message, g_redis;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        channel = data.channel, message = data.message;
                        return [4 /*yield*/, getRedis(data)
                            // if (!key) {
                            //     throw new Error('key 不能为空')
                            // }
                        ];
                    case 1:
                        g_redis = _b.sent();
                        // if (!key) {
                        //     throw new Error('key 不能为空')
                        // }
                        dbInsertCommands([
                            "PUBLISH ".concat(channel, " ").concat(message)
                        ]);
                        _a = {};
                        return [4 /*yield*/, g_redis.publish(channel, message)];
                    case 2: return [2 /*return*/, (_a.info = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.pubsub = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, channel, message, g_redis, all;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        connectionId = data.connectionId, channel = data.channel, message = data.message;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        return [4 /*yield*/, g_redis.pubsub('CHANNELS')];
                    case 2:
                        all = _a.sent();
                        console.log('all', all);
                        // dbInsertCommands([
                        //     `PUBLISH ${channel} ${message}`
                        // ])
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.subscribe = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, _a, channel, params, redis;
            return __generator(this, function (_b) {
                connectionId = data.connectionId, _a = data.channel, channel = _a === void 0 ? '*' : _a;
                params = clients[connectionId].params;
                redis = new ioredis_1.default(params);
                subscribe_clients[connectionId] = redis;
                redis.on("pmessage", function (pattern, channel, message) {
                    console.log("Received msg", {
                        // pattern,
                        channel: channel,
                        message: message,
                    });
                    (0, ssh_service_1.sendRedisMsg)({
                        channel: channel,
                        message: message,
                    });
                    //   console.log(`Received ${message} from ${channel}`);
                });
                redis.psubscribe(channel, function (err, count) {
                    if (err) {
                        // Just like other commands, subscribe() can fail for some reasons,
                        // ex network issues.
                        console.error("Failed to subscribe: %s", err.message);
                    }
                    else {
                        // `count` represents the number of channels this client are currently subscribed to.
                        //   console.log(
                        //     `Subscribed successfully! This client is currently subscribed to ${count} channels.`
                        //   );
                        console.log('Subscribed successfully');
                    }
                });
                //   redis.on("messageBuffer", (channel, message) => {
                //     // Both `channel` and `message` are buffers.
                //     console.log(channel, message);
                //   });
                // dbInsertCommands([
                //     `PUBLISH ${channel} ${message}`
                // ])
                return [2 /*return*/, {
                    // info: await g_redis.publish(channel, message),
                    // ttl: await g_redis.pttl(key),
                    // size: await g_redis.strlen(key),
                    // encoding: await g_redis.object('ENCODING', key),
                    }];
            });
        });
    };
    RedisService.prototype.unSubscribe = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, _a, channel, redis;
            return __generator(this, function (_b) {
                connectionId = data.connectionId, _a = data.channel, channel = _a === void 0 ? '*' : _a;
                redis = subscribe_clients[connectionId];
                redis.punsubscribe(channel);
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.getInfo = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, g_redis;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key;
                        return [4 /*yield*/, getRedis(data)
                            // if (!key) {
                            //     throw new Error('key 不能为空')
                            // }
                        ];
                    case 1:
                        g_redis = _b.sent();
                        // if (!key) {
                        //     throw new Error('key 不能为空')
                        // }
                        dbInsertCommands([
                            "INFO"
                        ]);
                        _a = {};
                        return [4 /*yield*/, g_redis.info()];
                    case 2: return [2 /*return*/, (_a.info = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.getConfig = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, g_redis;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key;
                        return [4 /*yield*/, getRedis(data)
                            // if (!key) {
                            //     throw new Error('key 不能为空')
                            // }
                        ];
                    case 1:
                        g_redis = _b.sent();
                        // if (!key) {
                        //     throw new Error('key 不能为空')
                        // }
                        dbInsertCommands([
                            "INFO"
                        ]);
                        _a = {};
                        return [4 /*yield*/, g_redis.config('GET', 'databases')];
                    case 2:
                        _a.config = _b.sent();
                        return [4 /*yield*/, g_redis.info()];
                    case 3: return [2 /*return*/, (_a.info = _b.sent(),
                            _a)];
                }
            });
        });
    };
    RedisService.prototype.delete = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, _a, keys, g_redis, _i, keys_1, key_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        key = data.key, _a = data.keys, keys = _a === void 0 ? [] : _a;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _b.sent();
                        if (!keys.length) return [3 /*break*/, 3];
                        for (_i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
                            key_1 = keys_1[_i];
                            dbInsertCommands([
                                "DEL ".concat(key_1)
                            ]);
                        }
                        return [4 /*yield*/, g_redis.del(keys)];
                    case 2:
                        _b.sent();
                        return [2 /*return*/, {}];
                    case 3:
                        if (!key) {
                            throw new Error('key 不能为空');
                        }
                        dbInsertCommands([
                            "DEL ".concat(key)
                        ]);
                        return [4 /*yield*/, g_redis.del(key)];
                    case 4:
                        _b.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.expire = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, seconds, g_redis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = data.key, seconds = data.seconds;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        if (!key) {
                            throw new Error('key 不能为空');
                        }
                        if (!(seconds == -1)) return [3 /*break*/, 3];
                        dbInsertCommands([
                            "PERSIST ".concat(key)
                        ]);
                        return [4 /*yield*/, g_redis.persist(key)];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 3:
                        dbInsertCommands([
                            "EXPIRE ".concat(key, " ").concat(seconds)
                        ]);
                        return [4 /*yield*/, g_redis.expire(key, seconds)];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5: return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.set = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, value, g_redis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = data.key, value = data.value;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        if (!key) {
                            throw new Error('key 不能为空');
                        }
                        if (!value) {
                            throw new Error('value 不能为空');
                        }
                        dbInsertCommands([
                            "SET ".concat(key, " ").concat(value)
                        ]);
                        return [4 /*yield*/, g_redis.set(key, value)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.rename = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, newKey, g_redis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = data.key, newKey = data.newKey;
                        return [4 /*yield*/, getRedis(data)];
                    case 1:
                        g_redis = _a.sent();
                        if (!key) {
                            throw new Error('key 不能为空');
                        }
                        if (!newKey) {
                            throw new Error('newKey 不能为空');
                        }
                        dbInsertCommands([
                            "RENAME ".concat(key, " ").concat(newKey)
                        ]);
                        return [4 /*yield*/, g_redis.rename(key, newKey)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.connect = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var connectionId, host, port, 
            // user,
            password, db, _a, test, userName, g_redis, params, err_1, err_2;
            var _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        connectionId = (0, uid_1.uid)(32);
                        host = config.host, port = config.port, password = config.password, db = config.db, _a = config.test, test = _a === void 0 ? false : _a, userName = config.userName;
                        params = {
                            host: host,
                            port: port,
                            lazyConnect: true,
                            connectTimeout: 1000,
                            username: undefined,
                            password: undefined,
                            maxRetriesPerRequest: 1,
                            // This is the default value of `retryStrategy`
                            retryStrategy: function (times) {
                                var delay = Math.min(times * 2000, 2000);
                                console.log('redis/retry/times', times);
                                // console.log('redis/retry/delay', delay)
                                if (times > 3) {
                                    g_redis.quit();
                                    return 9999999999;
                                }
                                return delay;
                            },
                            reconnectOnError: function (err) {
                                console.log('redis/reconnectOnError', err);
                                // MaxRetriesPerRequestError: Reached the max retries per request limit (which is 1). Refer to "maxRetriesPerRequest" option for details.
                                // const targetError = "READONLY";
                                // if (err.message.includes(targetError)) {
                                //   // Only reconnect when the error contains "READONLY"
                                //     return true; // or `return 1;`
                                // }
                                return false;
                            },
                        };
                        if (password) {
                            params.password = password;
                        }
                        if (userName) {
                            params.username = userName;
                        }
                        // console.log('params', params)
                        g_redis = new ioredis_1.default(params);
                        g_redis
                            .on('connect', function () {
                            // emits when a connection is established to the Redis server.
                            // console.log('redis/on/connect', )
                        })
                            .on('ready', function () {
                            // console.log('redis/on/ready', )
                        })
                            .on('error', function () {
                            // console.log('redis/on/error', )
                        })
                            .on('close', function () {
                            console.log('redis/on/close');
                        })
                            .on('reconnecting', function () {
                            // console.log('redis/on/reconnecting', )
                        })
                            .on('end', function () {
                            console.log('redis/on/end');
                            (0, ssh_service_1.closeWebSocketByConnectionId)(connectionId);
                        });
                        if (!test) return [3 /*break*/, 6];
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, g_redis.connect()];
                    case 2:
                        _c.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        err_1 = _c.sent();
                        console.log('err', err_1);
                        return [3 /*break*/, 4];
                    case 4:
                        _b = {};
                        return [4 /*yield*/, g_redis.ping()];
                    case 5: 
                    // console.log('after connect')
                    return [2 /*return*/, (_b.ping = _c.sent(),
                            _b)];
                    case 6:
                        // g_redis.on()
                        g_redis.__db = 0; // 默认数据库 0
                        clients[connectionId] = {
                            redis: g_redis,
                            params: params,
                        };
                        _c.label = 7;
                    case 7:
                        _c.trys.push([7, 9, , 10]);
                        return [4 /*yield*/, g_redis.connect()];
                    case 8:
                        _c.sent();
                        return [3 /*break*/, 10];
                    case 9:
                        err_2 = _c.sent();
                        console.log('err', err_2);
                        return [3 /*break*/, 10];
                    case 10: return [4 /*yield*/, g_redis.ping()
                        // await g_redis.connect()
                        // .catch(err2 => {
                        //     console.log('err2', err2.message, err2)
                        // })
                        // try {
                        // }
                        // catch (err) {
                        //     console.log('err', err.message, err)
                        // }
                    ];
                    case 11:
                        _c.sent();
                        // await g_redis.connect()
                        // .catch(err2 => {
                        //     console.log('err2', err2.message, err2)
                        // })
                        // try {
                        // }
                        // catch (err) {
                        //     console.log('err', err.message, err)
                        // }
                        return [2 /*return*/, {
                                connectionId: connectionId,
                            }];
                }
            });
        });
    };
    RedisService.prototype.keys = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            function asyncMap(list, cb) {
                return __awaiter(this, void 0, void 0, function () {
                    var results, _i, list_1, item, _a, _b;
                    return __generator(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                results = [];
                                _i = 0, list_1 = list;
                                _c.label = 1;
                            case 1:
                                if (!(_i < list_1.length)) return [3 /*break*/, 4];
                                item = list_1[_i];
                                _b = (_a = results).push;
                                return [4 /*yield*/, cb(item)];
                            case 2:
                                _b.apply(_a, [_c.sent()]);
                                _c.label = 3;
                            case 3:
                                _i++;
                                return [3 /*break*/, 1];
                            case 4: return [2 /*return*/, results
                                // return Promise.all(list.map(item => {
                                //     return new Promise((resolve) => {
                                //         cb(item).then(() => {
                                //             resolve()
                                //         })
                                //     })
                                // }))
                            ];
                        }
                    });
                });
            }
            var g_redis, _a, db, keyword, cursor, _b, page, _c, pageSize, total, _d, _cursor, list, pipeline, keys, newList;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0: return [4 /*yield*/, getRedis(body)];
                    case 1:
                        g_redis = _e.sent();
                        _a = body.db, db = _a === void 0 ? 0 : _a, keyword = body.keyword, cursor = body.cursor, _b = body.page, page = _b === void 0 ? 1 : _b, _c = body.pageSize, pageSize = _c === void 0 ? 100 : _c;
                        // @ts-ignore
                        g_redis.__db = db;
                        g_redis.select(db);
                        return [4 /*yield*/, g_redis.dbsize()];
                    case 2:
                        total = _e.sent();
                        return [4 /*yield*/, getRedisKeys(g_redis, keyword, {
                                page: page,
                                pageSize: pageSize,
                                cursor: cursor,
                            })];
                    case 3:
                        _d = _e.sent(), _cursor = _d.cursor, list = _d.list;
                        pipeline = g_redis.pipeline();
                        list.forEach(function (key) { return pipeline.type(key); });
                        return [4 /*yield*/, pipeline.exec()
                            // list = await asyncMap(list, async key => {
                            //     return {
                            //         key,
                            //         // type: await g_redis.type(key),
                            //         type: 'string',
                            //     }
                            // })
                        ];
                    case 4:
                        keys = _e.sent();
                        newList = list.map(function (key, idx) {
                            var _a = keys[idx], err = _a[0], type = _a[1];
                            return {
                                key: key,
                                // type: await g_redis.type(key),
                                type: type,
                                // type: 'string',
                            };
                        });
                        return [2 /*return*/, {
                                total: total,
                                cursor: _cursor,
                                list: newList,
                                // keys,
                            }];
                }
            });
        });
    };
    RedisService.prototype.historyList = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, page, _b, pageSize, keyword, countSql, countResults, total, offset, sql, list;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = params.page, page = _a === void 0 ? 1 : _a, _b = params.pageSize, pageSize = _b === void 0 ? 10 : _b, keyword = params.keyword;
                        countSql = "SELECT COUNT(*) FROM redis_history";
                        return [4 /*yield*/, dbQueryList(countSql)
                            // console.log('countResults', countResults)
                        ];
                    case 1:
                        countResults = _c.sent();
                        total = countResults[0]['COUNT(*)'];
                        offset = (page - 1) * pageSize;
                        sql = "SELECT * FROM redis_history ORDER BY create_time DESC LIMIT ".concat(offset, ", ").concat(pageSize);
                        return [4 /*yield*/, dbQueryList(sql)
                            // db.each("", (err, row) => {
                            //     console.log('row', err, row)
                            //     // console.log(row.id + ": " + row.info);
                            //     list.push(row)
                            // })
                            // console.log('historyList end', )
                        ];
                    case 2:
                        list = _c.sent();
                        // db.each("", (err, row) => {
                        //     console.log('row', err, row)
                        //     // console.log(row.id + ": " + row.info);
                        //     list.push(row)
                        // })
                        // console.log('historyList end', )
                        return [2 /*return*/, {
                                total: total,
                                list: list,
                            }];
                }
            });
        });
    };
    RedisService.prototype.historyClear = function (_data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, historyClear()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    RedisService.prototype.keyCreate = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key;
            return __generator(this, function (_a) {
                key = data.key;
                dbInsertKey(key);
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.keyRemove = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var id;
            return __generator(this, function (_a) {
                id = data.id;
                dbRemoveKey(id);
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.keyList = function (params) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, page, _b, pageSize, keyword, countSql, countResults, total, offset, sql, list;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = params.page, page = _a === void 0 ? 1 : _a, _b = params.pageSize, pageSize = _b === void 0 ? 10 : _b, keyword = params.keyword;
                        countSql = "SELECT COUNT(*) FROM redis_history";
                        return [4 /*yield*/, dbQueryList(countSql)
                            // console.log('countResults', countResults)
                        ];
                    case 1:
                        countResults = _c.sent();
                        total = countResults[0]['COUNT(*)'];
                        offset = (page - 1) * pageSize;
                        sql = "SELECT * FROM redis_key ORDER BY create_time DESC LIMIT ".concat(offset, ", ").concat(pageSize);
                        return [4 /*yield*/, dbQueryList(sql)
                            // db.each("", (err, row) => {
                            //     console.log('row', err, row)
                            //     // console.log(row.id + ": " + row.info);
                            //     list.push(row)
                            // })
                            // console.log('historyList end', )
                        ];
                    case 2:
                        list = _c.sent();
                        // db.each("", (err, row) => {
                        //     console.log('row', err, row)
                        //     // console.log(row.id + ": " + row.info);
                        //     list.push(row)
                        // })
                        // console.log('historyList end', )
                        return [2 /*return*/, {
                                total: total,
                                list: list,
                            }];
                }
            });
        });
    };
    RedisService.prototype.connectionList = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content;
            return __generator(this, function (_a) {
                content = fs.readFileSync(redisConnectionFilePath, 'utf-8');
                return [2 /*return*/, {
                        list: JSON.parse(content)
                    }];
            });
        });
    };
    RedisService.prototype.connectionEdit = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, data, content, list, idx;
            return __generator(this, function (_a) {
                id = body.id, data = body.data;
                content = fs.readFileSync(redisConnectionFilePath, 'utf-8');
                list = JSON.parse(content);
                idx = list.findIndex(function (_item) { return _item.id == id; });
                list[idx] = __assign(__assign({}, list[idx]), data);
                console.log('list', list);
                fs.writeFileSync(redisConnectionFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.connectionCreate = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var content, list;
            return __generator(this, function (_a) {
                content = fs.readFileSync(redisConnectionFilePath, 'utf-8');
                list = JSON.parse(content);
                list.unshift(__assign(__assign({}, body), { id: (0, uid_1.uid)(32) }));
                fs.writeFileSync(redisConnectionFilePath, JSON.stringify(list, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.connectionDelete = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var id, content, list, newList;
            return __generator(this, function (_a) {
                id = body.id;
                content = fs.readFileSync(redisConnectionFilePath, 'utf-8');
                list = JSON.parse(content);
                newList = list.filter(function (item) { return item.id != id; });
                fs.writeFileSync(redisConnectionFilePath, JSON.stringify(newList, null, 4), 'utf-8');
                return [2 /*return*/, {}];
            });
        });
    };
    RedisService.prototype.flush = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(body)
                        // Redis 没有查看当前是哪个数据库的命令
                    ];
                    case 1:
                        g_redis = _a.sent();
                        // Redis 没有查看当前是哪个数据库的命令
                        return [4 /*yield*/, g_redis.flushdb()];
                    case 2:
                        // Redis 没有查看当前是哪个数据库的命令
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.flushAll = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, getRedis(body)
                        // Redis 没有查看当前是哪个数据库的命令
                    ];
                    case 1:
                        g_redis = _a.sent();
                        // Redis 没有查看当前是哪个数据库的命令
                        return [4 /*yield*/, g_redis.flushall()];
                    case 2:
                        // Redis 没有查看当前是哪个数据库的命令
                        _a.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    RedisService.prototype.gen2000 = function (body) {
        return __awaiter(this, void 0, void 0, function () {
            var g_redis, _a, number, pipeline, i, num;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, getRedis(body)];
                    case 1:
                        g_redis = _b.sent();
                        _a = body.number, number = _a === void 0 ? 100 : _a;
                        pipeline = g_redis.pipeline();
                        for (i = 0; i < number; i++) {
                            num = ('' + (i + 1)).padStart(('' + number).length, '0');
                            pipeline.set("gen:".concat(num), "value-".concat(num));
                        }
                        return [4 /*yield*/, pipeline.exec()];
                    case 2:
                        _b.sent();
                        return [2 /*return*/, {}];
                }
            });
        });
    };
    return RedisService;
}());
exports.RedisService = RedisService;
//# sourceMappingURL=redis.service.js.map