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.saasbusinessDao = system.getObject("db.saas.saasbusinessDao");
  }

  async updateChannelIdBySaasId(params) {
    let rs = await this.dao.updateChannelIdBySaasId(params);
    return system.getResult(rs);
  }

  // 内部维护使用
  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 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 save(params) {
    let id = this.trim(params.id);
    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 channel_id = this.trim(params.channel_id || 0);
    let saas_id = this.trim(params.saas_id || 0);
    let saas = await this.saasbusinessDao.findById(saas_id);
    if (!saas) {
      return system.getResult(null, "saas不存在");
    }

    if (!ucname) {
      return system.getResult(null, "请填写用户名");
    }
    let user;
    if (id) {
      user = await this.dao.findById(id);
    } else {
      user = {};
    }
    user.ucname = ucname;
    user.mobile = mobile;
    user.realName = realName;
    // 登录名验证
    let exists = await this.dao.findOne({
      ucname: ucname
    });
    if ((exists && !user.id) || (exists && user.id && user.id != exists.id)) {
      return system.getResult(null, `用户名[${ucname}]已存在`);
    }
    let encryptPassword = await this.getEncryptStr(password);
    // 保存密码
    if (user.id) {
      // 传入密码为空或加密密码与数据库相同，不进行修改
      if (encryptPassword && encryptPassword != user.password) {
        user.password = encryptPassword;
      }
      user = await user.save();
    } else {
      if (!encryptPassword) {
        return system.getResult(null, "请填写密码");
      }
      user.saas_id = saas_id;
      user.channel_id = channel_id;
      user.isMain = false;
      user.isEnabled = true;
      user.password = encryptPassword;
      console.log(`密码加密：${password} -------> ${encryptPassword}`);
      user = await this.dao.create(user);
    }
    return system.getResultSuccess(user);
  }

  async pageByCondition(params) {
    var result = {
      count: 0,
      rows: []
    };
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);
    var total = await this.dao.countByCondition(params);
    if (total == 0) {
      return system.getResultSuccess(result);
    }

    result.count = total;
    params.startRow = (currentPage - 1) * pageSize;
    result.rows = await this.dao.listByCondition(params) || [];
    if (result.rows) {
      for (let item of result.rows) {
        this.handleDate(item, ["created_at"], null, -8);
      }
    }
    return system.getResultSuccess(result);
  }

  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);
  }

  async updPassword(params) {
    let user = await this.findById(params.id);
    if (!user) {
      return system.getResult(null, "用户不存在");
    }

    user.password = await this.getEncryptStr(params.password);
    await user.save();
    return system.getResultSuccess();
  }
}

module.exports = SaasPlatformUserService;