package main

import (
	"encoding/json"
	"math/rand"
	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
	player_proto "mongo.games.com/game/protocol/player"
	"mongo.games.com/game/srvdata"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"
)

type CSPhoneLotteryInfoPacketFactory struct {
}

type CSPhoneLotteryInfoHandler struct {
}

func (this *CSPhoneLotteryInfoPacketFactory) CreatePacket() interface{} {
	pack := &player_proto.CSPhoneLotteryInfo{}
	return pack
}

// 获取抽奖信息
func (this *CSPhoneLotteryInfoHandler) Process(s *netlib.Session, packetid int, data interface{}, sid int64) error {

	if _, ok := data.(*player_proto.CSPhoneLotteryInfo); ok {
		p := PlayerMgrSington.GetPlayer(sid)
		logger.Logger.Trace("客户端请求抽奖信息！snid = ", p.SnId)
		if p == nil {
			logger.Logger.Warn("CSPhoneLotteryInfo p == nil")
			return nil
		}
		if WelfareMgrSington.GetPhoneLotteryStatus(p.Platform) == WelfareClose {
			return nil
		}
		pack := &player_proto.SCPhoneLotteryInfo{}
		pack.PhoneScore = p.PhoneScore
		pack.Count = p.LotteryCount
		pool := srvdata.PBDB_PhoneLotteryMgr.Datas.GetArr()
		for _, lottery := range pool {
			if p.AppChannel == common.ChannelGooglePlay {
				if lottery.Type == 1 {
					continue
				}
			} else {
				if lottery.Type == 2 {
					continue
				}
			}
			date := &player_proto.LotteryItem{
				Id:      lottery.Id,
				ItemId:  lottery.Item_Id,
				ItemNum: int64(lottery.Grade),
			}
			pack.Item = append(pack.Item, date)
		}
		p.SendToClient(int(player_proto.PlayerPacketID_PACKET_SC_PhoneLotteryInfo), pack)
		logger.Logger.Trace("返回抽奖信息：", pack.String())
	}
	return nil
}

// 请求抽奖
type CSPhoneLotteryPacketFactory struct {
}

type CSPhoneLotteryHandler struct {
}

func (this *CSPhoneLotteryPacketFactory) CreatePacket() interface{} {
	pack := &player_proto.CSPhoneLottery{}
	return pack
}
func (this *CSPhoneLotteryHandler) Process(s *netlib.Session, packetid int, data interface{}, sid int64) error {
	if msg, ok := data.(*player_proto.CSPhoneLottery); ok {
		p := PlayerMgrSington.GetPlayer(sid)
		if p == nil {
			logger.Logger.Warn("CSPhoneLottery p == nil")
			return nil
		}
		if WelfareMgrSington.GetPhoneLotteryStatus(p.Platform) == WelfareClose {
			return nil
		}
		countType := msg.GetLotteryType()
		count := int32(0)
		if countType == 1 {
			count = 1
		} else {
			count = 10
		}
		logger.Logger.Tracef("玩家请求抽奖，snid =%d,count = %d ", p.SnId, count)
		if p == nil {
			logger.Logger.Warn("CSPhoneLottery p == nil")
			return nil
		}
		if p.LotteryCount < count {
			logger.Logger.Trace("剩余抽奖次数不足，无法抽奖 count = ", count)
			return nil
		}
		//p.LotteryCount -= count
		p.addLotteryCount(-count)
		pool := srvdata.PBDB_PhoneLotteryMgr.Datas.GetArr()
		pack := &player_proto.SCPhoneLottery{}
		items := make([]*Item, 0)
		for i := 1; i <= int(count); i++ {
			//抽奖
			rate := 0
			weight := 0
			for _, lottery := range pool {
				if p.AppChannel == common.ChannelGooglePlay {
					if lottery.Type == 1 {
						continue
					}
				} else {
					if lottery.Type == 2 {
						continue
					}
				}
				if p.PhoneScore < int64(lottery.Odd) {
					rate = 1
					weight += int(lottery.Oddrate1)
				} else if p.PhoneScore >= int64(lottery.Odd) && p.PhoneScore < int64(lottery.Odd2) {
					rate = 2
					weight += int(lottery.Oddrate2)
				} else if p.PhoneScore >= int64(lottery.Odd2) && p.PhoneScore < int64(lottery.Odd3) {
					rate = 3
					weight += int(lottery.Oddrate3)
				} else if p.PhoneScore >= int64(lottery.Odd3) {
					rate = 4
					weight += int(lottery.Oddrate4)
				}
			}
			random := rand.Intn(weight) + 1
			num := 0
			logger.Logger.Tracef("玩家抽奖 当前权重区间 rate = %d,weight = %d ,随机到的值：%d", rate, weight, random)
			for _, lottery := range pool {
				if p.AppChannel == common.ChannelGooglePlay {
					if lottery.Type == 1 {
						continue
					}
				} else {
					if lottery.Type == 2 {
						continue
					}
				}
				if rate == 1 {
					if lottery.Oddrate1 == 0 {
						continue
					}
					num += int(lottery.Oddrate1)
				} else if rate == 2 {
					if lottery.Oddrate2 == 0 {
						continue
					}
					num += int(lottery.Oddrate2)
				} else if rate == 3 {
					if lottery.Oddrate3 == 0 {
						continue
					}
					num += int(lottery.Oddrate3)
				} else if rate == 4 {
					if lottery.Oddrate4 == 0 {
						continue
					}
					num += int(lottery.Oddrate4)
				}
				if random <= num {
					itemArr := &player_proto.LotteryItem{}
					itemArr.ItemId = lottery.Item_Id
					itemArr.ItemNum = int64(lottery.Grade)
					itemArr.Id = lottery.Id
					items = append(items, &Item{
						ItemId:  lottery.Item_Id,      // 物品id
						ItemNum: int64(lottery.Grade), // 数量
					})
					logger.Logger.Tracef("玩家抽奖获得物品 itemId = %d,itemNum = %d", lottery.Item_Id, lottery.Grade)
					pack.Item = append(pack.Item, itemArr)
					break
				}
			}
		}
		//增加到玩家背包
		BagMgrSingleton.AddJybBagInfo(p, items, 0, common.GainWay_PhoneScore, "system", "玩游戏积分")
		pack.Count = p.LotteryCount
		pack.PhoneScore = p.PhoneScore
		logger.Logger.Tracef("获取玩家抽奖权重 score = %d,抽奖获得的物品：%v", p.PhoneScore, pack)
		p.SendToClient(int(player_proto.PlayerPacketID_PACKET_SC_PhoneLottery), pack)
		//抽奖统计
		jsonData, err := json.Marshal(items)
		if err != nil {
			return err
		}
		LogChannelSingleton.WriteMQData(model.GeneratePhoneLottery(p.SnId, p.Platform, string(jsonData), 1, 0, 0, 0))
	}
	return nil
}

func init() {
	// 抽奖信息
	common.RegisterHandler(int(player_proto.PlayerPacketID_PACKET_CS_PhoneLotteryInfo), &CSPhoneLotteryInfoHandler{})
	netlib.RegisterFactory(int(player_proto.PlayerPacketID_PACKET_CS_PhoneLotteryInfo), &CSPhoneLotteryInfoPacketFactory{})
	// 抽奖
	common.RegisterHandler(int(player_proto.PlayerPacketID_PACKET_CS_PhoneLottery), &CSPhoneLotteryHandler{})
	netlib.RegisterFactory(int(player_proto.PlayerPacketID_PACKET_CS_PhoneLottery), &CSPhoneLotteryPacketFactory{})
}
