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)

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

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

	err := global.GVA_DB.Raw(sqlStr, ip, beforetime).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
}
