const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class TUserService extends ServiceBase {
  constructor() {
    super("tax", ServiceBase.getDaoName(TUserService));
    this.tcompanyDao = system.getObject("db.tax.tcompanyDao");
  }
  
  async smartLogin(params) {
    let userName = this.trim(params.userName);
    let mchtId = this.trim(params.mchtId);
    let companyName = this.trim(params.companyName);

    let user;
    let company;
    let password = "";
    if(userName.length > 6) {
      password = await this.getEncryptStr(userName.substring(userName.trim().length - 6));
    } else {
      password = await this.getEncryptStr(userName);
    }

    user = await this.dao.findOne({mchtId: mchtId});
    if (!user) {
      user = await this.dao.model.create({
        ucname: userName,
        password: password,
        companyId: 0,
        mchtId: mchtId,
      });
    }
    if(user.companyId) {
      company = await this.tcompanyDao.findById(user.companyId);
      if(!company) {
        company = await this.tcompanyDao.model.create({
          name: companyName,
          mchtId: mchtId,
        });
      }
    } else {
      company = await this.tcompanyDao.findOne({mchtId: mchtId});
      if(!company) {
        company = await this.tcompanyDao.model.create({
          name: companyName,
          mchtId: mchtId,
        });
      }
    }

    if(!user.companyId) {
      user.companyId = company.id;
      await user.save();
    }
    return system.getResultSuccess({
      user: user,
      company: company,
    });
  }
}
module.exports = TUserService;
