package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/md"
	"applet/app/utils"
	"applet/app/utils/cache"
	"applet/app/utils/logx"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
)

// GetDefaultUser is 获取默认账号，uid =0 为系统默认账号，用于一些请求需要渠道id之类的东西
func GetDefaultUser(c *gin.Context, token string) (*md.User, error) {
	user := new(md.User)
	if c.GetString("convert_url") == "1" { //转链接口
		goto DEFALUT
	} else {
		// Token 不为空时拿对应的用户数据
		if token != "" && strings.Contains(token, "Bearer") {

			user, err := CheckUser(c)
			if user == nil {
				return nil, errors.New("token is expired")
			}
			if err != nil {
				// 有报错自己拿默认用户
				goto DEFALUT
			}
			return user, nil
		}
	}

DEFALUT:
	// 默认拿uid 等于0的用户数据
	profile, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], 0)
	if err != nil {
		return nil, err
	}
	info, err := db.UserFindByID(db.DBs[c.GetString("mid")], 0)
	if err != nil {
		return nil, err
	}
	ul, err := db.UserLevelInIDescByWeightLowWithOne(db.DBs[c.GetString("mid")])
	if err != nil {
		return nil, err
	}
	user.Info = info
	user.Profile = profile
	user.Level = ul
	return user, nil
}

func FastLoginUserExist(c *gin.Context, r *md.LoginResponse, requestBody *md.FastLoginRequestBody) error {
	// 每次登录都会刷新token
	var user = &model.User{}
	var err error
	if requestBody.Mobile != "" {
		user, err = db.UserFindByMobileAll(db.DBs[c.GetString("mid")], requestBody.Mobile)
	}
	if user == nil || user.Uid == 0 {
		return e.NewErr(400, "用户不存在")
	}
	if err != nil {
		return err
	}
	if user.DeleteAt == 1 {
		return e.NewErr(403053, "账号被删除,如有疑问请联系客服")
	}
	//判断用户是否虚拟账号 虚拟账号不能用手机号登陆
	if user.IsFake == 1 {
		return e.NewErr(400000, "该手机号无法登陆，请联系客服！")
	}
	//0未激活,1正常,2冻结
	switch user.State {
	case 0:
		return e.NewErr(403028, "no active")
	case 2:
		return e.NewErr(403029, "您的账号已被冻结")
	}
	// 生成jwt
	appName := db.SysCfgGet(c, "app_name")
	profile, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], user.Uid)
	if err != nil || profile == nil {
		_ = logx.Warn(err)
		return e.NewErr(400000, "数据不完整")
	}
	token := CheckUserToken(c, user, appName)
	r.Token = token
	r.UserID = utils.IntToStr(user.Uid)
	r.UserName = requestBody.Mobile
	r.Phone = requestBody.Mobile
	// 更新
	profile.ArkidToken = token
	_, err = db.UserProfileUpdate(db.DBs[c.GetString("mid")], user.Uid, profile)
	if err != nil {
		return logx.Warn(err)
	}
	// 写入缓存
	key := fmt.Sprintf("%s:token:%s", c.GetString("mid"), user.Username)
	_, err = cache.SetEx(key, token, 39528000) // 半年
	if err != nil {
		return logx.Warn(err)
	}
	return nil
}
func CheckUserToken(c *gin.Context, user *model.User, appName string) string {
	profile, err := db.UserProfileFindByID(db.DBs[c.GetString("mid")], user.Uid)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err)
		return ""
	}
	token := profile.ArkidToken
	_, err = utils.ParseToken(token)
	if err != nil {
		token, _ = utils.GenToken(user.Uid, user.Username, user.Phone, appName, "", "")
		// 更新
		profile.ArkidToken = token
		_, err = db.UserProfileUpdate(db.DBs[c.GetString("mid")], user.Uid, profile)
		// 写入缓存
		key := fmt.Sprintf("%s:token:%s", c.GetString("mid"), user.Username)
		_, err = cache.SetEx(key, token, 39528000) // 半年
	}
	return token
}
