package svc

import (
	"applet/app/db"
	"applet/app/md"
	"errors"
	"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
}
