package log

import (
	"encoding/json"
	"go.uber.org/zap"
	"log-server/global"
	"log-server/model/log"
	"log-server/model/log/request"
	"log-server/model/log/response"
	"time"
)

type ServiceReportPointsLog struct {
}

func (s *ServiceReportPointsLog) CreateReportPointsLog(reportPointsLog *log.ReportPointsLog) (err error) {
	return global.GVA_DB.Create(&reportPointsLog).Error
}

func (s *ServiceReportPointsLog) GetReportPointsLogList(api log.ReportPointsLog, info request.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&log.ReportPointsLog{})
	var apiList []log.ReportPointsLog
	var createDate string
	if api.CreateDate == "" {
		createDate = time.Now().Format("2006-01-02")
	} else {
		createDate = api.CreateDate
	}
	db = db.Where("create_date = ?", createDate)
	if api.GameId != 0 {
		db = db.Where("game_id = ?", api.GameId)
	}
	if api.Account != "" {
		db = db.Where("account = ?", api.Account)
	}
	if api.LogUuid != "" {
		db = db.Where("log_uuid = ?", api.LogUuid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return apiList, total, err
	} else {
		db = db.Limit(limit).Offset(offset)
		if order != "" {
			var OrderStr string
			// 设置有效排序key 防止sql注入
			// 感谢 Tom4t0 提交漏洞信息
			orderMap := make(map[string]bool, 4)
			orderMap["id"] = true
			orderMap["log_uuid"] = true
			orderMap["account"] = true
			if orderMap[order] {
				if desc {
					OrderStr = order + " desc"
				} else {
					OrderStr = order
				}
			} else { // didn't matched any order key in `orderMap`
				global.GVA_LOG.Error("获取失败!", zap.Error(err))
				return apiList, total, err
			}

			err = db.Order(OrderStr).Find(&apiList).Error
		} else {
			err = db.Order("id").Find(&apiList).Error
		}
	}

	var apisReply []*response.GetReportPointsReply
	var reportPointsData []request.ReportPointsData
	if total != 0 {
		for _, apiInfo := range apiList {
			apiReply := new(response.GetReportPointsReply)
			apiReply.Id = apiInfo.Id
			apiReply.GameId = apiInfo.GameId
			apiReply.Status = apiInfo.Status
			apiReply.Account = apiInfo.Account
			apiReply.ReportPointsNum = apiInfo.ReportPointsNum
			_ = json.Unmarshal([]byte(apiInfo.ReportPointsData), &reportPointsData)
			apiReply.ReportPointsData = reportPointsData
			apiReply.LogUuid = apiInfo.LogUuid
			apiReply.CreateDate = apiInfo.CreateDate
			apiReply.CreateTime = apiInfo.CreateTime
			apisReply = append(apisReply, apiReply)
		}
	}
	return apisReply, total, err
}
