package game

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"math"
	mergeDataCfg "server/conf/merge_data"
	orderCfg "server/conf/order"
	"server/game/mod/decorate"
	"server/game/mod/item"
	"server/game/mod/order"
	"server/game/mod/quest"
	"server/msg"
	"server/pkg/github.com/name5566/leaf/log"
	"time"
)

func UnitEndlessReward(p *Player) error {
	EndlessMod := p.PlayMod.getEndlessMod()
	if EndlessMod == nil {
		return fmt.Errorf("EndlessMod is nil")
	}
	BaseMod := p.PlayMod.getBaseMod()
	Item, err := EndlessMod.GetReward(BaseMod.GetLevel())
	if err != nil {
		return err
	}
	if Item == nil {
		return fmt.Errorf("item is nil")
	}
	err = p.HandleItem(Item, msg.ITEM_POP_LABEL_Endless.String())
	if err != nil {
		return err
	}
	return nil
}

func UnitChessShop(p *Player) error {
	ChessMod := p.PlayMod.getChessMod()

	ChargeMod := p.PlayMod.getChargeMod()
	ChargeMod.InitChessShop(ChessMod.GetEmitList())
	return nil
}

func UnitOrder(p *Player) error {
	OrderMod := p.PlayMod.getOrderMod()
	ChessMod := p.PlayMod.getChessMod()
	BaseMod := p.PlayMod.getBaseMod()
	//OrderMod.OrderList = make(map[int]order.Order)
	for i := 0; i < 1000; i++ {
		//OrderMod.ChessPool = nil
		//OrderMod.EmitShuffle = nil
		err := OrderMod.CreateNormalOrder(BaseMod.GetLevel(), ChessMod.GetOrderEmit(), BaseMod.GetEnergyMul(), order.Common_type)
		if err != nil {
			return err
		}
		for k, v := range OrderMod.OrderList {
			if v.Type == order.Super_type {
				continue
			}
			if len(v.Items) > 0 {
				continue
			}
			if v.Diff == 0 {
				continue
			}
			Star := order.GetOrderStar(v.MergeId, ChessMod.GetOrderEmit())
			v.Items = []*item.Item{item.NewItem(item.ITEM_STAR_ID, Star)}
			OrderMod.OrderList[k] = v
			fmt.Printf("OrderId %d, Diff %d, MergeId %v, Star %d\n", k, v.Diff, v.MergeId, Star)
		}
	}
	NumMap := make(map[int]int)
	for _, v := range OrderMod.OrderList {
		NumMap[len(v.MergeId)]++
	}
	sum0 := 0
	for _, v := range NumMap {
		sum0 += v
	}
	for k, v := range NumMap {
		fmt.Printf("棋子数量： %d, 占比： %.2f%% \n", k, float64(v)/float64(sum0)*100)
	}
	DiffMap := make(map[int]int)
	for _, v := range OrderMod.OrderList {
		DiffMap[v.Diff]++
	}
	sum := 0
	for _, v := range DiffMap {
		sum += v
	}
	for k, v := range DiffMap {
		fmt.Printf("难度等级： %d, 占比： %.2f%% \n", k, float64(v)/float64(sum)*100)
	}
	AP := make(map[string]int, 0)
	BP := make(map[string]int, 0)
	for _, v := range OrderMod.OrderList {
		for _, id := range v.MergeId {
			Color := mergeDataCfg.GetColorById(id)
			if Color == "Bath Toys" {
				AP["Bath Toys"] += 1
			}
			if Color == "Cleaning Tools" {
				AP["Cleaning Tools"] += 1
			}
			if Color == "Baby Toy" {
				BP["Baby Toy"] += 1
			}
			if Color == "Books And Picture Books" {
				BP["Books And Picture Books"] += 1
			}
		}
	}
	sum1 := 0
	for _, v := range AP {
		sum1 += v
	}
	sum2 := 0
	for _, v := range BP {
		sum2 += v
	}
	for k, v := range AP {
		fmt.Printf("%s %.2f\n", k, float64(v)/float64(sum1)*100)
	}
	for k, v := range BP {
		fmt.Printf("%s %.2f\n", k, float64(v)/float64(sum2)*100)
	}
	return nil
}

func UnitOrderSeed(player *Player) error {
	start := time.Now()

	BaseMod := player.PlayMod.getBaseMod()
	BaseMod.Seed = true
	player.TriggerSeedSource()
	o := player.TriggerSeedOrder()
	fmt.Println(o)

	elapsed := time.Since(start)
	fmt.Printf("UnitOrderSeed took %s\n", elapsed)
	return nil
}

func UnitChess(p *Player) error {
	CardMod := p.PlayMod.getCardMod()
	for i := 0; i < 1000; i++ {
		CardId := CardMod.RandCard(3)
		fmt.Println(CardId)
	}
	return nil
}

func UnitDecorate(p *Player) error {
	return nil
}

func UnitSevenMonthReward(p *Player) error {
	ChargeMod := p.PlayMod.getChargeMod()
	BaseMod := p.PlayMod.getBaseMod()
	ChessMod := p.PlayMod.getChessMod()
	ChargeMod.TriggerChargeUnlock(int(BaseMod.Level), ChessMod.GetEmitList())
	return nil
}

func UnitAllCard(p *Player) error {
	CardMod := p.PlayMod.getCardMod()
	Item, err := CardMod.OpenCardPack(5)
	if err != nil {
		return err
	}
	fmt.Print(Item)
	return nil
}

func UnitLimitProgress(p *Player) error {
	LimitedTimeEventMod := p.PlayMod.getLimitedTimeEventMod()
	LimitedTimeEventMod.Progress = 5
	LimitedTimeEventMod.ZeroUpdate(7)
	LimitedTimeEventMod.AddProgress(6)
	return nil
}

func UnitLimitedTimeEvent(p *Player) error {
	LimitedTimeEventMod := p.PlayMod.getLimitedTimeEventMod()
	ChessMod := p.PlayMod.getChessMod()
	mergeList := []int{246, 15}
	AddItem := LimitedTimeEventMod.GetChestReward(mergeList, ChessMod.GetStarEmitList())
	fmt.Print(AddItem)
	return nil
}

func UnitCard(p *Player) error {
	CardMod := p.PlayMod.getCardMod()
	for i := 0; i < 10000; i++ {
		CardMod.OpenCardPack(5)
	}
	return nil
}
func UnitOrder1(p *Player, Lv, EnergyMul int) ([]string, [][]float64) {
	// ChessMod := p.PlayMod.getChessMod()
	// Emit := ChessMod.GetEmitList()
	// OrderMod := p.PlayMod.getOrderMod()
	// OrderMod.LastDiff = 1
	// OrderMod.OrderList = make(map[int]order.Order)
	// // ChessMod := p.PlayMod.getChessMod()
	// // EmitList := ChessMod.GetEmitList()
	// // fmt.Println(EmitList)
	// OrderMod.Debug = make(map[int]int)
	// for i := 0; i < 5000; i++ {
	// 	err := OrderMod.CreateNormalOrder(Lv, Emit, EnergyMul)
	// 	log.Debug("OrderMod.CreateNormalOrder %d", i)
	// 	if err != nil {
	// 		return nil, nil
	// 	}
	// }
	// I := make(map[int]int)
	// for k, v := range OrderMod.Debug {
	// 	// fmt.Printf("chessId %d, num %d\n", k, v)
	// 	ChessLv := mergeDataCfg.GetLvById(k)
	// 	I[ChessLv] += v
	// }
	// keys := make([]int, 0, len(I))
	// Sum := 0
	// for k, v := range I {
	// 	Sum += v
	// 	keys = append(keys, k)
	// }
	// sort.Ints(keys)
	// xValue := make([]string, 0)
	// yValue := make([][]float64, 0)
	// line := make([]float64, 0)
	// for _, k := range keys {
	// 	xValue = append(xValue, fmt.Sprintf("Lv %d", k))
	// 	line = append(line, float64(I[k])/float64(Sum)*100)
	// 	fmt.Printf("Lv %d, num %.2f %%\n", k, float64(I[k])/float64(Sum)*100)
	// }
	// yValue = append(yValue, line)
	// return xValue, yValue
	return nil, nil
}

func UnitOrder2(p *Player, Lv, EnergyMul int) float64 {
	ChessMod := p.PlayMod.getChessMod()
	Emit := ChessMod.GetEmitList()
	OrderMod := p.PlayMod.getOrderMod()
	OrderMod.LastDiff = 1
	OrderMod.OrderList = make(map[int]order.Order)
	// ChessMod := p.PlayMod.getChessMod()
	// EmitList := ChessMod.GetEmitList()
	// fmt.Println(EmitList)
	// OrderMod.Debug = make(map[int]int)
	for i := 0; i < 5000; i++ {
		err := OrderMod.CreateNormalOrder(Lv, Emit, EnergyMul, order.Common_type)
		log.Debug("OrderMod.CreateNormalOrder %d", i)
		if err != nil {
			return 0
		}
	}
	Energy := 0.0
	for _, v := range OrderMod.OrderList {
		for _, v1 := range v.MergeId {
			Color := mergeDataCfg.GetColorById(v1)
			Lv := mergeDataCfg.GetLvById(v1)
			EmitId := order.GetEmitByColor(Emit, Color)
			AdjustLv := mergeDataCfg.GetAdjust(EmitId, Color, EnergyMul)
			Energy += math.Pow(2, float64(Lv-1+AdjustLv))
		}
	}
	return Energy / float64(5000)
}

func UnitChess1(p *Player) error {
	ChessMod := p.PlayMod.getChessMod()
	p.PushClientRes(ChessMod.BackData())
	p.EmitRetireTrigger1()
	DailyTaskMod := p.PlayMod.getDailyTaskMod()
	p.PushClientRes(DailyTaskMod.BackData())
	return nil
}

func UnitPlayroom(p *Player) error {

	p.PlayroomBackData()
	return nil
}

func UnitDailyTask(p *Player) error {
	FT := p.PlayMod.getFriendTreasureMod()
	FT.ZeroUpdate()
	return nil
}

func UnitTriggerMail(p *Player) error {
	p.QuestTrigger(&quest.Trigger{Label: quest.TRIGGER_LABEL_UPLV})
	p.ProcessTrigger()
	return nil
}

func UnitDecorateErr(p *Player) error {
	DecorateMod := p.PlayMod.getDecorateMod()
	if len(DecorateMod.FinishList) != DecorateMod.Progress {
		log.Debug("decorate error uid %d", p.M_DwUin)
	}
	log.Debug("decorate ok uid %d", p.M_DwUin)
	return nil
}

func UnitPlayroomOrder(p *Player) error {
	PlayroomMod := p.PlayMod.getPlayroomMod()
	PlayroomMod.CreateOrderReward(100, p.PlayMod.getItemMod())
	return nil
}

func UnitPetOrder(p *Player) error {
	p.CreateNormalOrder()
	ChessMod := p.PlayMod.getChessMod()
	DecorateMod := p.PlayMod.getDecorateMod()
	OrderFactor := orderCfg.GetOrderFactor(DecorateMod.GetAreaId())
	Star := order.GetOrderStar([]int{305}, ChessMod.GetStarEmitList())
	a := int(float64(Star)*float64(OrderFactor)/1000+0.5) * 10
	fmt.Print(a)
	return nil
}

func UnitDecoratePartCost(p *Player) error {
	p.LoginBackData()
	DecorateMod := p.PlayMod.getDecorateMod()
	DecorateMod.AreaId = 3
	DecorateMod.PartCost = make(map[int]*decorate.PartCostInfo)
	DecorateMod.PartClassPool = []int{}
	DecorateMod.PartPool = make(map[int]int)
	DecorateMod.InitData()
	Items, _, _ := DecorateMod.GetDecorateCostItem(1, 33, false)
	err := p.HandleLoseItem(Items, "")
	if err != nil {
		fmt.Print(err)
	}
	return nil
	ChessMod := p.PlayMod.getChessMod()
	return ChessMod.PutPartInBag(1515)
}

func UnitOrderTrigger(p *Player) error {
	OrderMod := p.PlayMod.getOrderMod()
	BaseMod := p.PlayMod.getBaseMod()
	Lv := int(BaseMod.Level)
	ChessMod := p.PlayMod.getChessMod()
	Emit := ChessMod.GetEmitList()
	EnergyMul := BaseMod.GetEnergyMul()
	OrderMod.TriggerOrder(Lv, order.TRIGGER_TYPE_ORDER, Emit, EnergyMul)
	order.GetOrderStar([]int{1146}, ChessMod.GetOrderEmit())
	return nil
}

func UnitOrderExtra(p *Player) error {
	OrderMod := p.PlayMod.getOrderMod()
	BaseMod := p.PlayMod.getBaseMod()
	ChessMod := p.PlayMod.getChessMod()
	Update := OrderMod.CreateExtraOrder([]int{25}, nil, ChessMod.GetUnlockChessList(), BaseMod.GetEnergyMul(), BaseMod.GetLevel())
	fmt.Print(Update)
	return nil
}

func UnitOrderPetReward(p *Player) error {
	OrderMod := p.PlayMod.getOrderMod()
	Item, _, OrderType, _, _ := OrderMod.RewardOrder(10015)
	if OrderType == order.Pet_type {
		Item = p.FormatPetOrderItem(Item)
	}
	return nil
}

func UnitCatnip(p *Player) error {
	//OrderMod := p.PlayMod.getOrderMod()
	//KvMod := p.PlayMod.getKvMod()
	ChessMod := p.PlayMod.getChessMod()
	var buf bytes.Buffer
	encode := gob.NewEncoder(&buf)
	encode.Encode(ChessMod)
	fmt.Printf("buf len:%dk\n", buf.Len()/1024)
	return nil
}

func Benchmark(player *Player) {
	ChampshipMod := player.PlayMod.getChampshipMod()
	ChampshipMod.AddScore([]int{949, 941, 10})
	player.HandleInChampshipRank()
	player.HandleInUserRank()
}
