package service

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/utils"
	"time"
)

func GetIpaddr(ip string) (utils.IpData, string) {

	if ip == "127.0.0.1" {
		return utils.IpData{}, ""
	}

	nowtime := time.Now()

	d, _ := time.ParseDuration("-6h")

	beforetime := nowtime.Add(d).Format("2006-01-02 15:04:05")

	data := new(model.Ipaddr)
	table := " ipaddr "
	field := " id, ip, code, data "

	sqlStr := "SELECT " + field +
		" FROM " + table +
		" WHERE ip = '" + ip + "' and code = 200 and create_time > '" + beforetime + "'" +
		" ORDER BY create_time desc "

	err := global.GVA_DB.Raw(sqlStr).Find(&data)
	if err != nil {
		fmt.Println(err)
	}

	if data.Id > 0 {
		ipDataDb := new(utils.IpData)
		utils.UnserislizeJson(data.Data, ipDataDb)
		return *ipDataDb, ""
	}

	ipData := utils.GetIpaddr(ip)

	IpaddrData := model.Ipaddr{
		Ip:         ip,
		Code:       ipData.Code,
		TaskNo:     ipData.TaskNo,
		Data:       string(utils.SerializeJson(ipData.Data)),
		CreateTime: utils.NowTime(),
	}

	global.GVA_DB.Table("ipaddr").Create(&IpaddrData)

	if ipData.Code == 200 {
		return ipData.Data, ""
	}

	fmt.Println(ipData.Msg)

	return utils.IpData{}, ipData.Msg
}
