'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;
        console.log('params.username', params)
        let password = Hex.stringify(MD5(params.password));
        const userRes = await models.User.findOne({
            where: {
                $or: [{ username: params.username },
                { phone: params.username }
                ],
                password: password,
                delete: false,
            },
            attributes: { exclude: ['password', 'delete'] },
            include: [{
                attributes: ["resourceId", "isshow"],
                model: models.UserResource
            }]
        });
        console.log('userRes', userRes)
        if (!userRes.isAdmin) {
            ctx.status = 400;
            ctx.body = {
                "message": "不是管理员,禁止登录"
            }
        }
        else if (!userRes) {
            ctx.status = 400;
            ctx.body = {
                "message": "账号或密码错误"
            }
        } else if (!userRes.enable) {
            ctx.status = 400;
            ctx.body = { message: "该用户已被禁用" }
        } else {
            const token = uuid.v4();
            const { departmentId } = userRes.dataValues;
            const deptInfo = await models.Department.findOne({
                where: {
                    id: departmentId
                }
            })
            let userRslt = Object.assign(userRes.dataValues, {
                authorized: true,
                token: token,
            });

            await models.UserToken.create({
                token: token,
                userInfo: userRslt,
                expired: moment().add(30, 'days').format()
            });

            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": "登录失败"
        }
    }
}

/**
 * 微信小程序登录
 * @@requires.body {phone-手机号, password-密码} ctx 
 */
async function wxLogin (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({
            where: {
                phone: params.phone,
                password: password,
                delete: false,
            },
            attributes: { exclude: ['password', 'delete'] },
            include: [{
                attributes: ["resourceId", "isshow"],
                model: models.UserResource
            }]
        });
        if (!userRes) {
            ctx.status = 400;
            ctx.body = { message: "手机号或密码错误" }
        } else if (!userRes.enable) {
            ctx.status = 400;
            ctx.body = { message: "该用户已被禁用" }
        } else {
            const token = uuid.v4();

            let userRslt = Object.assign({
                authorized: true,
                loginSource: 'wx',
                token: token,
                ...userRes.dataValues,
            });

            if (params.phone == 'SuperAdmin') {
                const allResource = await models.Resource.findAll({})
                userRslt.userResources = allResource.map(r => {
                    return {
                        resourceId: r.dataValues.code
                    }
                })
            }
            await models.UserToken.create({
                token: token,
                userInfo: userRslt,
                expired: moment().add(30, 'day').format('YYYY-MM-DD HH:mm:ss')
            }, { transaction: transaction });



            ctx.status = 200;
            ctx.body = Object.assign({
                ...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, code } = ctx.request.body;
        const models = ctx.fs.dc.models;

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

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

module.exports = {
    login,
    wxLogin,
    logout,
};