package db

import (
	"context"
	"fmt"
	"youngee_b_api/model/gorm_model"

	log "github.com/sirupsen/logrus"
)

func GetPricingStrategy(ctx context.Context, fansLow int64, fansUp int64, feeForm int64, platForm int64) (*gorm_model.InfoPricingStrategy, error) {
	db := GetReadDB(context.Background())
	var PricingStrategys []gorm_model.InfoPricingStrategy
	whereStr := fmt.Sprintf("fee_form = %d and platform = %d and fans_low <= %d and fans_up > %d", feeForm, platForm, fansLow, fansLow)
	orStr := fmt.Sprintf("fee_form = %d and platform = %d and fans_low < %d and fans_up >= %d", feeForm, platForm, fansUp, fansUp)
	orStr1 := fmt.Sprintf("fee_form = %d and platform = %d and fans_low >= %d and fans_up <= %d", feeForm, platForm, fansLow, fansUp)
	orStr2 := fmt.Sprintf("fee_form = %d and platform = %d and fans_low <= %d and fans_up >= %d", feeForm, platForm, fansLow, fansUp)
	err := db.Model(gorm_model.InfoPricingStrategy{}).Where(whereStr).Or(orStr).Or(orStr1).Or(orStr2).Scan(&PricingStrategys).Error
	if err != nil {
		log.Println("DB GetLastAutoDefaultID:", err)
		return nil, err
	}
	fmt.Printf("PricingStrategys%+v \n", PricingStrategys)
	PricingStrategy := gorm_model.InfoPricingStrategy{}
	if feeForm == 1 {
		var maxCharge float64 = 0
		for _, v := range PricingStrategys {
			if v.ServiceCharge >= maxCharge {
				maxCharge = v.ServiceCharge
				PricingStrategy = v
			}
		}
	} else {
		var maxRate int64 = 0
		for _, v := range PricingStrategys {
			if v.ServiceRate >= maxRate {
				maxRate = v.ServiceRate
				PricingStrategy = v
			}
		}
	}
	return &PricingStrategy, nil
}
