const system = require("../../system");
const ServiceBase = require("../sve.base");
class ProxyapplicantService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(ProxyapplicantService));
    this.userSve = system.getObject("service.userSve");
    this.roleDao=system.getObject("db.roleDao");
  }

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

    if (tc.auditStatus != '0') {
      // 该合伙人已审核
      return -1;
    }
    var passwd = super.encryptPasswd(tc.mobile.substring(tc.mobile.length - 6));
    return this.db.transaction(async function (t) {
      var updateFields = {
        auditStatus: "1",
        auditStatusName: "审核通过",
        audit_id: opUserId,
      }
      // 更新派工态
      await self.dao.model.update(updateFields, {where: {id: id}, transaction: t});
      var user = await self.userSve.findOne({userName:tc.mobile});
      if(user) {
        if(!user.isPartner) {
          await self.dao.model.update({user_id:user.id}, {where: {id: id}, transaction: t});
          user.isPartner = true;

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

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

  }
}
module.exports = ProxyapplicantService;