#include "SysUserService.h"

#include <QCryptographicHash>

SysUserService::SysUserService()
{

}

bool SysUserService::verifySysUser(QString account, QString password, QMap<QString, QVariant> &user)
{
    SystemDao sysDao;
    bool verifyPass = false;

    user = sysDao.getSysUserByAccount(account);
    if (user.value("id").toString().isEmpty() == false) {
        // ID不为空表示查询到指定账户的user

        // 验证密码
        // 将salt转成MD5
        QCryptographicHash hash(QCryptographicHash::Md5);
        hash.addData(user.value("salt").toString().toUtf8());
        QByteArray saltRst = hash.result();
        QString saltMD5 = saltRst.toHex();

        // 处理用户输入的password部分
        hash.reset();
        hash.addData(saltRst);
        hash.addData(password.toUtf8());

        QByteArray pwdRst = hash.result();
        for (int i = 0; i < 999; i++) {
            hash.reset();
            hash.addData(pwdRst);

            pwdRst = hash.result();
        }
        QString pwdMD5 = pwdRst.toHex();

        verifyPass = pwdMD5.compare(user.value("password").toString(), Qt::CaseInsensitive) == 0;
        if (verifyPass) {
            // 查找用户权限
            sysDao.getUserRoleIdAndName(user.value("id").toString(), user);
        } else {
            // 密码匹配失败
            LogUtil::PrintLog("ERROR", QString("%1登录失败[%2]").arg(account).arg("用户名或密码错误"));
        }
    }

    return verifyPass;
}
