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

class SaasMerchantUserService extends ServiceBase {
  constructor() {
    super("user", ServiceBase.getDaoName(SaasMerchantUserService));
  }

  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 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, "用户不存在");
    }
    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 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);
  }
}

module.exports = SaasMerchantUserService;