package vehicle

import (
	"wails-app/internal/dao"
	"wails-app/internal/global"
	"wails-app/internal/model/vehicle/request"
)

type VehicleRecordService struct{}

// GetVehicleRecordByID 根据ID获取车辆记录
func (s *VehicleRecordService) GetVehicleRecordByID(id uint) (dao.VehicleRecord, error) {
	var record dao.VehicleRecord
	result := global.GVA_DB.First(&record, id)
	if result.RowsAffected == 0 {
		return dao.VehicleRecord{}, result.Error
	}
	return record, nil
}

// ListVehicleRecordsByPlateNumber 根据车牌号获取车辆记录列表
func (s *VehicleRecordService) ListVehicleRecordsByPlateNumber(plateNumber string, page, pageSize int) (int64, []dao.VehicleRecord, error) {
	var records []dao.VehicleRecord
	var total int64

	query := global.GVA_DB.Model(&dao.VehicleRecord{}).Where("plate_number = ?", plateNumber)

	// 计算总数
	query.Count(&total)

	// 分页查询
	offset := (page - 1) * pageSize
	result := query.Order("entry_time DESC").Offset(offset).Limit(pageSize).Find(&records)
	if result.Error != nil {
		return 0, nil, result.Error
	}

	return total, records, nil
}

// ListVehicleRecords 获取所有车辆记录列表
func (s *VehicleRecordService) ListVehicleRecords(info request.VehicleRecordRequest) (list []dao.VehicleRecord, total int64, err error) {
	db := global.GVA_DB.Debug().Model(&dao.VehicleRecord{})

	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

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

	// RFID标签精确查询
	if info.RFIDTag != "" {
		db = db.Where("rfid_tag LIKE ?", "%"+info.RFIDTag+"%")
	}

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

	// 分页查询 + 排序
	err = db.Order("entry_time DESC").Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}
