package game

import (
	"server/GoUtil"
	"server/MergeConst"
	"server/conf"
	"server/db"
	"server/game/mod/order"
	"server/msg"
	"server/pkg/github.com/name5566/leaf/log"
	"time"
)

func TriggerShippingOrder(player *Player, req *msg.ReqShippingOrder) {
	OrderSn := req.OrderSn
	Status := int(req.Status)
	if Status == MergeConst.ORDER_STATUS_CANCEL { // 取消支付
		CancelOrder(player, OrderSn)
		player.PushClientRes(&msg.ResShippingOrder{
			Code: msg.RES_CODE_SUCCESS,
			Msg:  "cancel success",
		})
		return
	}
	OrderData := &db.SqlChargeOrderStruct{}
	var err error
	n := 0
	for {
		n++
		if n > 5 {
			break
		}
		OrderData, err = GoogleVerify(player, OrderSn, req.ProduceId, req.Token)
		if err != nil {
			log.Debug("GoogleVerify parmas OrderSn：%s; ProduceId:%s; Token:%s", OrderSn, req.ProduceId, req.Token)
			log.Debug("GoogleVerify err:%v", err)
			time.Sleep(1 * time.Second)
			continue
		}
		if OrderData.PayStatus != MergeConst.ORDER_STATUS_PAY {
			time.Sleep(1 * time.Second)
			continue
		}
		if OrderData.PayStatus == MergeConst.ORDER_STATUS_PAY {
			break
		}

	}
	if OrderData == nil {
		return
	}
	log.Debug("[order verify success] Uid:%d;OrderSn:%s;PayOrder:%s;", player.M_DwUin, OrderData.OrderId, OrderData.PayChannelOrderId)
	player.lock.Lock()
	defer player.lock.Unlock()
	Charge(player, int(OrderData.ProductId))
	OrderData.PayStatus = MergeConst.ORDER_STATUS_SHIP
	db.UpdatePlayerChargeData(OrderData)
	player.PlayMod.save()
	orderDataMap := map[string]interface{}{
		"AppId":             conf.Server.AppID,
		"ServerId":          conf.Server.ServerID,
		"OrderId":           OrderData.OrderId,
		"PayChannelOrderId": OrderData.PayChannelOrderId,
		"ProductId":         OrderData.ProductId,
		"CreateTime":        OrderData.CreateTime,
		"PayTime":           OrderData.PayTime,
		"Price":             OrderData.Price,
		"PayType":           OrderData.PayType,
	}
	player.Kafka("pay", orderDataMap)
	player.SendClientRes()
}

func TriggerComfortOrder(p *Player) {
	BaseMod := p.PlayMod.getBaseMod()
	Now := GoUtil.Now()
	Lv := BaseMod.GetLevel()

	if Now-BaseMod.GetLogoutTime() < 7*86400 || Lv < 6 {
		return
	}
	OrderMod := p.PlayMod.getOrderMod()
	ChessMod := p.PlayMod.getChessMod()
	ChessList := ChessMod.GetUnlockChessList()
	TriggerType := 1
	for _, Order := range OrderMod.GetOrderList() {
		if GoUtil.IsContain(ChessList, Order.MergeId) {
			continue
		}
		if Order.Diff == order.DIFF_LOW {
			return
		}
		if Order.Diff == order.DIFF_MID {
			TriggerType = 2
		}
	}
	EmitList := ChessMod.GetEmitList()
	EnergyMul := BaseMod.GetEnergyMul()
	if TriggerType == 1 {
		OrderMod.CreateComfortOrder(Lv, EmitList, EnergyMul, order.DIFF_LOW, 2)
		OrderMod.CreateComfortOrder(Lv, EmitList, EnergyMul, order.DIFF_LOW, 3)
		OrderMod.CreateComfortOrder(Lv, EmitList, EnergyMul, order.DIFF_MID, 2)
	} else {
		OrderMod.CreateComfortOrder(Lv, EmitList, EnergyMul, order.DIFF_LOW, 2)
		OrderMod.CreateComfortOrder(Lv, EmitList, EnergyMul, order.DIFF_LOW, 3)
	}
}
