package repository

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

type PaymentRepository struct{}

func (r *PaymentRepository) Create(record *dao.PaymentRecord) error {
	return global.GVA_DB.Create(record).Error
}

// PaymentListQuery 收费记录查询参数
type PaymentListQuery struct {
	PlateNumber   string `form:"plate_number"`
	PaymentMethod string `form:"payment_method"`
	ParkingLotID  uint   `form:"parking_lot_id"`
	StartDate     string `form:"start_date"`
	EndDate       string `form:"end_date"`
	Page          int    `form:"page"`
	PageSize      int    `form:"page_size"`
}

// PaymentListResult 收费记录列表项
type PaymentListResult struct {
	ID            uint    `json:"id"`
	PlateNumber   string  `json:"plate_number"`
	VehicleType   string  `json:"vehicle_type"`
	PaymentMethod string  `json:"payment_method"`
	Amount        float64 `json:"amount"`
	PaidAmount    float64 `json:"paid_amount"`
	ChangeAmount  float64 `json:"change_amount"`
	OperatorID    uint    `json:"operator_id"`
	OperatorName  string  `json:"operator_name"`
	ParkingLot    string  `json:"parking_lot"`
	PaidAt        string  `json:"paid_at"`
	EntryTime     string  `json:"entry_time"`
	ExitTime      string  `json:"exit_time"`
	StayTime      int64   `json:"stay_time"`
}

// List 查询收费记录列表（关联 vehicle_record + vehicle + vehicle_type）
func (r *PaymentRepository) List(q PaymentListQuery) ([]PaymentListResult, int64, error) {
	db := global.GVA_DB.Table("payment_record").
		Select(`payment_record.id, vehicle_record.plate_number, vehicle_type.name as vehicle_type, payment_record.payment_method,
			payment_record.amount, payment_record.paid_amount, payment_record.change_amount,
			payment_record.operator_id, sys_users.nick_name as operator_name, vehicle_record.parking_lot_id, parking_lot.lot_name as parking_lot, payment_record.paid_at,
			vehicle_record.entry_time, vehicle_record.exit_time, vehicle_record.stay_time`).
		Joins("LEFT JOIN vehicle_record ON vehicle_record.id = payment_record.record_id").
		Joins("LEFT JOIN vehicle ON vehicle.plate_number = vehicle_record.plate_number").
		Joins("LEFT JOIN vehicle_type ON vehicle_type.id = vehicle.vehicle_type_id").
		Joins("LEFT JOIN sys_users ON sys_users.id = payment_record.operator_id").
		Joins("LEFT JOIN parking_lot ON parking_lot.id = vehicle_record.parking_lot_id")

	if q.PlateNumber != "" {
		db = db.Where("vehicle_record.plate_number LIKE ?", "%"+q.PlateNumber+"%")
	}
	if q.ParkingLotID > 0 {
		db = db.Where("vehicle_record.parking_lot_id = ?", q.ParkingLotID)
	}
	if q.PaymentMethod != "" {
		db = db.Where("payment_record.payment_method = ?", q.PaymentMethod)
	}
	if q.StartDate != "" {
		db = db.Where("payment_record.paid_at >= ?", q.StartDate)
	}
	if q.EndDate != "" {
		db = db.Where("payment_record.paid_at <= ?", q.EndDate+" 23:59:59")
	}

	var total int64
	db.Count(&total)

	if q.Page <= 0 {
		q.Page = 1
	}
	if q.PageSize <= 0 {
		q.PageSize = 10
	}
	offset := (q.Page - 1) * q.PageSize

	var results []PaymentListResult
	err := db.Order("payment_record.paid_at DESC").Offset(offset).Limit(q.PageSize).Scan(&results).Error
	return results, total, err
}

// TodaySummary 当日收费汇总
type TodaySummary struct {
	TotalAmount float64 `json:"total_amount"`
	CashAmount  float64 `json:"cash_amount"`
	FreeAmount  float64 `json:"free_amount"`
	TotalCount  int64   `json:"total_count"`
}

// GetTodaySummary 获取当日收费汇总
func (r *PaymentRepository) GetTodaySummary() (TodaySummary, error) {
	var s TodaySummary
	today := time.Now().Format("2006-01-02")
	err := global.GVA_DB.Table("payment_record").
		Select(`COALESCE(SUM(amount), 0) as total_amount,
			COALESCE(SUM(CASE WHEN payment_method = 'cash' THEN amount ELSE 0 END), 0) as cash_amount,
			COALESCE(SUM(CASE WHEN payment_method = 'free' THEN amount ELSE 0 END), 0) as free_amount,
			COUNT(*) as total_count`).
		Where("paid_at >= ? AND paid_at < ?", today, today+" 23:59:59").
		Scan(&s).Error
	return s, err
}
