package v1

import (
	"context"
	"designs/app/common/request"
	"designs/app/common/response"
	"designs/global"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

// 总览，返回当天的 接口访问总数，登录人数，新增用户数
func Overview(c *gin.Context) {
	form := request.Check(c, &struct {
		Day string `form:"day" json:"day" binding:"required"`
	}{})
	//查询接口访问次数
	dayCount, err := global.App.Redis.Get(context.Background(), "dayLog:"+form.Day).Result()
	if err != nil {
		global.App.Log.Error("redis incr error", "err", err)
	}
	dayLoginLog, err := global.App.Redis.Get(context.Background(), "dayLog:"+form.Day).Result()
	if err != nil {
		global.App.Log.Error("redis get error", "err", err)
	}
	//查询新注册人数
	dayRegisterLog, err := global.App.Redis.Get(context.Background(), "registerDayLog:"+form.Day).Result()
	if err != nil {
		global.App.Log.Error("redis get error", "err", err)
	}

	response.Success(c, gin.H{
		"data": map[string]interface{}{
			"dayCount":       dayCount,
			"dayLoginLog":    dayLoginLog,
			"dayRegisterLog": dayRegisterLog,
		},
	})
}

// 获取指定接口的请求次数 （小时的， 天的）
// 后期还可以根据游戏，平台 ，甚至用户等参数，去获取接口访问的频率
func GetInterfaceLog(c *gin.Context) {
	form := request.Check(c, &struct {
		Day       string `form:"day" json:"day" binding:""`
		Hour      string `form:"hour" json:"hour" binding:""`
		Interface string `form:"interface" json:"interface" binding:"required"`
		Pf        string `form:"pf" json:"pf" binding:""`
		Gid       string `form:"gid" json:"gid" binding:""`
	}{})

	if form.Hour == "" && form.Day == "" {
		response.Fail(c, 1003, "day ，和hour 参数必须选一个传")
	}
	var key string
	if form.Day != "" {
		key = "dayLog:"
	} else if form.Hour != "" {
		key = "hourInterfaceLog:"
	}

	if form.Pf != "" && form.Gid != "" {
		key = key + form.Gid + ":" + form.Pf
	}
	key = key + ":" + form.Interface

	if form.Day != "" {
		key = key + ":" + form.Day
	} else if form.Hour != "" {
		key = key + ":" + form.Hour
	}

	//查询新注册人数
	res, err := global.App.Redis.Get(context.Background(), key).Result()
	if err != nil {
		global.App.Log.Error("redis get error", "err", err)
	}

	response.Success(c, gin.H{
		"data": res,
	})
}

// 获取所有的接口，以及接口的名字
func GetInterfaceInfo(c *gin.Context) {
	response.Success(c, gin.H{
		"data": []struct {
			Name string `json:"name"`
			Path string `json:"path"`
		}{
			{Name: "登录", Path: "/v1/user/login"},
			{Name: "刷新", Path: "/v1/user/refreshToken"},
			{Name: "添加游戏配置", Path: "/v1/user/addGidConfig"},
			{Name: "查看游戏配置", Path: "/v1/user/getGidConfig"},
			{Name: "查看系统时间", Path: "/v1/user/getSysTime"},
			{Name: "获取用户数据", Path: "/v1/user/getUserData"},
			{Name: "设置游戏数据", Path: "/v1/user/setGameData"},
			{Name: "获取游戏数据", Path: "/v1/user/getGameData"},
			{Name: "更新用户信息", Path: "/v1/user/updateUserInfo"},
			{Name: "设置排行数据", Path: "/v1/user/SetRankData"},
			{Name: "获取排行数据", Path: "/v1/user/getRankData"},
			{Name: "设置省内排行数据", Path: "/v1/user/setProvinceRankData"},
			{Name: "获取省内排行数据", Path: "/v1/user/getProvinceRankData"},
			{Name: "更新用户位置数据", Path: "/v1/user/getProvinceRankSumData"},
			{Name: "获取省内排行总榜数据", Path: "/v1/user/updateUserlocation"},
		},
	})
}

// 获取某一日内，接口每个小时的访问数
func GetInterfaceData(c *gin.Context) {
	form := request.Check(c, &struct {
		Day       string `form:"day" json:"day" binding:""`
		Interface string `form:"interface" json:"interface" binding:"required"`
		Pf        string `form:"pf" json:"pf" binding:""`
		Gid       string `form:"gid" json:"gid" binding:""`
	}{})

	type hourDara struct {
		Hour int `json:"hour"`
		Data int `json:"data"`
	}

	var res []hourDara
	for i := 1; i <= 24; i++ {
		key := "hourInterfaceLog:" + form.Interface + ":" + form.Day + strconv.Itoa(i)
		if form.Pf != "" && form.Gid != "" {
			key = "hourInterfaceLog:" + form.Gid + ":" + form.Pf + ":" + form.Interface + ":" + form.Day + strconv.Itoa(i)
		}

		data, err := global.App.Redis.Get(context.Background(), key).Result()
		if err != nil {
			global.App.Log.Error("redis get error", "err", err)
		}
		dataInt, _ := strconv.Atoi(data)
		res = append(res, hourDara{
			Hour: i,
			Data: dataInt,
		})
	}

	response.Success(c, gin.H{
		"data": res,
	})

}

// 获取某一区间内，接口每天的访问数
func GetInterfaceDataByDay(c *gin.Context) {
	form := request.Check(c, &struct {
		Start     string `form:"start" json:"start" binding:""`
		End       string `form:"end" json:"end" binding:""`
		Interface string `form:"interface" json:"interface" binding:"required"`
		Pf        string `form:"pf" json:"pf" binding:""`
		Gid       string `form:"gid" json:"gid" binding:""`
	}{})

	dayRange, err := GenerateDaysBetween(form.Start, form.End)
	if err != nil {
		response.Fail(c, 1003, err.Error())
		return
	}

	type dayData struct {
		Day  string `json:"day"`
		Data int    `json:"data"`
	}
	var res []dayData
	for _, v := range dayRange {
		key := "dayLog:" + form.Interface + ":" + v

		if form.Pf != "" && form.Gid != "" {
			key = "dayLog:" + form.Gid + ":" + form.Pf + ":" + form.Interface + ":" + v
		}

		data, err := global.App.Redis.Get(context.Background(), key).Result()
		if err != nil {
			global.App.Log.Error("redis get error", "err", err)
		}
		dataInt, _ := strconv.Atoi(data)
		res = append(res, dayData{
			Day:  v,
			Data: dataInt,
		})
	}

	response.Success(c, gin.H{
		"data": res,
	})

}

func GenerateDaysBetween(startDate, endDate string) ([]string, error) {
	start, err := time.Parse("20060102", startDate)
	if err != nil {
		return nil, err
	}
	end, err := time.Parse("20060102", endDate)
	if err != nil {
		return nil, err
	}

	var days []time.Time
	for curr := start; !curr.After(end); curr = curr.AddDate(0, 0, 1) {
		days = append(days, curr)
	}

	var res []string
	for _, v := range days {
		res = append(res, v.Format("20060102"))
	}

	return res, nil
}
