package admin

import (
	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/jwtSet"
	"main/model"
	"main/utils"
	"strings"
)

func Logs(party iris.Party) {
	party.Post("/", saveLogs)
	party.Get("/", jwtSet.Jwt.Serve, checkAdmin, getLogStats)
	party.Get("/detail", jwtSet.Jwt.Serve, checkAdmin, getLogDetail)
	party.Get("/sys", jwtSet.Jwt.Serve, checkAdmin, getSysLogs)
	party.Get("/log-container-list", jwtSet.Jwt.Serve, checkAdmin, getSysLogsContainerList)
}

// FormatLog 对日志内容切分，格式化数据
func FormatLog(logItem string, date string, c chan model.Logs) {
	var resLogItem model.Logs
	resLogItem.Ip = strings.Split(logItem, " ")[0]
	resLogItem.Location = GetIpLocation(resLogItem.Ip)
	//resLogItem.Location = getLocalIpAddr(resLogItem.Ip)
	//if resLogItem.Location == "" {
	//	resLogItem.Location, _ = getIpAddr(resLogItem.Ip)
	//}
	resLogItem.Time = formatTime(date, strings.Split(strings.Split(logItem, "[")[1], "]")[0])
	if strings.Split(logItem, "\"")[1] != "" {
		if strings.Contains(strings.Split(logItem, "\"")[1], " /") {
			resLogItem.Method = strings.Split(strings.Split(logItem, "\"")[1], " ")[0]
			resLogItem.Path = strings.Split(strings.Split(logItem, "\"")[1], " ")[1]
		} else {
			resLogItem.Method = ""
			resLogItem.Path = strings.Split(logItem, "\"")[1]
		}
		resLogItem.Status = strings.Split(strings.Split(logItem, "\" ")[1], " ")[0]
	}
	resLogItem.UserAgent = strings.Split(logItem, "\"")[5]
	c <- resLogItem
}

// GetIpLocation 获取IP对应的地址
func GetIpLocation(ip string) string {
	if len(ipLocationList) == 0 {
		UpdateLocalIpList()
	}
	location := getLocalIpAddr(ip)
	if location == "" {
		location, _ = getIpAddr(ip)
	}
	return location
}

func UpdateLocalIpList() {
	var nullDataList []nullData
	db := database.GetInstance().GetMysqlDb()
	if err := db.Model(&model.Logs{}).
		Distinct("logs.ip", "ips_locations.location").
		Where("ips_locations.location is null").
		Joins("left join ips_locations on logs.ip=ips_locations.ip").
		Scan(&nullDataList).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	if len(nullDataList) != 0 {
		for _, data := range nullDataList {
			location, err := utils.GetIpLocation(data.IP)
			if err != nil {
				logrus.Errorln(data.IP, "IP地址获取失败", err)
			}
			if err = db.Create(&model.IpsLocation{
				Ip:       data.IP,
				Location: location,
			}).Error; err != nil {
				logrus.Errorln("sql执行失败：", err)
			}
		}
	}
	if err := db.Distinct("ip, location").Find(&ipLocationList).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
	}
	logrus.Infoln("更新本地IP地址列表")
}
