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

class SaasBusinessService extends ServiceBase {
  constructor() {
    super("saas", ServiceBase.getDaoName(SaasBusinessService));
    this.saasplatformuserDao = system.getObject("db.user.saasplatformuserDao");
  }

  /**
   * 添加
   * @param {T} params
   */
  async openSaasBusiness(params) {
    let now = moment().format("YYYY-MM-DD HH:mm:ss");
    console.log(`saas business 信息插入 ： ${JSON.stringify(params)}, ${now}`);
    let saasid = Number(params.saasid || 0);
    let companyName = this.trim(params.companyName);
    let domain = this.trim(params.domain);
    let mobile = this.trim(params.mobile);
    let passwd = this.trim(params.passwd);
    let realName = this.trim(params.realName);
    try {
      let sb = {
        name: companyName,
        domain: domain,
        managerMobile: mobile,
      };
      if (saasid) {
        let exists = await this.dao.findById(saasid);
        if (exists) {
          return system.getResult(null, `saas[${saasid}]已存在`)
        }
        sb.id = saasid;
      }
      sb = await this.dao.create(sb);

      // 手机号存在，增加一个默认账号
      if (mobile) {
        let exists = await this.saasplatformuserDao.findOne({ucname: mobile});
        if (exists) {
          return system.getResult(null, `手机号[${mobile}]已存在`)
        }
        let user = await this.saasplatformuserDao.create({
          ucname: mobile,
          realName: realName,
          password: await this.getEncryptStr(passwd),
          isMian: true,
          saas_id: sb.id,
          isEnabled: true,
        });

        sb.managerId = user.id;
        await sb.save();
      }
      return system.getResult(sb);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error.stack}`);
    }
  }

}

module.exports = SaasBusinessService;