'use strict';
const redis = require("ioredis")
const moment = require('moment')

module.exports = async function factory (app, opts) {
    let client = new redis(opts.redis.port, opts.redis.host);

    client.on("error", function (err) {
        app.fs.logger.error('info', '[FS-AUTH-REDIS]', 'redis connect error.');
        console.error("Error :", err);
        process.exit(-1);
    });

    client.on('connect', function () {
        console.log(`redis connect success ${opts.redis.host + ':' + opts.redis.port}`);
    })

    // 查询尚未过期token放入redis
    const tokenRes = await app.fs.dc.models.UserToken.findAll({
        where: {
            expired: { $gte: moment().format('YYYY-MM-DD HH:mm:ss') }
        }
    });

    for (let t of tokenRes) {
        const { token, dataValues } = t
        dataValues.userInfo = JSON.stringify(dataValues.userInfo)
        dataValues.expired = moment(dataValues.expired).format()
        await client.hmset(token, dataValues);
    }
    // token 2 redis end

    // 自定义方法
    async function hdelall (key) {
        const obj = await client.hgetall(key);
        const hkeys = Object.keys(obj)
        await client.hdel(key, hkeys)
    }

    app.redis = client
    app.redisTools = {
        hdelall,
    }
}