package service

import (
	"licserver/internal/model"
	"time"

	"gorm.io/gorm"
)

type DashboardService struct {
	db *gorm.DB
}

func NewDashboardService(db *gorm.DB) *DashboardService {
	return &DashboardService{db: db}
}

type DashboardStats struct {
	TotalDevices   int64               `json:"total_devices"`   // 设备总数
	TotalLicenses  int64               `json:"total_licenses"`  // 授权码总数
	TodayNew       int64               `json:"today_new"`       // 今日新增
	OnlineDevices  int64               `json:"online_devices"`  // 在线设备
	ActiveDevices  int64               `json:"active_devices"`  // 激活设备
	ExpiredDevices int64               `json:"expired_devices"` // 过期设备
	DeviceTypes    []DeviceTypeStats   `json:"device_types"`    // 设备类型分布
	TrendData      []DailyRegistration `json:"trend_data"`      // 注册趋势
	LicenseStats   LicenseStatistics   `json:"license_stats"`   // 授权码统计
}

type DeviceTypeStats struct {
	Type  string `json:"type"`
	Count int64  `json:"count"`
}

type DailyRegistration struct {
	Date  string `json:"date"`
	Count int64  `json:"count"`
}

type LicenseStatistics struct {
	Unused  int64 `json:"unused"`  // 未使用
	Used    int64 `json:"used"`    // 已使用
	Expired int64 `json:"expired"` // 已过期
	Revoked int64 `json:"revoked"` // 已撤销
}

func (s *DashboardService) GetDashboardStats() (*DashboardStats, error) {
	stats := &DashboardStats{}

	// 获取设备总数
	s.db.Model(&model.Device{}).Count(&stats.TotalDevices)

	// 获取授权码总数
	s.db.Model(&model.LicenseCode{}).Count(&stats.TotalLicenses)

	// 获取今日新增设备数
	today := time.Now().Format("2006-01-02")
	s.db.Model(&model.Device{}).Where("DATE(register_time) = ?", today).Count(&stats.TodayNew)

	// 获取在线设备数（最近30分钟内有活动的设备）
	thirtyMinutesAgo := time.Now().Add(-30 * time.Minute)
	s.db.Model(&model.Device{}).Where("last_active_at > ?", thirtyMinutesAgo).Count(&stats.OnlineDevices)

	// 获取激活和过期设备数
	s.db.Model(&model.Device{}).Where("status = ?", "active").Count(&stats.ActiveDevices)
	s.db.Model(&model.Device{}).Where("status = ?", "expired").Count(&stats.ExpiredDevices)

	// 获取设备类型分布
	var deviceTypes []DeviceTypeStats
	s.db.Model(&model.Device{}).
		Select("device_type as type, count(*) as count").
		Group("device_type").
		Scan(&deviceTypes)
	stats.DeviceTypes = deviceTypes

	// 获取最近7天的注册趋势
	var trendData []DailyRegistration
	sevenDaysAgo := time.Now().AddDate(0, 0, -7)
	s.db.Model(&model.Device{}).
		Select("DATE(register_time) as date, count(*) as count").
		Where("register_time >= ?", sevenDaysAgo).
		Group("DATE(register_time)").
		Order("date ASC").
		Scan(&trendData)
	stats.TrendData = trendData

	// 获取授权码统计
	s.db.Model(&model.LicenseCode{}).Where("status = ?", "unused").Count(&stats.LicenseStats.Unused)
	s.db.Model(&model.LicenseCode{}).Where("status = ?", "used").Count(&stats.LicenseStats.Used)
	s.db.Model(&model.LicenseCode{}).Where("status = ?", "expired").Count(&stats.LicenseStats.Expired)
	s.db.Model(&model.LicenseCode{}).Where("status = ?", "revoked").Count(&stats.LicenseStats.Revoked)

	return stats, nil
}
