package main

import (
	"fmt"
	"mongo.games.com/game/protocol/shop"
	"time"

	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
	hall_proto "mongo.games.com/game/protocol/gamehall"
	player_proto "mongo.games.com/game/protocol/player"
	webapi_proto "mongo.games.com/game/protocol/webapi"
	"mongo.games.com/game/protocol/welfare"
	"mongo.games.com/game/srvdata"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/module"
)

const (
	OpAll           = 0
	OpTurnplate     = 1
	OpBlindBox      = 2
	OpFirstPay      = 3
	OpContinuousPay = 4
	OpPhoneLottery  = 5
)

const (
	WelfareNil   = 0 // 不处理
	WelfareOpen  = 1 // 开启
	WelfareClose = 2 // 关闭
)

const (
	GameSubsidyid = 1 //救济金id
)

var WelfareMgrSington = &WelfareMgr{
	Sign7:              make(map[string]*webapi_proto.Welfare7SignDateList),
	Turnplate:          make(map[string]*webapi_proto.WelfareTurnplateDateList),
	BlindBox:           make(map[string]*webapi_proto.WelfareBlindBoxDataList),
	BlindBoxCycle:      make(map[string]int32),
	FirstPay:           make(map[string]*webapi_proto.WelfareFirstPayDataList),
	FirstPayCycle:      make(map[string]int32),
	ContinuousPay:      make(map[string]*webapi_proto.WelfareContinuousPayDataList),
	ContinuousPayCycle: make(map[string]int32),
	PhoneLotteryStatus: make(map[string]*webapi_proto.WelfarePhoneLotteryStatus),
}

type WelfareMgr struct {
	BaseClockSinker
	Sign7              map[string]*webapi_proto.Welfare7SignDateList
	Turnplate          map[string]*webapi_proto.WelfareTurnplateDateList
	BlindBox           map[string]*webapi_proto.WelfareBlindBoxDataList
	BlindBoxCycle      map[string]int32
	FirstPay           map[string]*webapi_proto.WelfareFirstPayDataList
	FirstPayCycle      map[string]int32
	ContinuousPay      map[string]*webapi_proto.WelfareContinuousPayDataList
	ContinuousPayCycle map[string]int32
	PhoneLotteryStatus map[string]*webapi_proto.WelfarePhoneLotteryStatus
}

func (this *WelfareMgr) ModuleName() string {
	return "WelfareMgr"
}

// 设置 rnums 救济金领取次数
func (this *WelfareMgr) SetWelfData(p *Player, rnums int32) {
	// this.MonitorWelfData(p)
	if rnums > 0 {
		p.WelfData.ReliefFundTimes += rnums
	}
	p.dirty = true
}

func (this *WelfareMgr) GetReliefFund(p *Player, isVideo bool) {
	sdata := srvdata.PBDB_GameSubsidyMgr.GetData(GameSubsidyid)
	// this.MonitorWelfData(p)
	pack := &welfare.SCGetReliefFund{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	if sdata != nil {

		if p.WelfData.ReliefFundTimes >= sdata.Times {
			pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes

			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETRELIEFFUND), pack)

		} else if p.Coin >= int64(sdata.LimitNum) {
			pack.OpRetCode = welfare.OpResultCode_OPRC_CoinTooMore
		} else {
			var rate int = 1
			var gainWay int32 = common.GainWay_ReliefFund
			var add int64
			coin := int64(sdata.Get) // 增加金币
			p.WelfData.ReliefFundTimes += 1
			award := PetMgrSington.GetAwardPetByWelf(p)
			if award > 0 {
				if isVideo { // 双倍领取，蝶女视频加成
					gainWay = common.GainWay_ReliefFund2
					rate = 2
					add = int64(float64(coin*award*2) / 100.0)
					roleGirl := PetMgrSington.GetRoleInfo(p, 2000001)
					if roleGirl != nil && roleGirl.Level > 0 {
						//蝶女加成
						add += int64(float64(coin*int64(roleGirl.Award)*2) / 100.0)
					}
					coin = coin*2 + add
					TaskSubjectSingleton.Touch(common.TaskTypeAdv, &TaskData{
						SnId: p.SnId,
						Num:  1,
					})
				} else {
					add = int64(float64(coin*award) / 100.0)
					coin = coin + add
				}
			}
			p.AddCoin(coin, add, gainWay, "ReliefFund",
				fmt.Sprintf("领取救济金-%v-%v倍", coin, rate))

			//LogChannelSingleton.WriteMQData(model.GenerateSystemFreeGive(p.SnId, p.Name, p.Platform, model.SystemFreeGive_GiveType_ReliefFund, model.SystemFreeGive_CoinType_Coin, int64(coin)))

			pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
			pack.Coin = coin
			pack.Times = p.WelfData.ReliefFundTimes

			logger.Logger.Tracef("NewReliefFundLogEx snid: %v Coin:%v", p.SnId, pack.Coin)
			getType := model.SystemFreeGive_GiveType_ReliefFund
			if isVideo {
				getType = model.SystemFreeGive_GiveType_ShopAd
			}

			log := model.NewReliefFundLogEx(p.SnId, getType, model.SystemFreeGive_CoinType_Coin, coin, p.CreateTime.Unix(), p.Platform)
			if log != nil {
				LogChannelSingleton.WriteLog(log)
				logger.Logger.Tracef("NewReliefFundLogEx WriteLog snid: %v Coin:%v", p.SnId, pack.Coin)
			}
		}
	}
	logger.Logger.Tracef("GetReliefFund snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETRELIEFFUND), pack)
}

func (this *WelfareMgr) Init() {
	if !model.GameParamData.UseEtcd {
		// 后台说现在没有不走ETCD情况~
	} else {

		EtcdMgrSington.InitSign7()

		EtcdMgrSington.InitTurnplate()

		EtcdMgrSington.InitBlindBox()

		EtcdMgrSington.InitFirstPay()

		EtcdMgrSington.InitContinuousPay()

		EtcdMgrSington.InitPhoneLottery()

	}
}

func (this *WelfareMgr) UpdateSign7(cfg *webapi_proto.Welfare7SignDateList) {
	this.Sign7[cfg.Platform] = cfg
}
func (this *WelfareMgr) UpdateTurnplate(cfg *webapi_proto.WelfareTurnplateDateList) {
	s := int32(0)
	if turnplate := this.Turnplate[cfg.Platform]; turnplate != nil {
		s = this.Turnplate[cfg.Platform].Switch
	}
	this.Turnplate[cfg.Platform] = cfg
	if s != 0 && s != cfg.Switch { // 打开关闭要广播给客户端
		this.WelfareClues(nil, cfg.Platform, OpTurnplate)
	}
}

func (this *WelfareMgr) UpdateBlindBox(cfg *webapi_proto.WelfareBlindBoxDataList) {
	s := int32(0)
	if blindBox := this.BlindBox[cfg.Platform]; blindBox != nil {
		s = this.BlindBox[cfg.Platform].Switch
	}
	this.BlindBox[cfg.Platform] = cfg
	if cfg.Cycle == WelfareOpen {
		this.BlindBoxCycle[cfg.Platform] = 1
	}
	if s != 0 && s != cfg.Switch { // 打开关闭要广播给客户端
		this.WelfareClues(nil, cfg.Platform, OpBlindBox)
	}
}

func (this *WelfareMgr) UpdateFirstPay(cfg *webapi_proto.WelfareFirstPayDataList) {
	s := int32(0)
	if firstPay := this.FirstPay[cfg.Platform]; firstPay != nil {
		s = this.FirstPay[cfg.Platform].Switch
	}
	this.FirstPay[cfg.Platform] = cfg
	if cfg.Cycle == WelfareOpen {
		this.FirstPayCycle[cfg.Platform] = 1
	}
	if s != 0 && s != cfg.Switch { // 打开关闭要广播给客户端
		this.WelfareClues(nil, cfg.Platform, OpFirstPay)
	}
}

func (this *WelfareMgr) UpdateContinuousPay(cfg *webapi_proto.WelfareContinuousPayDataList) {
	s := int32(0)
	if continuousPay := this.ContinuousPay[cfg.Platform]; continuousPay != nil {
		s = this.ContinuousPay[cfg.Platform].Switch
	}
	this.ContinuousPay[cfg.Platform] = cfg
	if cfg.Cycle == WelfareOpen {
		this.ContinuousPayCycle[cfg.Platform] = 1
	}
	if s != 0 && s != cfg.Switch { // 打开关闭要广播给客户端
		this.WelfareClues(nil, cfg.Platform, OpContinuousPay)
	}
}

func (this *WelfareMgr) UpdatePhoneLotteryStatus(cfg *webapi_proto.WelfarePhoneLotteryStatus) {
	this.PhoneLotteryStatus[cfg.Platform] = cfg
	s := int32(0)
	if phoneLotteryStatus := this.PhoneLotteryStatus[cfg.Platform]; phoneLotteryStatus != nil {
		s = this.PhoneLotteryStatus[cfg.Platform].Switch
	}
	this.PhoneLotteryStatus[cfg.Platform] = cfg
	if s != 0 && s != cfg.Switch { // 打开关闭要广播给客户端
		this.WelfareClues(nil, cfg.Platform, OpPhoneLottery)
	}

}
func (this *WelfareMgr) GetPhoneLotteryStatus(platform string) int32 {
	if this.PhoneLotteryStatus[platform] != nil {
		return this.PhoneLotteryStatus[platform].GetSwitch()
	}
	//测试代码
	return WelfareClose
}
func (this *WelfareMgr) OnDayChanged(player *Player) error {
	if player.WelfData != nil {
		player.WelfData.ReliefFundTimes = 0
		blindBox := this.BlindBox[player.Platform]
		//continuousPay := this.ContinuousPay[player.Platform]
		if blindBox != nil { // 关闭循环重置为-1
			if blindBox.Cycle == WelfareClose && player.WelfData.BlindBoxId != 0 {
				player.WelfData.BlindBoxId = -1
			} else { // 循环
				player.WelfData.BlindBoxId = 0
			}
		}
		//this.WelfareShowRed(player) //
		if !this.Welfareturnplate(player, 0) {
			player.SendShowRed(hall_proto.ShowRedCode_Welfare, 0, 1) // 0 轮盘红点
		}

		// 同步救济金次数
		pack := &welfare.SCGetReliefFund{
			OpRetCode: welfare.OpResultCode_OPRC_Sucess,
			Times:     player.WelfData.ReliefFundTimes,
			Coin:      -1, // 更新剩余次数
		}
		player.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETRELIEFFUND), pack)
		logger.Logger.Tracef("OnDayChanged SCGetReliefFund snid: %v pack: %v", player.SnId, pack)
	}
	return nil
}

func (this *WelfareMgr) MonitorWelfData(player *Player) {

	if player.WelfData == nil {
		player.WelfData = &model.WelfareData{
			Sign7:  &model.NewSignData{},
			VIPBag: make(map[int32]map[int32]int32),
		}
	} else if player.WelfData.Sign7 == nil {
		player.WelfData.Sign7 = &model.NewSignData{}
	} else if player.WelfData.VIPBag == nil {
		player.WelfData.VIPBag = make(map[int32]map[int32]int32)
	}
}

func (this *WelfareMgr) GetTurnplate(p *Player) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCGetTurnplate{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	turnplate := this.Turnplate[p.Platform]
	sign7 := this.Sign7[p.Platform]
	if turnplate != nil && sign7 != nil {
		if turnplate.Switch != WelfareOpen {
			logger.Logger.Tracef("GetTurnplate Switch err  p.SnId = %v %v", p.SnId, turnplate.Switch)
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
			return
		}

		if len(turnplate.RateList) != len(sign7.List) || len(turnplate.List) == 0 {
			logger.Logger.Tracef("GetTurnplate turnplate.List err  p.SnId = %v %v %v", p.SnId, len(turnplate.List), len(turnplate.RateList))
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
			return
		} else {
			for _, v := range turnplate.RateList {
				if len(turnplate.List) != len(v.Rate) { // 概率和转盘奖励不等
					logger.Logger.Tracef("GetTurnplate turnplate.RateList err  p.SnId = %v %v", p.SnId, len(turnplate.List))
					p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
					return
				}
			}
		}

		diff := p.WelfData.Sign7.SignIndex % int32(len(turnplate.RateList))

		if diff >= int32(len(turnplate.RateList)) {
			logger.Logger.Tracef("GetTurnplate turnplate.List err  p.SnId = %v %v %v", p.SnId, len(turnplate.List), len(turnplate.RateList))
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
			return
		}

		ts := time.Now().Unix()

		// 查看是否已经领取
		dif := common.DiffDaybyTs(ts, p.WelfData.Sign7.SignTickets)
		if dif == 0 { // 当天已经领取
			logger.Logger.Tracef("GetTurnplate LastTickets is repeat p.SnId = %v  %v %v", p.SnId, p.WelfData.Sign7.SignTickets, diff)
			pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
			return
		}

		var drawdates []*webapi_proto.WelfareDate
		for _, v := range sign7.List {
			if v.Day == diff+1 { // 找到对应天数
				drawdates = append(drawdates, v.Date...) // 领取原始奖励

				rand := turnplate.RateList[diff].Rate        // 找到对应天数概率
				idx := common.RandSliceIndexByWight31N(rand) // 获取奖励下标
				datas := turnplate.List[idx]

				drawdates = append(drawdates, datas.Date...) // 领取转盘奖励

				p.WelfData.Sign7.SignTickets = ts // 签到
				if len(p.WelfData.Sign7.TurnplateIdx) >= len(turnplate.RateList) {
					p.WelfData.Sign7.TurnplateIdx = nil
				}
				p.WelfData.Sign7.TurnplateIdx = append(p.WelfData.Sign7.TurnplateIdx, int32(idx)) // 获取领取转盘下标
				p.WelfData.Sign7.SignIndex += 1
				// 转盘
				gainWay := int32(common.GainWay_ActTurnplate)
				oper, remark := "system", "轮盘奖励"
				DrawWelfareDate(datas.Date, p, gainWay, oper, remark, false) // 领取奖励
				// 签到
				gainWay = int32(common.GainWay_ActSignNew)
				oper, remark = "system", "新七日签到"
				DrawWelfareDate(v.Date, p, gainWay, oper, remark, false) // 领取奖励

				for _, d := range drawdates {
					pack.Date = append(pack.Date, &welfare.WelfareDate{
						Grade:   d.Grade,
						Type:    d.Type,
						Name:    d.Name,
						Item_Id: d.Item_Id,
					})
				}
				pack.Idx = int32(idx)
				pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
				hadSign := p.WelfData.Sign7.SignIndex % int32(len(turnplate.RateList))
				if hadSign == 0 {
					hadSign = int32(len(turnplate.RateList))
				}
				pack.SignDay = hadSign // 已签到天数
				break
			}
		}

	}
	logger.Logger.Tracef("GetTurnplate  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
}

func (this *WelfareMgr) GetTurnplteVideo(p *Player) {
	pack := &welfare.SCGetTurnplate{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
		IsVideo:   true,
	}

	send := func() {
		logger.Logger.Tracef("GetTurnplate  snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
	}

	turn := this.Turnplate[p.Platform] // 转盘
	sign7 := this.Sign7[p.Platform]    // 签到
	if turn == nil || sign7 == nil {
		send()
		return
	}

	if turn.Switch != WelfareOpen {
		logger.Logger.Tracef("GetTurnplate Switch err  p.SnId = %v %v", p.SnId, turn.Switch)
		p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
		return
	}

	if len(turn.RateList) != len(sign7.List) || len(turn.List) == 0 {
		logger.Logger.Tracef("GetTurnplate turn.List err  p.SnId = %v %v %v", p.SnId, len(turn.List), len(turn.RateList))
		p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
		return
	} else {
		for _, v := range turn.RateList {
			if len(turn.List) != len(v.Rate) { // 概率和转盘奖励不等
				logger.Logger.Tracef("GetTurnplate turn.RateList err  p.SnId = %v %v", p.SnId, len(turn.List))
				p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
				return
			}
		}
	}

	// 看视频奖励只能当天领，在签到之后
	ts := time.Now().Unix()
	// 查看是否已经领取
	diff := common.DiffDaybyTs(ts, p.WelfData.Sign7.SignTickets)
	if diff != 0 { // 当天没签到，需要先签到
		logger.Logger.Tracef("GetTurnplate LastTickets is repeat p.SnId = %v  %v %v", p.SnId, p.WelfData.Sign7.SignTickets, diff)
		pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
		p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
		return
	}

	// 判断是否已经领取过
	diff = common.DiffDaybyTs(ts, p.WelfData.Sign7.VideoTicket)
	if diff == 0 { // 已经领取过了
		logger.Logger.Tracef("GetTurnplate VideoTicket is repeat p.SnId = %v  %v %v", p.SnId, p.WelfData.Sign7.VideoTicket, diff)
		pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
		p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
		return
	}

	// 可以领取
	p.WelfData.Sign7.VideoTicket = ts
	index := p.WelfData.Sign7.SignIndex % int32(len(turn.RateList))
	var drawdates []*webapi_proto.WelfareDate
	for _, v := range sign7.List {
		if v.Day == index { // 找到对应天数
			idx := p.WelfData.Sign7.TurnplateIdx[len(p.WelfData.Sign7.TurnplateIdx)-1]
			drawdates = append(drawdates, v.Date...) // 签到奖励
			datas := turn.List[idx]
			drawdates = append(drawdates, datas.Date...) // 转盘奖励

			// 转盘
			gainWay := int32(common.GainWay_ActTurnplate2)
			oper, remark := "system", "轮盘奖励"
			DrawWelfareDate(datas.Date, p, gainWay, oper, remark, true) // 领取奖励
			// 签到
			gainWay = int32(common.GainWay_ActSignNew2)
			oper, remark = "system", "新七日签到"
			DrawWelfareDate(v.Date, p, gainWay, oper, remark, true) // 领取奖励

			for _, d := range drawdates {
				coin := d.Grade * 2
				if d.Type == 1 { // 蝶女金币加成
					roleGirl := PetMgrSington.GetRoleInfo(p, 2000001)
					if roleGirl != nil && roleGirl.Level > 0 {
						coin = int32(float64(coin) * float64(100+roleGirl.Award) / 100.0)
					}
				}
				pack.Date = append(pack.Date, &welfare.WelfareDate{
					Grade:   coin,
					Type:    d.Type,
					Name:    d.Name,
					Item_Id: d.Item_Id,
				})
			}
			pack.Idx = idx
			pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
			hadSign := p.WelfData.Sign7.SignIndex % int32(len(turn.RateList))
			if hadSign == 0 {
				hadSign = int32(len(turn.RateList))
			}
			pack.SignDay = hadSign // 已签到天数
			TaskSubjectSingleton.Touch(common.TaskTypeAdv, &TaskData{
				SnId: p.SnId,
				Num:  1,
			})
			break
		}
	}

	logger.Logger.Tracef("GetTurnplate  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETTURNPLATE), pack)
}

// isVideo 看视频了，计算看视频加成
func DrawWelfareDate(dates []*webapi_proto.WelfareDate, p *Player, gainWay int32, oper, remark string, isVideo bool) {
	// 注意dates只能读，不能写
	for _, v := range dates {
		switch v.Type {
		case 1: //金币
			coin := int64(v.Grade)
			add := int64(0)
			if isVideo {
				roleGirl := PetMgrSington.GetRoleInfo(p, 2000001)
				if roleGirl != nil && roleGirl.Level > 0 /*|| !role.IsUsing*/ {
					//蝶女加成
					add = int64(float64(coin) * float64(roleGirl.Award) * 2 / 100.0)
				}
				coin = coin*2 + add
			}

			p.AddCoin(coin, add, gainWay, oper, remark)
			giveType := int32(-1)
			switch gainWay {
			case common.GainWay_VIPGift: //vip礼包
				giveType = model.SystemFreeGive_GiveType_VipGift
			case common.GainWay_ActTurnplate: //转盘
				giveType = model.SystemFreeGive_GiveType_ActTurnplate
			case common.GainWay_ActSignNew:
				if remark == "新七日签到" {
					giveType = model.SystemFreeGive_GiveType_ActSign
				} else { //累签
					giveType = model.SystemFreeGive_GiveType_ActContinuousSign
				}
			}
			if giveType != -1 {
				LogChannelSingleton.WriteMQData(model.GenerateSystemFreeGive(p.SnId, p.Name, p.Platform, giveType, model.SystemFreeGive_CoinType_Coin, int64(coin)))
			}
		case 2: //钻石
			p.AddDiamond(int64(v.Grade), 0, gainWay, oper, remark)
			giveType := int32(-1)
			switch gainWay {
			case common.GainWay_VIPGift:
				giveType = model.SystemFreeGive_GiveType_VipGift
			case common.GainWay_ActTurnplate:
				giveType = model.SystemFreeGive_GiveType_ActTurnplate
			case common.GainWay_ActSignNew:
				if remark == "新七日签到" {
					giveType = model.SystemFreeGive_GiveType_ActSign
				} else { //累签
					giveType = model.SystemFreeGive_GiveType_ActContinuousSign
				}
			}
			if giveType != -1 {
				LogChannelSingleton.WriteMQData(model.GenerateSystemFreeGive(p.SnId, p.Name, p.Platform, giveType, model.SystemFreeGive_CoinType_Diamond, int64(v.Grade)))
			}
		case 3: //道具
			if v.Grade > 0 {
				item := &Item{
					ItemId:  v.Item_Id,
					ItemNum: int64(v.Grade),
				}
				BagMgrSingleton.AddJybBagInfo(p, []*Item{item}, 0, gainWay, oper, remark)
				itemData := srvdata.PBDB_GameItemMgr.GetData(item.ItemId)
				if itemData != nil {
					BagMgrSingleton.RecordItemLog(p.Platform, p.SnId, ItemObtain, item.ItemId, itemData.Name, item.ItemNum, remark)
				}
			}
		}
	}
}

func (this *WelfareMgr) GetAddupSign(p *Player, addupday int32) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCGetAddupSign{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	turnplate := this.Turnplate[p.Platform]
	sign7 := this.Sign7[p.Platform]
	if turnplate != nil && sign7 != nil {
		if turnplate.Switch != WelfareOpen {
			logger.Logger.Tracef("Get7Sign Switch err  p.SnId = %v %v", p.SnId, turnplate.Switch)
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETADDUPSIGN), pack)
			return
		}
		signIndex := p.WelfData.Sign7.SignIndex

		if addupday > signIndex || addupday > int32(len(sign7.List)) || addupday < 1 { // 累计签到不够 或者超过签到上限 或者非法输入
			logger.Logger.Tracef("Get7Sign Sign7.SignIndex is repeat p.SnId = %v  %v  %v", p.SnId, signIndex, addupday)
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETADDUPSIGN), pack)
			return
		}

		for _, v := range p.WelfData.Sign7.AddupIndex {
			if v == addupday { // 已经领取
				pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
				logger.Logger.Tracef("Get7Sign Sign7.AddupIndex is repeat p.SnId = %v  %v", p.SnId, addupday)
				p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETADDUPSIGN), pack)
				return
			}
		}
		flag := false
		for _, v := range sign7.List {
			for _, d := range v.AddUpDate { // 累计奖励
				if d.AddUpDay != addupday {
					continue
				}
				p.WelfData.Sign7.AddupIndex = append(p.WelfData.Sign7.AddupIndex, addupday) // 签到
				ad := &welfare.AddUpWelfareDate{
					AddUpDay: d.AddUpDay,
				}
				for _, d1 := range d.AddUpDate {
					ad.AddUpDate = append(ad.AddUpDate, &welfare.WelfareDate{
						Grade:   d1.Grade,
						Type:    d1.Type,
						Name:    d1.Name,
						Item_Id: d1.Item_Id,
					})
				}
				pack.Date = append(pack.Date, ad)
				pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
				pack.AddUpSignDay = append(pack.AddUpSignDay, p.WelfData.Sign7.AddupIndex...)
				gainWay := int32(common.GainWay_ActSignNew)
				oper, remark := "system", fmt.Sprintf("累计%v天签到", addupday)
				DrawWelfareDate(d.AddUpDate, p, gainWay, oper, remark, false) // 领取奖励
				flag = true
				break
			}
			if flag {
				break
			}
		}
	}
	logger.Logger.Tracef("GetAddupSign  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETADDUPSIGN), pack)
}

func (this *WelfareMgr) WelfaredInfo(p *Player) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCWelfaredInfo{}
	diff := 0
	ts := time.Now().Unix()
	turnplate := this.Turnplate[p.Platform]
	sign7 := this.Sign7[p.Platform]
	if turnplate != nil && sign7 != nil {
		pack.Switch = turnplate.Switch
		if turnplate.Switch != WelfareClose {
			pack.DrawTurnplate = 2
			signIndex := p.WelfData.Sign7.SignIndex % int32(len(turnplate.RateList))

			diff = common.DiffDaybyTs(ts, p.WelfData.Sign7.SignTickets)
			if diff == 0 || signIndex >= int32(len(turnplate.RateList)) { // 已经领取 或者全部领取
				pack.DrawTurnplate = 1
			}

			for _, v := range turnplate.List {
				data := &welfare.WelfareTurnplateDate{
					Id: v.Id,
				}
				for _, d := range v.Date {
					data.Date = append(data.Date, &welfare.WelfareDate{
						Grade:   d.Grade,
						Type:    d.Type,
						Name:    d.Name,
						Item_Id: d.Item_Id,
					})
				}
				pack.Tlist = append(pack.Tlist, data)
			}

			for _, v := range sign7.List {

				data := &welfare.Welfare7SignDate{
					Day: v.Day,
				}
				for _, d := range v.Date {
					data.Date = append(data.Date, &welfare.WelfareDate{
						Grade:   d.Grade,
						Type:    d.Type,
						Name:    d.Name,
						Item_Id: d.Item_Id,
					})
				}
				for _, d := range v.AddUpDate { // 累计奖励
					ad := &welfare.AddUpWelfareDate{
						AddUpDay: d.AddUpDay,
					}
					for _, d1 := range d.AddUpDate {
						ad.AddUpDate = append(ad.AddUpDate, &welfare.WelfareDate{
							Grade:   d1.Grade,
							Type:    d1.Type,
							Name:    d1.Name,
							Item_Id: d1.Item_Id,
						})
					}
					data.AddUpDate = append(data.AddUpDate, ad)
				}
				pack.Slist = append(pack.Slist, data)
			}
			pack.TurnplateIdx = append(pack.TurnplateIdx, p.WelfData.Sign7.TurnplateIdx...)
			//需要判断是要显示7 还是显示0
			if signIndex == 0 {
				if pack.DrawTurnplate == 1 {
					signIndex = int32(len(turnplate.RateList))
				}
			}
			pack.SignDay = signIndex
			pack.AddUpSignDay = append(pack.AddUpSignDay, p.WelfData.Sign7.AddupIndex...)
		}
	}
	logger.Logger.Tracef("WelfaredInfo  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_WELFAREINFO), pack)
}

func (this *WelfareMgr) WelfareClues(p *Player, platform string, op int) {

	pack := &player_proto.SCEasyWelfaredInfo{}
	// 0转盘1盲盒2首冲3连续充值
	turnplate := this.Turnplate[platform]
	if turnplate != nil {
		if op == OpAll || op == OpTurnplate {
			if turnplate.Switch == WelfareOpen && p != nil && this.Welfareturnplate(p, 1) { // 没有关闭且所有奖励已经领取
				pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) //关闭
			} else {
				pack.WelfareSwitch = append(pack.WelfareSwitch, turnplate.Switch)
			}
		} else { // 不更新
			pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareNil)
		}
	} else {
		pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) // 配置nil就是关闭
	}

	blindBox := this.BlindBox[platform]
	if blindBox != nil {
		if op == OpAll || op == OpBlindBox {
			if blindBox.Switch == WelfareOpen && blindBox.Cycle == WelfareClose && p != nil && p.WelfData.BlindBoxId != 0 { // 没有关闭且所有奖励已经领取
				pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) //关闭
			} else {
				pack.WelfareSwitch = append(pack.WelfareSwitch, blindBox.Switch)
			}
		} else { // 不更新
			pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareNil)
		}
	} else {
		pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) // 配置nil就是关闭
	}

	firstPay := this.FirstPay[platform]
	if firstPay != nil {
		if op == OpAll || op == OpFirstPay {
			ln := len(firstPay.List)
			max := firstPay.List[ln-1].Day                                                                                     // 正序
			if firstPay.Switch == WelfareOpen && firstPay.Cycle == WelfareClose && p != nil && p.WelfData.FirstPayDay >= max { // 没有关闭且所有奖励已经领取
				pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) //关闭
			} else {
				pack.WelfareSwitch = append(pack.WelfareSwitch, firstPay.Switch)
			}
		} else { // 不更新
			pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareNil)
		}
	} else {
		pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) // 配置nil就是关闭
	}

	continuousPay := this.ContinuousPay[platform]
	if continuousPay != nil {
		if op == OpAll || op == OpContinuousPay {
			ln := len(continuousPay.List)
			max := continuousPay.List[ln-1].Day                                                                                               // 正序
			if continuousPay.Switch == WelfareOpen && continuousPay.Cycle == WelfareClose && p != nil && p.WelfData.ContinuousPayDay >= max { // 没有关闭且所有奖励已经领取
				pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) //关闭
			} else {
				pack.WelfareSwitch = append(pack.WelfareSwitch, continuousPay.Switch)
			}
		} else { // 不更新
			pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareNil)
		}
	} else {
		pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose) // 配置nil就是关闭
	}
	//抽手机活动开关
	if this.PhoneLotteryStatus[platform] != nil {
		phoneLotterySwitch := this.PhoneLotteryStatus[platform].Switch
		pack.WelfareSwitch = append(pack.WelfareSwitch, phoneLotterySwitch) //抽手机活动开关
	} else {
		pack.WelfareSwitch = append(pack.WelfareSwitch, WelfareClose)
	}
	if p != nil {
		logger.Logger.Tracef("WelfareClues  snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(player_proto.PlayerPacketID_PACKET_SC_SWELFAREINFO), pack)
	} else {
		logger.Logger.Tracef("WelfareClues to Platform pack: %v", pack)
		PlayerMgrSington.BroadcastMessageToPlatform(platform, int(player_proto.PlayerPacketID_PACKET_SC_SWELFAREINFO), pack)
	}
}

func (this *WelfareMgr) Welfareturnplate(p *Player, op int32) bool { // 0 红点提示 1全部领取
	var isShow bool
	turnplate := this.Turnplate[p.Platform]
	sign7 := this.Sign7[p.Platform]
	if turnplate != nil && sign7 != nil {
		if turnplate.Switch == WelfareClose {
			return true
		}
		diff := 0
		ts := time.Now().Unix()
		signIndex := p.WelfData.Sign7.SignIndex % int32(len(turnplate.RateList))

		diff = common.DiffDaybyTs(ts, p.WelfData.Sign7.SignTickets)
		if diff == 0 || signIndex >= int32(len(turnplate.RateList)) { // 已经领取 或者全部领取
			isShow = true
			if op == 1 && signIndex < int32(len(turnplate.RateList)) { // 没有领完
				isShow = false
			}
		}

		if isShow { // 当日已经领取 查看累计奖励是否领取
			var addUpDate []int32
			for _, v := range sign7.List {

				for _, d := range v.AddUpDate { // 累计奖励
					addUpDate = append(addUpDate, d.AddUpDay)
				}
			}
			signIndex := p.WelfData.Sign7.SignIndex
			for _, addupday := range addUpDate {
				if addupday <= signIndex {
					falg := false
					for _, v := range p.WelfData.Sign7.AddupIndex {
						if v == addupday { // 已经领取
							falg = true
							break
						}
					}
					if !falg {
						isShow = false // 有未领取每日奖励
						break
					}

				}
			}
		}

	}
	return isShow
}

func (this *WelfareMgr) WelfareShowRed(p *Player) {
	if p == nil {
		return
	}
	this.MonitorWelfData(p) // 登录检测
	this.WelfareClues(p, p.Platform, OpAll)

	if !this.Welfareturnplate(p, 0) {
		p.SendShowRed(hall_proto.ShowRedCode_Welfare, 0, 1) // 0 轮盘红点
	}

}

func (this *WelfareMgr) BlindBoxInfo(p *Player, bid int32) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCBlindBoxInfo{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	blindBox := this.BlindBox[p.Platform]
	if blindBox != nil {
		if blindBox.Switch != WelfareOpen {
			logger.Logger.Tracef("BlindBoxInfo Switch err  p.SnId = %v %v", p.SnId, blindBox.Switch)
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_BLINBOXINFO), pack)
			return
		}
		ln := len(blindBox.List)
		if ln < 2 { // 一个以上
			logger.Logger.Tracef("BlindBoxInfo blindBox.List err  p.SnId = %v %v", p.SnId, ln)
			p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_BLINBOXINFO), pack)
			return
		}

		pack.MinId = blindBox.MinId
		pack.Draw = 1
		cyc := this.BlindBoxCycle[p.Platform]
		if p.WelfData.BlindBoxId == -1 {
			if cyc == 1 || blindBox.Cycle == WelfareOpen {
				p.WelfData.BlindBoxId = 0
			}
		} // == 1代表当日循环
		if p.WelfData.BlindBoxId == 0 { // 未领取过发随机Date

			idx := bid
			num := 0
			for int32(idx) == bid { // 不相等跳出 ln>1 不会死循环
				idx = int32(common.RandInt(ln)) + 1
				if num > 100 {
					break
				}
				num++
			}
			data := blindBox.List[idx-1]
			pack.Draw = 2
			pack.Date = &welfare.BlindBoxData{
				Id:       data.Id,
				Type:     data.Type,
				Name:     data.Name,
				Grade:    data.Grade,
				Consume:  data.Consume,
				Price1:   data.Price1,
				Price2:   data.Price2,
				Discount: data.Discount,
				//Item_Id: data.Item_Id, 目前未使用
			}
		}

		pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
		pack.Cycle = blindBox.Cycle
	}
	logger.Logger.Tracef("BlindBoxInfo  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_BLINBOXINFO), pack)
}

func (this *WelfareMgr) RecordWelfareLog(p *Player, num, takenum, discount int64, day, gainWay, wtype int32, item []*model.WelfareItem, oper, remark string) {

	log := model.NewWelfareLogEx(p.SnId, num, takenum, p.Coin, p.Diamond, discount, day,
		p.Ver, gainWay, wtype, item, oper, remark, p.Platform, p.Channel,
		p.BeUnderAgentCode, p.PackageID)

	if log != nil {
		//logger.Logger.Trace("RecordItemLog 开始记录 道具操作")
		LogChannelSingleton.WriteLog(log)
	}
}

func (this *WelfareMgr) BuyBlindBox(p *Player, buyid, ConfigPayId int32) {
	// this.MonitorWelfData(p)
	//pack := &welfare.SCGetBlindBox{
	//	OpRetCode: welfare.OpResultCode_OPRC_Error,
	//}
	pack := &shop.SCPayInfo{
		RetCode: shop.OpResultCode_OPRC_Error,
	}
	blindBox := this.BlindBox[p.Platform]
	if blindBox == nil {
		logger.Logger.Tracef("BuyBlindBox blindBox==nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	if blindBox.Switch != WelfareOpen {
		logger.Logger.Tracef("BuyBlindBox Switch err  p.SnId = %v %v", p.SnId, blindBox.Switch)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}

	if p.WelfData.BlindBoxId != 0 { // 已经领取
		logger.Logger.Tracef("BuyBlindBox BlindBoxId is  repeat = %v %v", p.SnId, p.WelfData.BlindBoxId)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	var bbd *webapi_proto.BlindBoxData
	for _, v := range blindBox.List {
		if v.Id == buyid {
			bbd = v
			//if v.Consume == ConsumeDiamond {
			//if p.Diamond < v.Price2 {
			//	logger.Logger.Tracef("BuyBlindBox Diamond < Price2  p.SnId = %v  %v  %v", p.SnId, p.Diamond, v.Price2)
			//	pack.OpRetCode = welfare.OpResultCode_OPRC_ErrCoin
			//	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETBLINBOX), pack)
			//	return
			//}
			//p.WelfData.BlindBoxId = v.Id
			//gainWay := int32(common.GainWay_ActBlindBox)
			//oper, remark := "system", "购买盲盒"
			//p.AddDiamond(-v.Price2, gainWay, oper, remark) // 消耗
			//oper, remark = "system", "盲盒奖励"
			//switch v.Type { // 增加
			//case 1: //金币
			//	p.AddCoin(int64(v.Grade), gainWay, oper, remark)
			//case 2: //钻石
			//	p.AddDiamond(int64(v.Grade), gainWay, oper, remark)
			//}
			//
			//// 记录
			//item := []*model.WelfareItem{&model.WelfareItem{
			//	Num:    int64(v.Grade),
			//	ItemId: v.Item_Id,
			//	Type:   v.Type,
			//}}
			//this.RecordWelfareLog(p, int64(v.Grade), v.Price2, int64(v.Discount*10000), 0, gainWay, model.WelfareBuyBlindBox,
			//	item, oper, remark)
			//pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
			//break
			//}

			//if v.Consume != ConsumeDiamond { // 非钻石支付需要接三方 不能走这里判断
			//	logger.Logger.Tracef("BuyBlindBox Switch err  p.SnId = %v %v", p.SnId, blindBox.Switch)
			//	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_GETBLINBOX), pack)
			//	return
			//}
		}
	}
	if bbd == nil {
		logger.Logger.Tracef("BuyBlindBox bbd == nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	ShopMgrSington.SendAPICreateOrder(p, ConfigPayId, bbd, "BlindBox")
	////三方购买
	//task.New(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
	//	var amount [3]int32
	//	if bbd.Type == 1 {
	//		//金币
	//		amount[0] = bbd.Grade
	//	} else if bbd.Type == 2 {
	//		//钻石
	//		amount[1] = bbd.Grade
	//	}
	//	dbShop := model.NewDbShop(p.Platform, 0, amount[:], Shop_Consume_Money, int32(bbd.Price2), nil, 0, "",
	//		p.SnId, 0, "BlindBox")
	//	err := model.InsertDbShopLog(dbShop)
	//	if err != nil {
	//		logger.Logger.Errorf("model.InsertDbShopLog err:", err)
	//		return nil
	//	}
	//	return webapi.API_CreateOrder(common.GetAppId(), dbShop.LogId.Hex(), ConfigPayId, p.SnId, 0, p.Platform, p.PackageID, p.DeviceOS,
	//		p.DeviceId, bbd.Name, amount, int32(bbd.Price2), nil)
	//}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
	//	logger.Logger.Trace("API_CreateOrder_BuyBlindBox:", data)
	//	info := data.(*webapi_proto.ASCreateOrder)
	//	if info == nil || info.Tag != 0 {
	//		//失败
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	} else {
	//		pack.RetCode = shop.OpResultCode_OPRC_Sucess
	//		pack.Url = info.Url
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	}
	//}), "API_CreateOrder_BuyBlindBox").Start()
}

func (this *WelfareMgr) FirstPayInfo(p *Player) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCWelfareFirstPayData{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	firstPay := this.FirstPay[p.Platform]
	if firstPay != nil {
		pack.Switch = firstPay.Switch
		if firstPay.Switch != WelfareClose {
			ln := len(firstPay.List)
			if ln == 0 { // 不能为空
				logger.Logger.Tracef("FirstPayInfo firstPay.List err  p.SnId = %v %v", p.SnId, ln)
				p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_FIRSTPAYINFO), pack)
				return
			}

			ts := time.Now().Unix()
			day := p.WelfData.FirstPayDay
			pack.Draw = 2
			if day != 0 { // 查看是否已经领取
				dif := common.DiffDaybyTs(ts, p.WelfData.FirstPayTickets)
				if dif == 0 { // 当天已经领取
					pack.Draw = 1
				}
			}

			max := firstPay.List[ln-1].Day // 正序
			cyc := this.FirstPayCycle[p.Platform]
			if pack.Draw == 2 { // 当天未领取判断
				if day >= max {
					if firstPay.Cycle != WelfareOpen && cyc != 1 { // 全部领取完就发最后一天
						day = max
						pack.Draw = 1 // 不循环 且今日无开启循环操作 领完不能再领取了
					} else {
						// p.WelfData.FirstPayDay = 0 // 循环
						day = firstPay.List[0].Day // 从第一天开始
					}
				} else if day == 0 {
					day = firstPay.List[0].Day
				}
			}
			pack.Cycle = firstPay.Cycle
			MoneyRatio := float64(0)
			if vips := VipMgrSington.GetVIPcfg(p.Platform); vips != nil {
				MoneyRatio = vips.MoneyRatio
			}
			for _, v := range firstPay.List {
				if v.Day == day {
					vipEx := v.VIPEX
					if MoneyRatio > 0.000001 {
						vipEx = int32(float64(v.Price2) * MoneyRatio)
					}
					pack.List = &welfare.WelfareSpree{
						Day:      v.Day,
						VIPEX:    vipEx,
						Consume:  v.Consume,
						Price1:   v.Price1,
						Price2:   v.Price2,
						Discount: v.Discount,
					}
					for _, it := range v.Item {
						pack.List.Item = append(pack.List.Item, &welfare.WelfareDate{
							Grade:   it.Grade,
							Type:    it.Type,
							Name:    it.Name,
							Item_Id: it.Item_Id,
						})
					}
					pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
					break
				}
			}

		}
	}
	logger.Logger.Tracef("FirstPayInfo  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_FIRSTPAYINFO), pack)
}

// 默认已经成功
func (this *WelfareMgr) BuyFirstPay(p *Player, ConfigPayId int32) {
	// this.MonitorWelfData(p)
	//pack := &welfare.SCWelfareFirstPay{
	//	OpRetCode: welfare.OpResultCode_OPRC_Error,
	//}
	pack := &shop.SCPayInfo{
		RetCode: shop.OpResultCode_OPRC_Error,
	}
	firstPay := this.FirstPay[p.Platform]
	if firstPay == nil {
		logger.Logger.Errorf("BuyFirstPay firstPay == nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	ts := time.Now().Unix()

	if p.WelfData.FirstPayDay != 0 { // 查看是否已经领取
		dif := common.DiffDaybyTs(ts, p.WelfData.FirstPayTickets)
		if dif == 0 { // 当天已经领取
			logger.Logger.Errorf("BuyFirstPay LastTickets is repeat p.SnId = %v  %v", p.SnId, p.WelfData.FirstPayTickets)
			//pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
			p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
			return
		}
	}

	ln := len(firstPay.List)
	if ln == 0 { // 不能为空
		logger.Logger.Errorf("BuyFirstPay firstPay.List err  p.SnId = %v %v", p.SnId, ln)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	max := firstPay.List[ln-1].Day // 正序

	if p.WelfData.FirstPayDay >= max {
		cyc := this.FirstPayCycle[p.Platform]
		if firstPay.Cycle != WelfareOpen && cyc != 1 { // 全部领取完
			//pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
			logger.Logger.Tracef("BuyFirstPay Cycle  p.WelfData.FirstPayDay max  p.SnId = %v %v", p.SnId, firstPay.Cycle, p.WelfData.FirstPayDay, max)
			p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
			return
		}
		p.WelfData.FirstPayDay = 0
	}

	var wfs *webapi_proto.WelfareSpree

	for i, v := range firstPay.List {

		if v.Day == p.WelfData.FirstPayDay || p.WelfData.FirstPayDay == 0 {

			if p.WelfData.FirstPayDay != 0 { // 为0领取第一个 p.WelfData.FirstPayDay不为0代表已经领取到该礼包 需要领取下一个
				i++
			}
			wfs = v

			//data := firstPay.List[i] // 越界条件已判断
			//
			//p.WelfData.FirstPayDay = data.Day
			//p.WelfData.FirstPayTickets = ts
			//// TODO
			//p.AddMoneyPayTotal(v.Price2)
			//gainWay := int32(common.GainWay_ActFirstPay)
			//oper, remark := "system", "首充奖励"
			//DrawWelfareDate(data.Item, p, gainWay, oper, remark) // 领取奖励
			//var item []*model.WelfareItem
			//for _, v := range data.Item {
			//	item = append(item, &model.WelfareItem{
			//		Num:    int64(v.Grade),
			//		ItemId: v.Item_Id,
			//		Type:   v.Type,
			//	})
			//}
			//MoneyRatio := float64(0)
			//if vips := VipMgrSington.GetVIPcfg(p.Platform); vips != nil {
			//	MoneyRatio = vips.MoneyRatio
			//}
			//vipEx := int64(data.VIPEX)
			//if MoneyRatio > 0.000001 {
			//	vipEx = int64(float64(v.Price2) * MoneyRatio)
			//}
			//this.RecordWelfareLog(p, vipEx, v.Price2, int64(v.Discount*10000), p.WelfData.FirstPayDay, gainWay, model.WelfareBuyFirstPay,
			//	item, oper, remark)
			//
			//pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
			break
		}
	}
	if wfs == nil || wfs.Item == nil {
		logger.Logger.Errorf("BuyFirstPay fwfs == nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	ShopMgrSington.SendAPICreateOrder(p, ConfigPayId, wfs, "FirstRecharge")
	////三方购买
	//task.New(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
	//	var amount [3]int32
	//	for _, it := range wfs.Item {
	//		if it.Type == 1 {
	//			amount[0] = it.Grade
	//		} else if it.Type == 2 {
	//			amount[1] = it.Grade
	//		}
	//	}
	//	dbShop := model.NewDbShop(p.Platform, 0, amount[:], Shop_Consume_Money, int32(wfs.Price2),
	//		nil, 0, "", p.SnId, 0, "FirstRecharge")
	//	err := model.InsertDbShopLog(dbShop)
	//	if err != nil {
	//		logger.Logger.Errorf("model.InsertDbShopLog err:", err)
	//		return nil
	//	}
	//	return webapi.API_CreateOrder(common.GetAppId(), dbShop.LogId.Hex(), ConfigPayId, p.SnId, 0, p.Platform, p.PackageID, p.DeviceOS,
	//		p.DeviceId, "FirstRecharge", amount, int32(wfs.Price2), nil)
	//}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
	//	logger.Logger.Trace("API_CreateOrder_BuyFirstPay:", data)
	//	info := data.(*webapi_proto.ASCreateOrder)
	//	if info == nil || info.Tag != 0 {
	//		//失败
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	} else {
	//		pack.RetCode = shop.OpResultCode_OPRC_Sucess
	//		pack.Url = info.Url
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	}
	//}), "API_CreateOrder_BuyFirstPay").Start()
}

func (this *WelfareMgr) ContinuousPayInfo(p *Player) {
	// this.MonitorWelfData(p)
	pack := &welfare.SCWelfareContinuousPayData{
		OpRetCode: welfare.OpResultCode_OPRC_Error,
	}
	continuousPay := this.ContinuousPay[p.Platform]
	if continuousPay != nil {
		pack.Switch = continuousPay.Switch
		if continuousPay.Switch != WelfareClose {
			ln := len(continuousPay.List)
			if ln == 0 { // 不能为空
				logger.Logger.Tracef("ContinuousPayInfo continuousPay.List err  p.SnId = %v %v", p.SnId, ln)
				p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_FIRSTPAYINFO), pack)
				return
			}

			ts := time.Now().Unix()
			day := p.WelfData.ContinuousPayDay
			max := continuousPay.List[ln-1].Day // 正序
			pack.Draw = 2
			if day != 0 { // 查看是否已经领取
				dif := common.DiffDaybyTs(ts, p.WelfData.ContinuousPayTickets)
				if dif == 0 { // 当天已经领取
					pack.Draw = 1
				} else if continuousPay.Break == WelfareOpen && dif > 1 && p.WelfData.ContinuousPayDay < max { // 开启中断
					day = 0 //continuousPay.List[0].Day // 从头开始
				}
			}

			if pack.Draw == 2 { // 当天未领取判断
				cyc := this.ContinuousPayCycle[p.Platform]
				for i, v := range continuousPay.List {
					if v.Day == day || day == 0 || day >= max {
						if day != 0 { // 为0领取第一个 day不为0代表已经领取到该礼包 需要领取下一个
							i++
						}
						if day >= max {
							i = ln
						}
						if i < ln {
							day = continuousPay.List[i].Day
						} else {
							if continuousPay.Cycle != WelfareOpen && cyc != 1 { // 全部领取完就发最后一天
								day = max
								pack.Draw = 1 // 不循环 领完不能再领取了
							} else {
								day = continuousPay.List[0].Day // 从第一天开始
							}
						}
						break
					}
				}

			}
			pack.Day = day
			pack.Cycle = continuousPay.Cycle
			for _, v := range continuousPay.List {

				data := &welfare.WelfareSpree{
					Day: v.Day,
					// VIPEX:    v.VIPEX,
					Consume:  v.Consume,
					Price1:   v.Price1,
					Price2:   v.Price2,
					Discount: v.Discount,
				}
				for _, it := range v.Item {
					data.Item = append(data.Item, &welfare.WelfareDate{
						Grade:   it.Grade,
						Type:    it.Type,
						Name:    it.Name,
						Item_Id: it.Item_Id,
					})
				}
				pack.List = append(pack.List, data)
			}
			pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
		}
	}
	logger.Logger.Tracef("ContinuousPayInfo  snid: %v pack: %v", p.SnId, pack)
	p.SendToClient(int(welfare.SPacketID_PACKET_SC_WELF_CONTINPAYINFO), pack)
}

// 默认已经成功
func (this *WelfareMgr) BuyContinuousPay(p *Player, ConfigPayId int32) {
	// this.MonitorWelfData(p)
	//pack := &welfare.SCWelfareContinuousPay{
	//	OpRetCode: welfare.OpResultCode_OPRC_Error,
	//}
	pack := &shop.SCPayInfo{
		RetCode: shop.OpResultCode_OPRC_Error,
	}
	continuousPay := this.ContinuousPay[p.Platform]
	if continuousPay == nil {
		logger.Logger.Tracef("BuyContinuousPay continuousPay == nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	ts := time.Now().Unix()

	ln := len(continuousPay.List)
	if ln == 0 { // 不能为空
		logger.Logger.Tracef("BuyContinuousPay firstPay.List err  p.SnId = %v %v", p.SnId, ln)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	max := continuousPay.List[ln-1].Day // 正序

	if p.WelfData.ContinuousPayDay != 0 { // 查看是否已经领取
		dif := common.DiffDaybyTs(ts, p.WelfData.ContinuousPayTickets)
		if dif == 0 { // 当天已经领取
			logger.Logger.Tracef("BuyContinuousPay LastTickets is repeat p.SnId = %v  %v", p.SnId, p.WelfData.ContinuousPayTickets)
			//pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
			p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
			return
		} else if continuousPay.Break == WelfareOpen && dif > 1 && p.WelfData.ContinuousPayDay < max { // 开启中断 且没有领取到最后一天
			p.WelfData.ContinuousPayDay = 0 // 从第一天开始
		}
	}

	if p.WelfData.ContinuousPayDay >= max {
		cyc := this.ContinuousPayCycle[p.Platform]
		if continuousPay.Cycle != WelfareOpen && cyc != 1 { // 全部领取完
			//pack.OpRetCode = welfare.OpResultCode_OPRC_NoTimes
			logger.Logger.Tracef("BuyContinuousPay Cycle  p.WelfData.FirstPayDay max  p.SnId = %v %v", p.SnId, continuousPay.Cycle, p.WelfData.ContinuousPayDay, max)
			p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
			return
		}
		p.WelfData.ContinuousPayDay = 0
	}
	var wfs *webapi_proto.WelfareSpree
	for i, v := range continuousPay.List {

		if v.Day == p.WelfData.ContinuousPayDay || p.WelfData.ContinuousPayDay == 0 {
			if p.WelfData.ContinuousPayDay != 0 { // 为0领取第一个 p.WelfData.FirstPayDay不为0代表已经领取到该礼包 需要领取下一个
				i++
			}
			wfs = v

			//data := continuousPay.List[i] // 越界条件已判断
			//
			//p.WelfData.ContinuousPayDay = data.Day
			//p.WelfData.ContinuousPayTickets = ts
			//// TODO
			//p.AddMoneyPayTotal(v.Price2)
			//gainWay := int32(common.GainWay_ActContinuousPay)
			//oper, remark := "system", "连续充值奖励"
			//DrawWelfareDate(data.Item, p, gainWay, oper, remark) // 领取奖励
			//var item []*model.WelfareItem
			//for _, v := range data.Item {
			//	item = append(item, &model.WelfareItem{
			//		Num:    int64(v.Grade),
			//		ItemId: v.Item_Id,
			//		Type:   v.Type,
			//	})
			//}
			//MoneyRatio := float64(0)
			//if vips := VipMgrSington.GetVIPcfg(p.Platform); vips != nil {
			//	MoneyRatio = vips.MoneyRatio
			//}
			//vipEx := int64(data.VIPEX)
			//if MoneyRatio > 0.000001 {
			//	vipEx = int64(float64(v.Price2) * MoneyRatio)
			//}
			//this.RecordWelfareLog(p, vipEx, v.Price2, int64(v.Discount*10000), p.WelfData.FirstPayDay, gainWay, model.WelfareBuyFirstPay,
			//	item, oper, remark)
			//
			//pack.OpRetCode = welfare.OpResultCode_OPRC_Sucess
			break
		}
	}
	if wfs == nil || wfs.Item == nil {
		logger.Logger.Tracef("BuyContinuousPay wfs == nil snid: %v pack: %v", p.SnId, pack)
		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
		return
	}
	ShopMgrSington.SendAPICreateOrder(p, ConfigPayId, wfs, "ContinuousPay")
	//三方购买
	//task.New(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
	//	var amount [3]int32
	//	for _, it := range wfs.Item {
	//		if it.Type == 1 {
	//			amount[0] = it.Grade
	//		} else if it.Type == 2 {
	//			amount[1] = it.Grade
	//		}
	//	}
	//	dbShop := model.NewDbShop(p.Platform, 0, amount[:], Shop_Consume_Money, int32(wfs.Price2),
	//		nil, 0, "", p.SnId, 0, "ContinuousPay")
	//	err := model.InsertDbShopLog(dbShop)
	//	if err != nil {
	//		logger.Logger.Errorf("model.InsertDbShopLog err:", err)
	//		return nil
	//	}
	//	return webapi.API_CreateOrder(common.GetAppId(), dbShop.LogId.Hex(), ConfigPayId, p.SnId, 0, p.Platform, p.PackageID, p.DeviceOS,
	//		p.DeviceId, "ContinuousRecharge", amount, int32(wfs.Price2), nil)
	//}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
	//	logger.Logger.Trace("API_CreateOrder_BuyContinuousPay:", data)
	//	info := data.(*webapi_proto.ASCreateOrder)
	//	if info == nil || info.Tag != 0 {
	//		//失败
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	} else {
	//		pack.RetCode = shop.OpResultCode_OPRC_Sucess
	//		pack.Url = info.Url
	//		p.SendToClient(int(shop.SPacketID_PACKET_SCPAYINFO), pack)
	//	}
	//}), "API_CreateOrder_BuyContinuousPay").Start()
}

func (this *WelfareMgr) Update() {

}

func (this *WelfareMgr) Shutdown() {
	module.UnregisteModule(this)
}

func (this *WelfareMgr) OnDayTimer() {
	//logger.Logger.Tracef("WelfareMgr OnDayTimer")
	this.BlindBoxCycle = make(map[string]int32)
	this.FirstPayCycle = make(map[string]int32)
	this.ContinuousPayCycle = make(map[string]int32)
}

func (this *WelfareMgr) InterestClockEvent() int {

	return (1 << CLOCK_EVENT_MAX) - 1
}

func init() {
	module.RegisteModule(WelfareMgrSington, time.Second, 0)
	ClockMgrSington.RegisteSinker(WelfareMgrSington)
}
