package dao

import (
	"wails-app/internal/global"
	"time"
)

type Shortlist struct {
	global.GVA_MODEL
	ListType       string     `json:"list_type" gorm:"comment:名单类型"`
	VehicleId      int        `json:"vehicle_id" gorm:"comment:车辆ID"`
	Vehicle        *Vehicle   `json:"vehicle" gorm:"foreignKey:VehicleId"`
	ExpirationTime *time.Time `json:"expiration_time" gorm:"comment:过期时间;default:null"`
}

func (Shortlist) TableName() string {
	return "shortlist"
}

func QueryShortlistList(limit, offset int, listType, plateNumber, rfidTag string) (list []Shortlist, total int64, err error) {
	db := global.GVA_DB.Model(&Shortlist{}).Preload("Vehicle").Preload("Vehicle.VehicleType") // 预加载车辆信息

	// 1. 按名单类型筛选：black / white
	if listType != "" {
		db = db.Where("list_type = ?", listType)
	}

	// 2. 车牌号模糊查询
	if plateNumber != "" {
		db = db.Joins("Vehicle").Where("Vehicle.plate_number LIKE ?", "%"+plateNumber+"%")
	}

	// 3. RFID标签精确查询
	if rfidTag != "" {
		db = db.Joins("Vehicle").Where("Vehicle.rfid_tag = ?", rfidTag)
	}

	// 查询总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 查询列表
	err = db.Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}

func QueryAllShortlists() (list []Shortlist, err error) {
	err = global.GVA_DB.Model(&Shortlist{}).Find(&list).Error

	return list, err
}

func QueryShortlistByRFIDTag(rfidTag string) (shortlist Shortlist, err error) {
	err = global.GVA_DB.Model(&Shortlist{}).
		Preload("Vehicle").
		Joins("LEFT JOIN vehicle ON shortlist.vehicle_id = vehicle.id").
		Where("vehicle.rfid_tag = ?", rfidTag).
		First(&shortlist).Error

	return
}

func CreateShortlist(shortlist Shortlist) error {
	return global.GVA_DB.Create(&shortlist).Error
}

func UpdateShortlist(shortlist Shortlist) error {
	return global.GVA_DB.Where("id = ?", shortlist.ID).Updates(shortlist).Error
}

func DeleteShortlist(id int) error {
	return global.GVA_DB.Where("id = ?", id).Unscoped().Delete(&Shortlist{}).Error
}
