var system = require("../../../system")
const CtlBase = require("../../ctl.base");

class UserCtl extends CtlBase {
    constructor() {
        super("auth", CtlBase.getServiceName(UserCtl));
        this.redisClient = system.getObject("util.redisClient");
    }

    async login(pobj, qobj, req) {
        var loginName = this.trim(pobj.loginname);
        var password = this.trim(pobj.password);
        try {
            var user = await this.service.findOne({"loginname": loginName});
            if (!user) {
                return system.getResultFail(-1, "用户不存在");
            }
            user = user.dataValues;
            if (user.password !== super.encryptPasswd(password)) {
                return system.getResultFail(-1, "密码错误");
            }
            return system.getResultSuccess(user, "");
        } catch (error) {
            console.log(error);
            return system.getResultFail(500, "接口异常：" + error.message);
        }
    }

    async register(pobj, qobj, req) {
        if (!pobj.loginname) {
            return system.getResultFail(-1, "用户为空");
        }
        if (!pobj.password) {
            return system.getResultFail(-1, "密码为空");
        }
        var user = await this.service.findOne({
            loginname: pobj.loginname
        });
        if (user) {
            return system.getResultFail(-1, "用户已存在, 请修改并重试");
        }
        let inse = {
            loginname: pobj.loginname,
            password: super.encryptPasswd(pobj.password)
        };
        var u = await this.service.register(inse);

        return system.getResultSuccess(u, "注册成功");

    }

    async userList(queryobj, obj, req){
        var pageInfo = obj.pageInfo || {};
        var search = obj.search || {};
        var apps = await this.service.userPage(pageInfo, search);
        return system.getResultSuccess(apps, null);
    }


}

module.exports = UserCtl;