const system = require("../../system");
const ServiceBase = require("../sve.base");
class EpartnerService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(EpartnerService));
    this.userSve = system.getObject("service.userSve");
    this.roleDao = system.getObject("db.roleDao");
  }
  
  async findMapByIds(ids) {
    var result = [];
    if(!ids || ids.length == 0) {
      return result;
    }

    var sql = "select * from c_epartner where id in (:ids)";
    var list = await this.customQuery(sql, {ids:ids});
    if(!list || list.length == 0) {
      return result;
    }

    for(var item of list) {
      result["id_" + item.id] = item;
    }

    return result;
  }
  
  async idsLikeNickName(nickName) {
    var result = [];
    if(!nickName || !nickName.trim()) {
      return result;
    }

    var sql = "SELECT id FROM c_epartner WHERE nickName LIKE :nickName ";
    var list = await this.customQuery(sql, {nickName : "%" + nickName + "%"});
    
    if(list) {
      for(var item of list) {
        result.push(item.id);
      }
    }
    return result;
  }

  async auditPass(id, opUserId) {
    var self = this;
    var epartner = await this.findById(id);

    if (epartner.auditStatus != '0') {
      // 该合伙人已审核
      return -1;
    }

    var now = new Date();
    var passwd = super.encryptPasswd(epartner.mobile.substring(epartner.mobile.length - 6));
    return this.db.transaction(async function (t) {
      var updateFields = {
        auditStatus: "1",
        auditStatusName: "审核通过",
        audit_id: opUserId,
        reg_at: now
      }

      await self.dao.model.update(updateFields, {where: {id: id}, transaction: t});
      var user = await self.userSve.findPartnerUser(epartner.userName);
      if(user) {
        if(!user.isPartner) {
          await self.dao.model.update({user_id:user.id}, {where: {id: id}, transaction: t});
          user.isPartner = true;
          user.utype = 1;

          var sql="insert into `p_userrole` (`created_at`,`updated_at`,`user_id`,`role_id`) values (?,?,?,?)";
          var params = {replacements: [now, now, user.id, 2], transaction:t};
          await self.dao.customExecAddOrPutSql(sql,params);
          await user.save();
        } else {
          return -2;
        }
      } else {
        user = {
          userName: epartner.userName,
          password: passwd,
          nickName: epartner.nickName,
          headUrl: "",
          onlyCode:"bpo_" + epartner.mobile,
          mobile:epartner.mobile,
          isPartner:true,
          utype: 1,
        }
        user = await self.userSve.registerPartner(user, t);

        await self.dao.model.update({user_id:user.id}, {where: {id: id}, transaction: t});
      }
      return 1;
    });
  }

  async suggest(name) {
    return await this.dao.suggest(name);
  }
}
module.exports = EpartnerService;