package models

import (
	"exhibitionCentre/database"
	"exhibitionCentre/logging"

	"gorm.io/gorm"
)

type Order struct {
	gorm.Model
	UserName     string `gorm:"type:varchar(255);not null"`
	Phone        string `gorm:"type:varchar(255);not null"`
	Price        int    `gorm:"not null"`
	ExhibitId    uint   `gorm:"not null"` // 展品id
	ExhibitionId uint   `gorm:"not null"` // 展览id
}

func init() {
	if err := database.DB.AutoMigrate(&Order{}); err != nil {
		logging.Log.Fatalf("Mysql初始化Order表失败: %s\n", err.Error())
	}
	logging.Log.Info("Mysql初始化Order表完成.")
}

func CreateOrder(order *Order) error {
	if err := database.DB.Create(order).Error; err != nil {
		return err
	}
	return nil // 成功创建
}

func DeleteOrders(exhibitId int) error {
	if err := database.DB.Delete(&Order{}, "exhibit_id = ?", exhibitId).Error; err != nil {
		return err
	}
	return nil
}

func DeleteOrdersByExhibits(ids []int) error {
	if len(ids) == 0 {
		return nil
	}
	if err := database.DB.Delete(&Order{}, ids).Error; err != nil {
		return err
	}
	return nil
}

func GetOrdersByExhibitionId(exhibitionId int) ([]Order, error) {
	var orders []Order
	if err := database.DB.Find(&orders, "exhibition_id = ?", exhibitionId).Error; err != nil {
		return orders, err
	}
	return orders, nil
}

func GetOrdersByExhibitId(exhibitId int) ([]Order, error) {
	var orders []Order
	if err := database.DB.Order("price desc").Find(&orders, "exhibit_id = ?", exhibitId).Error; err != nil {
		return orders, err
	}
	return orders, nil
}
