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

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

  async appletLogin(obj) {
    let saas_merchant_id = obj.saas_merchant_id;
    let saas_id = obj.saas_id;
    let openid = obj.openid;
    let nickName = this.trim(obj.nickName);
    let avatarUrl = this.trim(obj.avatarUrl);
    if (!saas_merchant_id) {
      return system.getResult(null, "登录失败，商户信息错误");
    }
    if (!openid) {
      return system.getResult(null, "登录信息获取失败");
    }

    let user = await this.dao.byOpenId(openid, saas_merchant_id);
    if (!user) {
      user = {
        openid: openid,
        nickName: nickName,
        avatarUrl: avatarUrl,
        saas_merchant_id: saas_merchant_id,
        saas_id: saas_id,
        mobile: "",
        ucname: "",
        password: "",
        isEnabled: true,
      };
      user = await this.dao.model.create(user);
    } else {
      if(avatarUrl) {
        user.avatarUrl = avatarUrl;
        await this.dao.update({
          id: user.id,
          avatarUrl: avatarUrl,
        });
      }
      if(nickName) {
        this.dao.update({
          id: user.id,
          nickName: nickName
        });
      }
    }
    return system.getResultSuccess(user);
  }

  async info(params) {
    let user = await this.dao.byOpenId(params.openid, params.merchant_id);
    return system.getResultSuccess(user);
  }

  async mapByIds(params) {
    let rs = await this.dao.findMapByIds(params.ids);
    return system.getResultSuccess(rs);
  }
}

module.exports = SaasMerchantAppletUserService;