// 逻辑作接口-移动端用户登录
// 秒寻科技
// zt
//2024-02-2

package wxminiloginlogic

import (
	"ipsomc/core/company/companyapi"
	"ipsomc/core/company/companymodel"
	"ipsomc/core/dao/redis/redisapi"
	"ipsomc/core/dao/redis/redismodel"
	"ipsomc/core/usermobile/usermobileapi"
	"ipsomc/core/usermobile/usermobilemodel"
	"ipsomc/core/wxminilogin/wxminiloginapi"
	"ipsomc/core/wxminilogin/wxminiloginmodel"
	"ipsomc/module/project/projectapi"
	"ipsomc/module/project/projectmodel"
	"ipsomc/util"
	"strconv"
	"time"
)

type WxMiniLoginLgc struct {
	wxminiloginApi wxminiloginapi.WxMiniLoginApi
	usermobileApi  usermobileapi.UserMobileApi
	projectApi     projectapi.ProjectApi
	companyApi     companyapi.CompanyApi
	redisApi       redisapi.RedisApi
}

// 检查用户是否已经登录过，若曾经登录过则返回用户信息给前端，若未曾登录则操作数据库添加记录
func (obj *WxMiniLoginLgc) UserLoginLgc(dataModel *wxminiloginmodel.UserMobileLogin, mobileUserRespModel *usermobilemodel.UserMobile) error {
	//向微信服务器发送登录凭证，获得openid
	if err := obj.wxminiloginApi.GetOpenIdByCode(dataModel); err != nil {
		return err
	}

	//根据用户openid获得信息
	mobileUser := new(usermobilemodel.UserMobile)
	mobileUser.OpenID = dataModel.Openid
	if err := obj.usermobileApi.GetUserByOpenId(mobileUser); err != nil {
		return err
	}

	//根据二级域名获得项目信息
	projectModel := new(projectmodel.Project)
	projectModel.DomainName = dataModel.DomainName
	if err := obj.projectApi.GetProjectByDomainName(projectModel); err != nil {
		return err
	}

	//判断用户是否曾经已经登录
	if mobileUser.ID <= 0 { //没有登录过
		companyModel := new(companymodel.Company)
		companyModel.ID = projectModel.CompanyID
		if err := obj.companyApi.GetCompanyById(companyModel); err != nil {
			return err
		}

		//注册移动端用户
		mobileUser.CompanyID = companyModel.ID
		mobileUser.UserType = 2 //小程序登录
		mobileUser.OpenID = dataModel.Openid
		if err := obj.usermobileApi.AddUserByOpenId(mobileUser); err != nil {
			return err
		}
	} else { //曾经登录过
		mobileUser.ProjectID = projectModel.ProjectID
	}

	//将用户数据保存到redis中
	uuid := util.GenerateUuid()                                       //产生随机字符
	token := "mtoken" + strconv.Itoa(int(mobileUser.ID)) + "-" + uuid //生成用户token
	redisModel := new(redismodel.RedisUserMobile)
	redisModel.CompanyID = mobileUser.CompanyID
	redisModel.ProjectID = mobileUser.ProjectID
	redisModel.UserType = mobileUser.UserType
	redisModel.UserID = mobileUser.ID
	redisModel.Nickname = mobileUser.Nickname
	redisModel.Token = token
	redisModel.TokenTime = time.Now().Format("2006-01-02 15:16:17")
	if err := obj.redisApi.SetModelData(token, redisModel, 60); err != nil { //以用户的token为键
		return err
	}

	//组织返回数据
	mobileUserRespModel.Token = token
	mobileUserRespModel.ID = mobileUser.ID
	mobileUserRespModel.UserType = mobileUser.UserType

	return nil
}
