const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")

class SaasPlatformUserService extends ServiceBase {
  constructor() {
    super("user", ServiceBase.getDaoName(SaasPlatformUserService));
    this.saasDao = system.getObject("db.saas.saasDao");
  }

  // 内部维护使用
  async resetPasswordInner(params) {
    let user = await this.dao.findById(params.id);
    user.password = await this.getEncryptStr(user.password);
    await user.save();
    return system.getResultSuccess();
  }

  // 内部维护时使用
  async registerInner(params) {
    let ucname = this.trim(params.ucname);
    let password = this.trim(params.password);
    let realName = this.trim(params.realName);
    let mobile = this.trim(params.mobile);
    let saas_id = Number(params.saas_id || 0);
    if(!ucname) {
      return system.getResult(null, "请填写用户名");
    }
    if(!password) {
      return system.getResult(null, "请填写密码");
    }
    let pwd = await this.getEncryptStr(password);
    console.log(`密码加密：${password} -------> ${pwd}`);

    let saas = await this.saasDao.findById(saas_id);
    if(!saas) {
      return system.getResult(null, "saas不存在");
    }

    let exists = await this.dao.findOne({
      ucname: ucname
    });
    if(exists) {
      return system.getResult(null, `用户名[${ucname}]已存在`);
    }

    let user = {
      ucname: ucname,
      mobile: mobile,
      realName: realName,
      password: pwd,
      saas_id: saas_id,
      isMain: true,
      isEnabled: true,
    }
    user = await this.dao.create(user);
    return system.getResultSuccess(user);
  }

  async login(params) {
    let ucname = this.trim(params.ucname);
    let password = this.trim(params.password);

    if(!ucname || !password) {
      return system.getResult(null, "用户名或密码错误");
    }
    let pwd = await this.getEncryptStr(password);

    var user = await this.dao.byUcname(ucname);
    if(!user || pwd != user.password) {
      return system.getResult(null, "用户名或密码错误");
    }

    if(!user.isEnabled) {
      return system.getResult(null, "用户已禁用");
    }
    return system.getResultSuccess(user);
  }

  async info(params) {
    var id = Number(params.id || 0);
    var user = await this.dao.getById(id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }
    this.handleDate(user, ["created_at"], null, -8);
    return system.getResultSuccess(user);
  }

  async enabled(params) {
    var user = await this.dao.findById(params.id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }
    user.isEnabled = Number(params.enabled || 0) == 0 ? false : true;
    await user.save();
    return system.getResultSuccess();
  }

  async mapByIds(params) {
    let rs = await this.dao.findMapByIds(params.ids);
    return system.getResultSuccess(rs);
  }
}

module.exports = SaasPlatformUserService;