'use strict';
const Hex = require('crypto-js/enc-hex');
const MD5 = require('crypto-js/md5');
const moment = require('moment');
const uuid = require('uuid');

async function login (ctx, next) {
    const transaction = await ctx.fs.dc.orm.transaction();
    try {
        const models = ctx.fs.dc.models;
        const params = ctx.request.body;
        let password = Hex.stringify(MD5(params.password));

        const userRes = await models.User.findOne({
            attributes: { exclude: ['password'] },
            where: {
                username: params.username,
                password: password,
                delete: false,
            },
        });

        if (!userRes) {
            ctx.status = 400;
            ctx.body = {
                "message": "账号或密码错误"
            }
        } else if (!userRes.enabled) {
            ctx.status = 400;
            ctx.body = { message: "该用户已被禁用" }
        } else {
            const token = uuid.v4();

            let userRslt = Object.assign(
                userRes.dataValues,
                {
                    authorized: true,
                    token: token,
                    resources: []
                }
            );

            let tokenMsg = {
                token: token,
                userInfo: userRslt,
                expired: moment().add(30, 'days').format()
            }

            await models.UserToken.create(tokenMsg);

            tokenMsg.userInfo = JSON.stringify(tokenMsg.userInfo)
            tokenMsg.expired = moment(tokenMsg.expired).format()
            await ctx.redis.hmset(token, tokenMsg);

            ctx.status = 200;
            ctx.body = userRslt;
        }
        await transaction.commit();
    } catch (error) {
        await transaction.rollback();
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "登录失败"
        }
    }
}

async function logout (ctx) {
    try {
        const { token } = ctx.request.body;
        const models = ctx.fs.dc.models;

        await models.UserToken.destroy({
            where: {
                token: token,
            },
        });

        await ctx.redisTools.hdelall(token);

        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "退出失败"
        }
    }
}

async function loginAxy (ctx) {
    try {
        const data = ctx.request.body;
        const models = ctx.fs.dc.models;
        await models.UserToken.create(data);

        ctx.status = 204;
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            "message": "IOT AUTH 信息记录失败"
        }
    }
}

async function checkCrossToken (ctx) {
    try {
        const { token } = ctx.request.body;

        let cross = false
        const expired = await ctx.redis.hget(token, 'expired');
        // 也可以在这里做延时操作 需要同步数据库(也可能安心云)
        if (expired && moment().valueOf() <= moment(expired).valueOf()) {
            cross = true
        }

        ctx.status = 200;
        ctx.body = {
            cross,
        }
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {}
    }
}

module.exports = {
    login,
    logout,
    loginAxy,
    checkCrossToken,
};