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.userroleDao = system.getObject("db.user.userroleDao");
    this.authSve = system.getObject("service.auth.authSve");
    this.roleDao = system.getObject("db.role.roleDao");
    this.orgDao = system.getObject("db.org.orgDao");
  }


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

  /**
   * 根据path查询所有的用户
   * @param {*} params
   */
  async apiQueryUserByPath(params) {
    try {
      return await this.queryUserByPath(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 login(obj) {
    var uctype = Number(obj.uctype || 0);

    var user = await this.dao.getByUcname(obj.ucname);
    // 验证登录合法
    if (!user) {
      return system.getResult(null, "用户名或密码错误");
    }
    if (!user.isEnabled) {
      return system.getResult(null, "用户已禁用");
    }

    if (uctype && uctype != user.uctype) {
      return system.getResult(null, "用户类型错误");
    }

    var loginPwd = await this.getEncryptStr(obj.password);
    if (loginPwd != user.password) {
      return system.getResult(null, "用户名或密码错误");
    }

    await this.setLoginUser(user);

    return system.getResultSuccess(user);
  }

  async loginByUcid(obj) {
    var user = await this.dao.getByUcid(obj.ucid);
    // 验证登录合法
    if (!user) {
      return system.getResult(null, "用户名或密码错误");
    }
    await this.setLoginUser(user);
    return system.getResultSuccess(user);
  }

  async setLoginUser(user) {
    // 登录成功，补充登录所需内容
    // 用户类型 1平台 2商户 3交付商 4个人
    var uctype = user.uctype;

    // 角色
    user.roles = await this.userroleDao.findUserRoles(user.id);
    // 构建请求权限接口参数
    var roleIds = [];
    for (var role of user.roles) {
      roleIds.push(role.id);
    }
    var authParams = {
      roleIds: roleIds,
      saas_id: user.saas_id,
    }

    if (uctype == 1 && roleIds.length > 0) {
      // 菜单权限
      user.menus = await this.authSve.menuByRoleIds(authParams);
      // 接口权限
      user.auths = await this.authSve.authByRoleIds(authParams);
    }
  }

  async saveUser(obj) {
    try {
      var id = obj.id;
      var roleIds = obj.roles || [];
      var org_id = this.trim(obj.org_id);

      let roles = [];
      for (let roleId of roleIds) {
        roles.push({role_id: roleId});
      }

      if (!obj.saas_id) {
        return system.getResult(null, "saas_id不存在");
      }
      let user = {};

      if (id) {
        let u = await this.findById(id);
        if (u) {
          user.id = u.id;
        }
      }

      let exist = await this.findOne({
        ucname: obj.ucname
      });
      if (user.id) {
        if (exist && exist.id != user.id) {
          return system.getResult(null, `用户名【${ucname}】已存在`);
        }
      } else {
        if (exist) {
          return system.getResult(null, `用户名【${ucname}】已存在`);
        }
        user.password = await this.getEncryptStr(obj.password);
      }

      let org = await this.orgDao.findById(org_id);
      if (!org) {
        return system.getResult(null, `组织机构不存在`);
      }
      user.ucid = this.trim(obj.ucid);
      user.ucname = this.trim(obj.ucname);
      user.uctype = 1;
      user.uctypeId = "";
      user.mobile = this.trim(obj.mobile);
      user.realName = this.trim(obj.realName);
      user.org_id = org_id;
      user.saas_id = this.trim(obj.saas_id);
      var self = this;
      user = await self.db.transaction(async function (t) {
        if (user.id) {
          await self.dao.update(user, t);
        } else {
          // 创建商户
          user = await self.dao.create(user, t);
        }
        await self.userroleDao.delByUserId(user.id, t);

        if (roles && roles.length > 0) {
          for (var r of roles) {
            r.user_id = user.id;
          }
          await self.userroleDao.bulkCreate(roles, t);
        }
        user.orgpath = org.path + "/" + user.id + "/";
        await self.dao.update({
          id: user.id,
          orgpath: user.orgpath
        }, t);
        return user;
      });

      return system.getResultSuccess(user);
    } catch (error) {
      console.log(error);
      if (error.name == 'SequelizeValidationError') {
        return system.getResult(-1, `用户名重复`);
      }

      return system.getResult(-1, `系统错误 错误信息${error}`);
    }
  }

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

    user.roles = await this.userroleDao.listByUserId(id, "user_id, role_id");
    await this.setRoles([user]);
    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 pageByCondition(params) {
    var result = {
      count: 0,
      rows: []
    };
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);
    if (params.orgpath) {
      params.orgpath = params.orgpath + "%";
    }

    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) || [];
    if (result.rows) {
      for (let item of result.rows) {
        this.handleDate(item, ["created_at"], null, -8);
      }
      await this.setRoles(result.rows);
      await this.setOrg(result.rows);
    }
    return system.getResultSuccess(result);
  }

  async delUser(params) {
    var user = await this.findById(params.id);
    if (!user) {
      return system.getResultSuccess();
    }
    if (user.saas_id != params.saas_id) {
      return system.getResult(null, "权限不足");
    }
    await this.delete({
      id: params.id
    });
    return system.getResultSuccess();
  }

  async updPassword(params) {
    var 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();
  }

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

  async findUsers(params) {
    if (params.roleCodes && params.roleCodes.length > 0) {
      var roleIds = await this.roleDao.findIdsByCode(params.roleCodes, params.saas_id);
      if (!roleIds) {
        return [];
      }
      params.roleIds = roleIds;
    }
    let rs = await this.dao.findUsers(params);
    return system.getResultSuccess(rs);
  }

  async setOrg(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    let orgIds = [];
    for (let row of rows) {
      orgIds.push(row.org_id);
    }

    let map = await this.orgDao.mapByIds(orgIds);
    for (let row of rows) {
      let org = map[row.org_id] || {};
      row.orgname = org.orgname || "";
      row.org = org;
    }
  }

  async setRoles(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    let userIds = [];
    for (let row of rows) {
      userIds.push(row.id);
    }

    let rolesMap = await this.userroleDao.mapByUserIds2(userIds);
    for (let row of rows) {
      let roleIds = [];
      let roleNames = [];
      let roles = rolesMap[row.id] || [];
      for (let r of roles) {
        roleIds.push(r.id);
        roleNames.push(r.name);
      }
      row.roleIds = roleIds.join(",");
      row.roleNames = roleNames.join(",");
      row.roles = roles;
    }
  }

}

module.exports = UserService;