package v1

import (
	"context"
	"designs/app/common/request"
	"designs/app/common/response"
	"designs/common"
	"designs/config"
	"designs/global"
	"designs/model"
	"designs/service"
	"designs/utils"
	"fmt"
	"github.com/go-redis/redis/v8"
	"go.mongodb.org/mongo-driver/v2/bson"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type GameConfig struct {
	Gid       string `form:"gid" json:"gid" binding:"required"`             //游戏id
	Pid       string `form:"pid" json:"pid" binding:""`                     //游戏pid
	GameName  string `form:"gameName" json:"gameName" binding:"required"`   //游戏名称
	WxAppid   string `form:"wxAppid" json:"wxAppid" binding:"required"`     //微信appid
	WxSecret  string `form:"wxSecret" json:"wxSecret" binding:"required"`   //微信secret
	TtAppid   string `form:"ttAppid" json:"ttAppid" binding:"required"`     //抖音appid
	TtSecret  string `form:"ttSecret" json:"ttSecret" binding:"required"`   //抖音secret
	AppSecret string `form:"appSecret" json:"appSecret" binding:"required"` //游戏配置密钥
	TtTplId   string `form:"ttTplId" json:"ttTplId" binding:""`
	WxTplId   string `form:"wxTplId" json:"wxTplId" binding:""`

	ConfigPath string `form:"configPath" json:"configPath" binding:""`
}

type GetGameCfg struct {
	AppSecret string `form:"appSecret" json:"appSecret" binding:"required"` //游戏配置密钥
}

/* code 结构体 */
type CodeData struct {
	Code string `form:"code" json:"code" binding:"required"`
	Gid  string `form:"gid" json:"gid" binding:"required"`
	Pf   string `form:"pf" json:"pf" binding:"required"`
}

/* 保存数据结构体 */
type SaveData struct {
	Extend string `form:"extend" json:"extend" binding:"required"`
	Data   string `form:"data" json:"data" binding:"required"`
	Secret string `form:"secret" json:"secret" binding:""`
}

/* 获取结构体 */
type GetSaveData struct {
	Extend string `form:"extend" json:"extend" binding:"required"`
}

/*
*登陆
 */
func Login(c *gin.Context) {
	//http://127.0.0.1:8787/v1/user/login
	// 使用 ShouldBind 方法自动绑定：
	form := request.Check(c, &struct {
		UserName string `form:"userName" json:"userName" binding:"required"`
		Password string `form:"password" json:"password" binding:"required"`
	}{})

	//验证
	var admin model.Admin
	global.App.DB.Table("admin").Where("account", form.UserName).First(&admin)
	if admin.Password != "" && admin.Password != form.Password {
		response.Fail(c, 1003, "账户密码错误")
		return
	}

	var isSuper bool
	if admin.ID == 1 {
		isSuper = true
	}

	//获取token
	token, err := common.GetJwtToken(form.UserName, 0)
	//刷新refreshtoken
	refresh, _ := common.GetJwtToken(form.UserName, 1)
	if err != nil {
		response.Fail(c, 1003, err.Error())
		return
	}

	//回传
	response.Success(c, gin.H{
		"token":        token,
		"refreshToken": refresh,
		"isSuper":      isSuper,
		"loginTime":    time.Now().Unix(),
		"ip":           c.ClientIP(),
	})
}

/* 刷新token */
func RefreshToken(c *gin.Context) {
	userName := c.GetString("userName")

	//获取token
	token, err0 := common.GetJwtToken(userName, 0)
	if err0 != nil {
		global.App.Log.Info("RefreshToken err")
		response.Fail(c, 1003, "RefreshToken err")
		return
	}

	data := map[string]interface{}{
		"token": token,
	}
	//返回数据
	response.Success(c, gin.H{
		"data": data,
	})
}

/* 获取时间 */
func GetSysTime(c *gin.Context) {
	time := time.Now().Unix()
	common.RetJson(0, "获取系统时间", time, c)
}

type User struct {
	UserId   string `json:"userId"`
	Gid      string `json:"gid"`
	Pf       string `json:"pf"`
	NickName string `json:"nickName"`
	Head     string `json:"head"`
	OpenId   string `json:"openId"`
	InBlack  bool   `json:"inBlack"`
	Option   string `json:"option"`
}

func UserList(c *gin.Context) {
	form := request.Check(c, &struct {
		Gid    string `form:"gid" json:"gid" binding:""`
		Pf     string `form:"pf" json:"pf" binding:""`
		Search string `form:"search" json:"search" binding:""`
		Offset int    `form:"offset" json:"offset" binding:""`
		Limit  int    `form:"limit" json:"limit" binding:"required"`
	}{})

	var res []User
	//读取表
	userTotalKey := config.Get("app.user_total")
	if form.Gid != "" && form.Pf != "" {
		userTotalKey = config.Get("app.user_total") + ":" + form.Gid + ":" + form.Pf
	}

	//读取黑名单
	blackListKey := config.Get("app.black_list_table")
	black, err := global.App.Redis.ZRange(context.Background(), blackListKey, 0, -1).Result()
	if err != nil {
		response.Fail(c, 1003, "读取黑名单列表失败"+err.Error())
		return
	}

	var data []redis.Z
	if form.Search != "" {
		data, _ = global.App.Redis.ZRevRangeWithScores(context.Background(), userTotalKey, 0, 1000000).Result()

		//读取出所有的数据，然后过滤nickname
		for _, val := range data {
			userKey := val.Member.(string)
			userData, err := global.App.Redis.HGetAll(context.Background(), userKey).Result()
			if err != nil {
				global.App.Log.Error("GetUserData err")
				response.Fail(c, 1003, "GetUserData err"+err.Error())
				return
			}

			userMsg := strings.Split(userKey, ":")
			openId := userMsg[len(userMsg)-1]
			gid := userMsg[0]
			pf := userMsg[1]

			if userData["nickname"] == form.Search || openId == form.Search {

				//查看是否在黑名单
				var inBlack bool
				if utils.InArray(userKey, black) {
					inBlack = true
				}

				//查看是否加了权限
				optionKey := config.Get("app.option_key") + gid + ":" + pf + ":" + openId
				option, err := global.App.Redis.HGetAll(context.Background(), optionKey).Result()
				if err != nil {
					response.Fail(c, 1003, err.Error())
					return
				}

				res = append(res, User{
					UserId:   userData["userId"],
					Gid:      userData["gid"],
					Pf:       userData["pf"],
					NickName: userData["nickName"],
					Head:     userData["head"],
					OpenId:   openId,
					InBlack:  inBlack,
					Option:   option["option"],
				})
			}

		}

		response.Success(c, gin.H{
			"data":  res,
			"count": len(res),
		})
		return
	} else {
		data, _ = global.App.Redis.ZRevRangeWithScores(context.Background(), userTotalKey, int64(form.Offset), int64(form.Offset+form.Limit)-1).Result()

	}

	count, err := global.App.Redis.ZCard(context.Background(), userTotalKey).Result()
	if err != nil {
		response.Fail(c, 1001, err.Error())
		return
	}

	for _, val := range data {
		userKey := val.Member.(string)
		userData, err := global.App.Redis.HGetAll(context.Background(), userKey).Result()
		if err != nil {
			global.App.Log.Error("GetUserData err")
			response.Fail(c, 1003, "GetUserData err"+err.Error())
			return
		}

		//查看是否在黑名单
		var inBlack bool
		if utils.InArray(userKey, black) {
			inBlack = true
		}

		userMsg := strings.Split(userKey, ":")
		openId := userMsg[len(userMsg)-1]
		gid := userMsg[0]
		pf := userMsg[1]

		//查看是否加了权限
		optionKey := config.Get("app.option_key") + gid + ":" + pf + ":" + openId
		option, err := global.App.Redis.HGetAll(context.Background(), optionKey).Result()
		if err != nil {
			response.Fail(c, 1003, err.Error())
			return
		}

		res = append(res, User{
			UserId:   userData["userId"],
			Gid:      userData["gid"],
			Pf:       userData["pf"],
			NickName: userData["nickName"],
			Head:     userData["head"],
			OpenId:   openId,
			InBlack:  inBlack,
			Option:   option["option"],
		})
	}

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

func GetUserOnlineMsg(c *gin.Context) {
	form := request.Check(c, &struct {
		Gid       string `form:"gid" json:"gid" binding:"required"`
		Pf        string `form:"pf" json:"pf" binding:"required"`
		Date      string `form:"date" json:"data" binding:""`
		StartTime string `form:"startTime" json:"startTime" binding:""`
		EndTime   string `form:"endTime" json:"endTime" binding:""`
	}{})

	res, err := service.UserOnlineSummary(form.Gid, form.Pf, form.Date, form.StartTime, form.EndTime)
	if err != nil {
		response.Fail(c, 1001, err.Error())
		return
	}

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

func UserBehaviorList(c *gin.Context) {
	//form := request.Check(c, &struct {
	//	Gid    string `form:"gid" json:"gid" binding:"required"`
	//	Pf     string `form:"pf" json:"pf" binding:"required"`
	//	Cid    string `form:"cid" json:"cid" binding:""`
	//	Order  string `form:"order" json:"order" binding:""`
	//	Search string `form:"search" json:"search" binding:""`
	//}{})

	collection := global.App.MongoDB.Database("testing").Collection("numbers")
	res, _ := collection.InsertOne(context.Background(), bson.D{{"name", "pi"}, {"value", 3.14159}})
	fmt.Println(res)

}

func DownloadFile(c *gin.Context) {
	filename := c.Param("filename")

	// 验证文件是否存在
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		c.JSON(404, gin.H{"error": "文件不存在"})
		return
	}

	// 设置响应头，触发浏览器下载行为
	c.Header("Content-Disposition", "attachment; filename="+filename)
	c.Header("Content-Type", "application/octet-stream")
	c.File(filename)
}

// 上传图片到服务器
func Upload(c *gin.Context) {
	// 获取文件
	file, err := c.FormFile("file")
	if err != nil {
		response.Fail(c, 400, "未选择文件")
		return
	}

	// 存储路径生成
	saveDir := fmt.Sprintf("uploads/%s", time.Now().Format("2006-01-02"))

	os.MkdirAll(saveDir, 0755)

	savePath := filepath.Join(saveDir, file.Filename)

	// 保存文件
	if err := c.SaveUploadedFile(file, savePath); err != nil {
		response.Fail(c, 500, "文件保存失败")
		return
	}

	response.Success(c, gin.H{
		"path": savePath,
	})
}
