package admin

import (
	"common/mytime"
	"common/remark"
	"common/resultStatus"
	"common/webServer"
	"goutil/intUtil"
	"goutil/securityUtil"
	"strconv"
	"time"
)

func init() {

	//注册接口
	webServer.RegisterFunction(new(AdminApi))
}

func init() {
	moduleName := "AdminApi"
	desc := "管理员接口"
	author := "tangping"
	mendor := ""
	date := "2024-12-25"
	remark.RegisterModuleRemark(moduleName, desc, author, mendor, date)
}

// AdminApi 管理员接口
type AdminApi struct {
}

// ---------------------------------------- 接口 --------------------------------------------------
func init() {
	moduleName := "AdminApi"
	methodName := "Add"
	skipVerifyTokenPage := true
	methodDesc := "添加管理员用户"
	methodAuthor := "tangping"
	methodMendor := ""
	methodDate := "2024-12-25 15:55:00"
	methodInParam := []string{"string 账号,string:管理员名称,string:管理员密码,string:管理员性别,string:管理员生日,int64:管理员手机号,string:管理员邮箱,string:管理员微信群,string:管理员备注"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"id '类型:int'": "管理员id",
		}
	}`
	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}
func (a *AdminApi) Add(account string, name string, password string, sex int32, birthday string, phone int64, email string, wechatGroup string, describe string) (responseObj *webServer.ResponseObject) {
	responseObj = webServer.GetInitResponseObj()

	//校验参数
	if account == "" || name == "" || password == "" || sex == 0 || birthday == "" || phone == 0 || email == "" || wechatGroup == "" {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}

	//密码md5加密
	password = securityUtil.Md5String(password, true)

	//处理数据
	adminModel := &Admin{
		Account:     account,
		Name:        name,
		Password:    password,
		Sex:         sex,
		Birthday:    birthday,
		Phone:       phone,
		Email:       email,
		WechatGroup: wechatGroup,
		Describe:    describe,
	}

	//添加到数据库
	AddAdmin(adminModel)

	resultMap := make(map[string]any)
	resultMap["id"] = adminModel.ID
	responseObj.SetData(resultMap)
	return
}

func init() {
	moduleName := "AdminApi"
	methodName := "Get"
	skipVerifyTokenPage := false
	methodDesc := "获取管理员用户"
	methodAuthor := "tangping"
	methodMendor := ""
	methodDate := "2024-12-25 15:55:00"
	methodInParam := []string{"int64:管理员id"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"account '类型:string'": "管理员账号",
			"name '类型:string'": "管理员名称",
			"sex '类型:int32'": "管理员性别",
			"birthday '类型:string'": "管理员生日",
			"phone '类型:int64'": "管理员手机号",
			"email '类型:string'": "管理员邮箱",
			"wechatGroup '类型:string'": "管理员微信群",
			"describe '类型:string'": "管理员备注",
		}
	}`

	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}
func (a *AdminApi) Get(useAdmin *Admin, adminId int64) (responseObj *webServer.ResponseObject) {

	responseObj = webServer.GetInitResponseObj()

	//获取当前登录用户信息

	//验证参数
	if adminId == 0 {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}

	adminData, err := GetAdminByID(adminId)
	if err != nil {
		responseObj.SetResultStatus(resultStatus.DataError)
		return
	}

	//adminData映射成map
	resultMap := make(map[string]any)
	resultMap["account"] = adminData.Account
	resultMap["name"] = adminData.Name
	resultMap["sex"] = adminData.Sex
	resultMap["birthday"] = adminData.Birthday
	resultMap["phone"] = adminData.Phone
	resultMap["email"] = adminData.Email
	resultMap["wechatGroup"] = adminData.WechatGroup
	resultMap["describe"] = adminData.Describe

	responseObj.SetData(resultMap)
	return
}

// 管理员登录
func init() {
	moduleName := "AdminApi"
	methodName := "Login"
	skipVerifyTokenPage := true
	methodDesc := "管理员登录"
	methodAuthor := "tangping"
	methodMendor := ""
	methodDate := "2024-12-26 15:55:00"
	methodInParam := []string{"string:账号,string:密码"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"Token '类型:string'": "登录令牌",
		}
	}`

	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}

func (a *AdminApi) Login(account string, password string) (responseObj *webServer.ResponseObject) {

	responseObj = webServer.GetInitResponseObj()

	//验证参数
	if account == "" || password == "" {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}

	adminData, err := Login(account, securityUtil.Md5String(password, true))
	if err != nil {
		responseObj.SetResultStatus(resultStatus.DataError)
		return
	}

	//生成一个随机token
	token, err := intUtil.ShuffleIntDigits(time.Now().UnixNano())
	if err != nil {
		responseObj.SetResultStatus(resultStatus.DataError)
		return
	}

	//添加登录用户
	webServer.AddLoginUserToken(token, &webServer.TokenInfo{Id: adminData.ID, Account: account, UserInfo: adminData})

	//adminData映射成map
	resultMap := make(map[string]any)
	resultMap["Token"] = strconv.FormatInt(token, 10)

	responseObj.SetData(resultMap)
	return
}

// 获取某一天玩家的平均在线时长
func init() {
	moduleName := "AdminApi"
	methodName := "GetAveragePlaytimes"
	skipVerifyTokenPage := true
	methodDesc := "获取某一天玩家的平均在线时长"
	methodAuthor := "youjinlan"
	methodMendor := ""
	methodDate := "2025-01-21 16:00:00"
	methodInParam := []string{"int64 startTime, int64 endTime"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"AveragePlaytimesForEachSever '类型:map[int32]map[int64]int64'": "各个服在该时间段内的各天平均在线时长",
		}
	}`
	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}

func (a *AdminApi) GetAveragePlaytimes(startTime, endTime int64) (responseObj *webServer.ResponseObject) {
	responseObj = webServer.GetInitResponseObj()
	//验证参数
	nowTime := time.Now().Unix()
	nowZero := mytime.ZeroTime(nowTime, 0)
	if startTime == 0 || endTime == 0 {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}
	if startTime > nowTime {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}
	startZero := mytime.ZeroTime(startTime, 0)
	endZero := mytime.ZeroTime(endTime, 0)
	if endZero > nowZero {
		endZero = nowZero
	}
	//GetAveragePlaytimes()
	totalMap := make(map[int32]map[int64]int64)
	userSeverList, _ := GetUserSeverList()
	date := startZero
	for _, severlist := range userSeverList {
		dateMap := make(map[int64]int64)
		for {
			var averagePlaytimes int64
			if date != mytime.ZeroTime(nowTime, 0) {
				averagePlaytimes, _, _ = GetRecordAveragePlayTimes(date, severlist.SeverId)
				if averagePlaytimes == 0 {
					playtimes := GetUserTotalPlayTimes(date, severlist.SeverId)
					count := GetUserTotalPlayerNum(date, severlist.SeverId)
					if playtimes == 0 || count == 0 {
						averagePlaytimes = 0
					} else {
						averagePlaytimes = playtimes / count
					}
					//把今日之前的数据添加到数据库，因为数据不会再变化了，下次查询就不用计算了
					recordAveragePlayTimes := &RecordAveragePlayTimes{}
					recordAveragePlayTimes.AveragePlayTimes = averagePlaytimes
					recordAveragePlayTimes.PlayerNum = count
					recordAveragePlayTimes.SeverId = severlist.SeverId
					recordAveragePlayTimes.RecordDate = date
					AddRecordAveragePlayTimes(recordAveragePlayTimes)
				}
			} else {
				playtimes := GetUserTotalPlayTimes(date, severlist.SeverId)
				count := GetUserTotalPlayerNum(date, severlist.SeverId)
				if playtimes == 0 || count == 0 {
					averagePlaytimes = 0
				} else {
					averagePlaytimes = playtimes / count
				}
			}
			dateMap[date] = averagePlaytimes
			if date+86400 > endZero {
				date = startZero
				break
			}
			date = date + 86400
		}
		totalMap[severlist.SeverId] = dateMap
	}
	resultMap := make(map[string]any)
	resultMap["AveragePlaytimesForEachSever"] = totalMap
	responseObj.SetData(resultMap)
	return
}

// 获取某一天玩家的平均看广告次数
func init() {
	moduleName := "AdminApi"
	methodName := "GetAverageWatchADNum"
	skipVerifyTokenPage := true
	methodDesc := "获取某一天玩家的平均看广告次数"
	methodAuthor := "youjinlan"
	methodMendor := ""
	methodDate := "2025-01-24 15:00:00"
	methodInParam := []string{"int64 startTime, int64 endTime"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"AverageWatchADNumForEachSever '类型:map[int32]map[int64]int32'": "各个服在该时间段内的各天平均看广告次数",
		}
	}`
	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}

func (a *AdminApi) GetAverageWatchADNum(startTime, endTime int64) (responseObj *webServer.ResponseObject) {
	responseObj = webServer.GetInitResponseObj()
	//验证参数
	nowTime := time.Now().Unix()
	nowZero := mytime.ZeroTime(nowTime, 0)
	if startTime == 0 || endTime == 0 {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}
	if startTime > nowTime {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}
	startZero := mytime.ZeroTime(startTime, 0)
	endZero := mytime.ZeroTime(endTime, 0)
	if endZero > nowZero {
		endZero = nowZero
	}
	//GetAveragePlaytimes()
	totalMap := make(map[int32]map[int64]float32)
	userSeverList, _ := GetUserSeverList()
	date := startZero
	for _, severlist := range userSeverList {
		dateMap := make(map[int64]float32)
		for {
			if date != mytime.ZeroTime(nowTime, 0) {
				avgWatchADNum, _, _ := GetRecordAverageWatchADNum(date, severlist.SeverId)
				if avgWatchADNum == 0 {
					avgWatchADNum = GetUserAvgWatchADNum(date, severlist.SeverId)
					count := GetUserWatchADPlayerNum(date, severlist.SeverId)
					//把今日之前的数据添加到数据库，因为数据不会再变化了，下次查询就不用计算了
					recordAverageWatchADNum := &RecordAverageWatchADNum{}
					recordAverageWatchADNum.AverageWatchADNum = avgWatchADNum
					recordAverageWatchADNum.PlayerNum = count
					recordAverageWatchADNum.SeverId = severlist.SeverId
					recordAverageWatchADNum.RecordDate = date
					AddRecordAverageWatchADNum(recordAverageWatchADNum)
				}
			} else {
				avgWatchADNum := GetUserAvgWatchADNum(date, severlist.SeverId)
				dateMap[date] = avgWatchADNum
				if date+86400 > endZero {
					date = startZero
					break
				}
				date = date + 86400
			}
		}
		totalMap[severlist.SeverId] = dateMap
	}
	resultMap := make(map[string]any)
	resultMap["AverageWatchADNumForEachSever"] = totalMap
	responseObj.SetData(resultMap)
	return
}

// 获取某个玩家的生命周期
func init() {
	moduleName := "AdminApi"
	methodName := "GetPlayerLiveNum"
	skipVerifyTokenPage := true
	methodDesc := "获取某个玩家的生命周期"
	methodAuthor := "youjinlan"
	methodMendor := ""
	methodDate := "2025-01-24 17:00:00"
	methodInParam := []string{"int64 uid"}
	methodOutParam := `
	{
		"Code '类型:int'": "响应结果的状态值",
		"Message '类型:string'": "响应结果的状态值所对应的描述信息",
		"Data '类型:interface{}'": "响应结果的数据"
		{
			"LiveNum '类型:int32'": "玩家的生命周期(玩了多少天)",
		}
	}`
	remark.RegisterMethodRemark(moduleName, methodName, methodDesc, methodAuthor, methodMendor, methodDate, methodInParam, methodOutParam, skipVerifyTokenPage)
}

func (a *AdminApi) GetPlayerLiveNum(uid int64) (responseObj *webServer.ResponseObject) {
	responseObj = webServer.GetInitResponseObj()
	if uid == 0 {
		responseObj.SetResultStatus(resultStatus.APIDataError)
		return
	}
	var userRecord *RecordLoginOfWxUser
	if userRecord, _ = GetUserFirstRecord(uid); userRecord == nil {
		responseObj.SetResultStatus(resultStatus.PlayerNotExist)
		return
	}
	firstDate := userRecord.RecordDate
	userRecord, _ = GetUserLastRecord(uid)
	lastDate := userRecord.RecordDate
	resultMap := make(map[string]any)
	liveNum := mytime.DiffDays(lastDate, firstDate)
	resultMap["LiveNum"] = liveNum
	responseObj.SetData(resultMap)
	return
}
