package main

import (
	"fmt"
	"log"
	"math/rand"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Location struct {
	ID        uint `gorm:"primary_key"`
	Name      string
	Latitude  float64
	Longitude float64
}

func main() {
	dsn := "username:password@tcp(127.0.0.1:3306)/database_name?parseTime=true"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 创建 locations 表,如果不存在的话
	err = db.AutoMigrate(&Location{})
	if err != nil {
		log.Fatal(err)
	}

	// 插入模拟数据
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 10; i++ {
		location := Location{
			Name:      fmt.Sprintf("Location %d", i+1),
			Latitude:  randFloat(-90, 90),
			Longitude: randFloat(-180, 180),
		}
		if err := db.Create(&location).Error; err != nil {
			log.Printf("Failed to insert location %d: %v\n", i+1, err)
		} else {
			log.Printf("Inserted location %d: %s\n", i+1, location.Name)
		}
	}
}

// 生成指定范围内的随机浮点数
func randFloat(min, max float64) float64 {
	return min + rand.Float64()*(max-min)
}