package controllers

import (
	"aon_app_server/models"
	"aon_app_server/utils/mongo"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"net/http"
)

type LogController struct {
	MainController
}

func (server *LogController) Report() {
	body := server.Ctx.Input.RequestBody
	log := models.Log{}
	err := json.Unmarshal(body, &log) //解析body中数据
	logs.Debug("appRequest", log, string(body))
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	header := server.Ctx.Request.Header
	platform := header.Get("Sec-Ch-Ua-Platform")
	if log.Platform == "" && platform != "" {
		log.Platform = platform
	}
	userAgent := header.Get("User-Agent")
	if log.UserAgent == "" && userAgent != "" {
		log.UserAgent = userAgent
	}
	isMobile := header.Get("Sec-Ch-Ua-Mobile")
	if log.IsMobile == "" && isMobile != "" {
		log.IsMobile = isMobile
	}
	secUa := header.Get("Sec-Ch-Ua")
	if log.SecUa == "" && secUa != "" {
		log.SecUa = secUa
	}
	_, err = mongo.Insert(&log)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "")
}

func (server *LogController) BatchReport() {
	body := server.Ctx.Input.RequestBody
	var data []models.Log
	err := json.Unmarshal(body, &data) //解析body中数据
	logs.Debug("appRequest", data)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	header := server.Ctx.Request.Header
	for _, log := range data {
		platform := header.Get("Sec-Ch-Ua-Platform")
		if log.Platform == "" && platform != "" {
			log.Platform = platform
		}
		userAgent := header.Get("User-Agent")
		if log.UserAgent == "" && userAgent != "" {
			log.UserAgent = userAgent
		}
		isMobile := header.Get("Sec-Ch-Ua-Mobile")
		if log.IsMobile == "" && isMobile != "" {
			log.IsMobile = isMobile
		}
		secUa := header.Get("Sec-Ch-Ua")
		if log.SecUa == "" && secUa != "" {
			log.SecUa = secUa
		}
	}

	var interfaceSlice []interface{} = make([]interface{}, len(data))
	for i, v := range data {
		interfaceSlice[i] = v
	}

	_, err = mongo.InsertMany(interfaceSlice)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "")
}
