package serializer

import (
	"fonchain-artshow/cmd/model"
	"fonchain-artshow/pkg/utils"
	"math"
)

func _CalcPrice(artworks []*model.ArtworkPrice, ruler int32, totalPrice int64) (err error, save []*model.ArtworkPrice) {
	if totalPrice == 0 || ruler == 0 {
		return nil, artworks
	}

	save = make([]*model.ArtworkPrice, 0)

	var (
		needAddPriceArtworkIndex int
		currentArtworkRuler      int
		currentTotalPrice        int64
		maxRulerIndex            int
		totalDiv                 float64
	)

	price := utils.FormatFloat(float64(totalPrice)/float64(ruler)/10, 2) * 10 // 用于计算的单价
	//ruler_price := math.Floor(float64(total_price)/float64(ruler)/10) * 10     // 保存的单价

	for i := 0; i < len(artworks); i++ {
		if currentArtworkRuler < int(artworks[i].Ruler) {
			currentArtworkRuler = int(artworks[i].Ruler)
			needAddPriceArtworkIndex = i
			maxRulerIndex = i
		} else if currentArtworkRuler == int(artworks[i].Ruler) {
			currentArtworkRuler = 0
			needAddPriceArtworkIndex = -1
		}
		artworks[i].RulerPrice = int64(price)
		artworks[i].Price = int64(price * float64(artworks[i].Ruler))
		artworkPrice := float64(artworks[i].Price) * 0.95
		artworkPrice, div1 := math.Modf(artworkPrice)
		artworks[i].ArtworkPrice = int64(artworkPrice)
		totalDiv += div1 //  小数点 省略掉的   0.5

		copyrightPrice := artworks[i].Price - artworks[i].ArtworkPrice
		artworks[i].CopyrightPrice = copyrightPrice
		currentTotalPrice += artworks[i].Price
	}

	if needAddPriceArtworkIndex == -1 {
		needAddPriceArtworkIndex = maxRulerIndex
	}

	artworks[needAddPriceArtworkIndex].RulerPrice = int64(price)
	artworks[needAddPriceArtworkIndex].FloatPrice = totalPrice - currentTotalPrice - artworks[needAddPriceArtworkIndex].Price
	artworks[needAddPriceArtworkIndex].Price = int64(float32(totalPrice) - float32(currentTotalPrice) + float32(artworks[needAddPriceArtworkIndex].Price))
	artworks[needAddPriceArtworkIndex].ArtworkPrice = int64((float64(artworks[needAddPriceArtworkIndex].Price) * 0.95) + totalDiv)
	artworks[needAddPriceArtworkIndex].CopyrightPrice = artworks[needAddPriceArtworkIndex].Price - artworks[needAddPriceArtworkIndex].ArtworkPrice

	return nil, artworks
}

func CalcReward(artworks []*model.ArtworkPrice, reward int64) (err error, save []*model.ArtworkPrice) {
	save = artworks
	if reward == 0 {
		return nil, artworks
	}
	for i := 0; i < len(artworks); i++ {
		artworks[i].ArtistPrice = reward * int64(artworks[i].Ruler)
	}
	return nil, save
}
