const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
  constructor() {
    super("auth", ServiceBase.getDaoName(UserService));
    this.platformUtils = system.getObject("util.businessManager.opPlatformUtils");
  }

  async saveUser(user) {
    var u = await this.dao.findOne({
      ucid: user.ucid,
    }) || {};

    u.ucid = user.ucid;
    u.ucname = user.ucname;
    u.passwd = user.passwd;
    u.lastLoginTime = user.lastLoginTime;
    if(u.id) {
     u = await this.dao.create(ucid);
    } else {
      await u.save();
    }
    return u;
  }

  async authByCode(opencode) {
    var existedUser = null;
    var rawUser = null;
    var openuser = await this.apiCallWithAk(settings.paasUrl() + "api/auth/accessAuth/authByCode", { opencode: opencode });
    if (openuser) {
      //先查看自己系统中是否已经存在当前用户
      existedUser = await this.dao.model.findOne({ where: { ucname: openuser.userName, ucid: openuser.account_id }, raw: true });
      if (!existedUser) {
        existedUser = await this.register(openuser);
      }
      rawUser = existedUser;
      rawUser.Roles = openuser.Roles;
    }
    return rawUser;
  }
  async getUserLoginInfo(token) {
    var acckapp = await this.cacheManager["ApiUserCache"].cache(token, null, settings.usertimeout);
  }
  async register(openuser) {
    var param = {
      ucname: openuser.userName, ucid: openuser.account_id,
      lastLoginTime: new Date()
    }
    var cruser = await this.dao.create(param);
    return cruser;
  }
  //在平台进行登录，返回目标认证地址
  async navSysSetting(user) {
    var sysLoginUrl = settings.paasUrl() + "web/auth/userCtl/login?appKey=" + settings.appKey + "\&toKey=" + settings.paasKey;
    var x = { userName: user.userName, password: user.password, mobile: user.mobile };
    var restResult = await this.restS.execPost({ u: x }, sysLoginUrl);
    if (restResult) {
      var rtnres = JSON.parse(restResult.stdout);
      if (rtnres.status == 0) {
        return rtnres.data;
      }
    }
    return null;
  }
  async getUserByUserNamePwd(u) {
    var user = await this.dao.model.findOne({
      where: { userName: u.userName, password: u.password, app_id: u.app_id },
      include: [
        { model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
      ]
    });
    return user;
  }
  async checkSameName(uname, appid) {
    var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid } });
    var rtn = { isExist: false };
    if (ac) {
      rtn.isExist = true;
    }
    return rtn;
  }
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
