const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
  constructor() {
    super("user", ServiceBase.getDaoName(UserService));
    this.userinfoDao = system.getObject("db.user.userinfoDao");
    this.userroleDao = system.getObject("db.user.userroleDao");
  }


  /**
   * 条件查询
   * @param {*} params 
   */
  async apiFindUserBySaasId(params) {
    try {
      return await this.findUserBySaasId(params);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }


  /**************************************************************** */

  /**
   * 条件查询
   * @param {*} params 
   */
  async findUserBySaasId(params) {
    try {
      let res = await this.dao.findUserBySaasId(params);
      return system.getResult(res);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  async add(obj) {
    var roles = obj.roles || [];
    var org = obj.org;
    var saas_id = Number(obj.saas_id || 0);
    var ucid = this.trim(obj.ucid);
    var ucname = this.trim(obj.ucname);
    var password = this.trim(obj.password);
    var uctype = this.trim(obj.uctype);
    var mobile = this.trim(obj.mobile);
    var realName = this.trim(obj.realName);
    var isMain = obj.isMain || 0;

    if (!saas_id) {
      return system.getResult(null, "请指定saas_id");
    }

    var exist = await this.findOne({
      ucname: ucname
    });
    if (exist) {
      return system.getResult(null, `用户名【${ucname}】已存在`);
    }

    var user = {
      saas_id: saas_id,
      ucid: ucid,
      ucname: ucname,
      password: await this.getEncryptStr(password),
      uctype: uctype,
      org_id: org.id,
      isMain: isMain,
      orgpath: "",
      isEnabled: 1,
    }

    var orgpath = org.path;

    var info = {
      mobile: mobile,
      realName: realName,
    }

    var self = this;
    user = await self.db.transaction(async function (t) {
      // 创建商户
      user = await self.dao.create(user, t);
      info.id = user.id;

      info = await self.userinfoDao.create(info, t);

      if (roles && roles.length > 0) {
        for (var r of roles) {
          r.user_id = user.id;
        }
        await self.userroleDao.bulkCreate(roles, t);
      }

      if (!isMain) {
        orgpath = orgpath + "/" + user.id;
      }
      user.orgpath = orgpath;
      await self.dao.update({
        id: user.id,
        orgpath: orgpath
      }, t);
      return user;
    });

    return system.getResultSuccess(user);
  }

  async upd(obj) {
    var id = obj.id;
    var roles = obj.roles || [];
    var org = obj.org;
    var uctype = this.trim(obj.uctype);
    var mobile = this.trim(obj.mobile);
    var realName = this.trim(obj.realName);
    var isMain = obj.isMain || 0;

    var user = {
      id: id,
      org_id: org.id,
      orgpath: isMain ? org.path : org.path + "/" + id,
      isMain: obj.isMain || 0,
    }

    var info = {
      id: id,
      mobile: mobile,
      realName: realName,
    }

    var self = this;
    user = await self.db.transaction(async function (t) {
      // 创建商户
      await self.dao.update(user, t);
      await self.userinfoDao.update(info, t);

      await self.userroleDao.delByUserId(id, t);
      if (roles && roles.length > 0) {
        for (var r of roles) {
          r.user_id = id;
        }
        await self.userroleDao.bulkCreate(roles, t);
      }
      return user;
    });
    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, "用户不存在");
    }
    var info = await this.userinfoDao.getById(id);

    user.mobile = info.mobile;
    user.realName = info.realName;

    user.roles = await this.userroleDao.listByUserId(id);
    this.handleDate(user, ["created_at"], null, -8);
    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 result;
    }

    result.count = total;
    params.startRow = (currentPage - 1) * pageSize;
    result.rows = await this.dao.listByCondition(params) || [];
    return system.getResultSuccess(result);
  }

  async delUser(params) {
    await this.delete({
      id: params.id
    });

    return system.getResultSuccess();
  }


}
module.exports = UserService;