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


    this.authSve = system.getObject("service.auth.authSve");
  }


  /**
   * 条件查询
   * @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 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) {
    // 登录成功，补充登录所需内容
    // 详情
    user.info = await this.userinfoDao.findById(user.id);

    // 用户类型 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) {
      // 菜单权限
      user.menus = await this.authSve.menuByRoleIds(authParams);
      // 接口权限
      user.auths = await this.authSve.authByRoleIds(authParams);
    }
  }

  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 = Number(obj.uctype || 1);
    var uctypeId = this.trim(obj.uctypeId);
    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,
      uctypeId: uctypeId,
      org_id: org.id || 0,
      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 (user.uctype === 1) {
        orgpath = isMain ? orgpath : orgpath + "/" + user.id;
        await self.dao.update({
          id: user.id,
          orgpath: orgpath
        }, t);
      }
      user.orgpath = orgpath;
      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 uctypeId = this.trim(obj.uctypeId);
    var mobile = this.trim(obj.mobile);
    var realName = this.trim(obj.realName);
    var isMain = obj.isMain || 0;

    var user = {
      id: id,
      uctype: uctype,
      uctypeId: uctypeId,
      org_id: org.id || "",
      orgpath: "",
      isMain: obj.isMain || 0,
    }

    if (user.uctype === 1) {
      user.orgpath = isMain ? org.path : org.path + "/" + id;
    }

    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, "user_id, role_id");
    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);

    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 (var item of result.rows) {
        this.handleDate(item, ["created_at"], null, -8);
      }
    }
    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();
  }
}
module.exports = UserService;