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

package usermobilelogic

import (
	"ipsomc/core/company/companymodel"
	"ipsomc/core/dao/mysql/mysqlapi"
	"ipsomc/core/dao/redis/redisapi"
	"ipsomc/core/dao/redis/redismodel"
	"ipsomc/core/usermobile/usermobileapi"
	"ipsomc/core/usermobile/usermobilemodel"
	"ipsomc/util"
	"strconv"
	"time"
)

type UserMobileLgc struct {
	mySqlApi mysqlapi.MySqlApi
	userApi  usermobileapi.UserMobileApi
	redisApi redisapi.RedisApi
}

// 检查用户是否已经登录过，若曾经登录过则返回用户信息给前端，若未曾登录则操作数据库添加记录
func (obj *UserMobileLgc) CheckUserLoginLgc(dataModel *usermobilemodel.UserMobile) error {
	var count uint8
	modelUser := new(usermobilemodel.UserMobile)

	//基于openid判断用户曾经是否登录
	if err := obj.mySqlApi.GetDb().Model(modelUser).Where("openid=?", dataModel.OpenID).Count(&count).Error; err != nil {
		return err
	}

	//曾经登录过
	if count > 0 {
		//获得用户信息
		if err := obj.mySqlApi.GetDb().Model(modelUser).Where("openid=?", dataModel.OpenID).First(modelUser).Error; err != nil {
			return err
		}

		//组织返回数据
		dataModel.CompanyID = modelUser.CompanyID
		dataModel.UserType = modelUser.UserType
		dataModel.ID = modelUser.ID
		dataModel.Nickname = modelUser.Nickname
		dataModel.Avatar = modelUser.Avatar
		dataModel.Province = modelUser.Province
		dataModel.City = modelUser.City
		dataModel.Country = modelUser.Country
	} else { //未曾登录
		//根据域名获得公司id
		modelCompany := new(companymodel.Company)
		if err := obj.mySqlApi.GetDb().Model(modelCompany).Where("domain_name=?", dataModel.DomainName).First(modelCompany).Error; err != nil {
			return err
		}

		//将数据添加到数据库
		modelUser.CompanyID = modelCompany.ID
		//modelUser.ItemID = modelCompany.
		modelUser.UserType = 2 //小程序登录
		modelUser.OpenID = dataModel.OpenID
		if err := obj.userApi.AddUserByOpenId(modelUser); err != nil {
			return err
		}

		//组织返回数据
		dataModel.CompanyID = modelCompany.ID
		dataModel.UserType = modelUser.UserType
		dataModel.ID = modelUser.ID
	}

	//生成token
	uuid := util.GenerateUuid()
	token := "mtoken" + strconv.Itoa(int(modelUser.ID)) + "-" + uuid
	dataModel.Token = token

	//将用户数据保存到redis中
	redisModel := new(redismodel.RedisUserMobile)
	redisModel.CompanyID = modelUser.CompanyID
	redisModel.UserType = modelUser.UserType
	redisModel.UserID = modelUser.ID
	redisModel.Nickname = modelUser.Nickname
	redisModel.Token = token
	redisModel.TokenTime = time.Now().Format("2006-01-02 15:16:17")

	//以token为键，将用户信息保存到redis中，token过期时间为60分钟
	if err := obj.redisApi.SetModelData(token, redisModel, 60); err != nil {
		return err
	}

	return nil
}
