var system = require("../../../system")
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');

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

  async login(pobj, qobj, req) {
    let loginName = this.trim(pobj.loginName);
    let password = this.trim(pobj.password);
    try {
      let user = await this.service.findOne({"userName": loginName});
      if (!user) {
        return system.getResultFail(-1, "用户不存在");
      }

      if (user.password !== this.encryptPasswd(password)) {
        return system.getResultFail(-1, "用户名或密码错误");
      }

      let sid = await this.setLogin(user);
      return system.getResultSuccess(sid);
    } catch (error) {
      console.log(error);
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async register(pobj, qobj, req) {
    try {
      let user = await this.service.create({
        userName: this.trim(pobj.userName),
        password: this.encryptPasswd(pobj.password),
        mobile: this.trim(pobj.mobile),
        nickName: this.trim(pobj.nickName),
        sign_body: this.trim(pobj.sign_body),
        isAdmin: Number(pobj.isAdmin) ? true : false,
      });

      return system.getResultSuccess(user);
    } catch (error) {
      console.log(error);
      if (error.message == 'Validation error') {
        return system.getResult(-1, "用户名已存在");
      }
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async setLogin(user) {
    let sid = uuidv4();
    await this.redisClient.setWithEx(sid, JSON.stringify(user), 60 * 60 * 5);
    return sid;
  }
}

module.exports = UserCtl;