package game

import (
	"encoding/json"
	"fmt"
	"os/exec"
	"server/MergeConst"
	"server/conf"
	activityCfg "server/conf/activity"
	chargeCfg "server/conf/charge"
	passCfg "server/conf/pass"
	"server/db"
	"server/game/mod/activity"
	"server/game/mod/item"
	MsgMod "server/game/mod/msg"
	piggyBank "server/game/mod/piggy_bank"
	"server/game/mod/quest"
	GoUtil "server/game_util"
	proto "server/msg"
	"server/pkg/github.com/name5566/leaf/log"
	"strings"
)

func (p *Player) Charge(ChargeId int) {
	p.ChargeFire(ChargeId)    // 充值
	p.EndlessFire(ChargeId)   // 无尽礼包
	p.PiggyBankFire(ChargeId) // 猪猪银行
	p.PlayroomFire(ChargeId)  // 游乐场
	p.ActivityFire(ChargeId)  // 活动礼包
	p.ADPetWorkFire(ChargeId) // 广告宠物工作
	p.PassFire(ChargeId)
	OrderMod := p.PlayMod.getOrderMod()
	OrderMod.SetIsCharge() // 设置订单模块为充值状态
	p.QuestTrigger(&quest.Trigger{Label: quest.TRIGGER_LABEL_PURCHASE, A: []interface{}{}})
}

func (p *Player) SendCharge(d *ChargeExtra) {
	FriendMgrSend(&MsgMod.Msg{
		From:  int(p.M_DwUin),
		Type:  MsgMod.HANDLE_TYPE_SEND_CHARGE,
		To:    int(d.Uid),
		SendT: GoUtil.Now(),
		Extra: d,
	})
}

func (p *Player) ADPetWorkFire(ChargeId int) {
	ChargeMod := p.PlayMod.getChargeMod()
	Item := ChargeMod.FireAdReward(ChargeId)
	if Item != nil {
		err := p.HandleItem(Item, proto.ITEM_POP_LABEL_ActivityGift.String())
		if err != nil {
			log.Debug("ChargeFire err : %s", err)
			return
		}
	}
	p.PlayMod.save()
	p.ChargeBackData()
}

func (p *Player) ActivityFire(ChargeId int) {
	ActivityMod := p.PlayMod.getActivityMod()
	ActivityId := activityCfg.GetActivityGiftId(ChargeId)
	ActivityInfo := p.GetActivityInfoById(ActivityId)
	if ActivityInfo == nil {
		log.Debug("ActivityFire ActivityInfo nil : player id :%d, charge id:%d", p.M_DwUin, ChargeId)
		return
	}
	Item, err := ActivityMod.Fire(ChargeId)
	if err != nil {
		log.Debug("ActivityFire err : %s", err)
		return
	}
	if Item == nil {
		return
	}
	err = p.HandleItem(Item, proto.ITEM_POP_LABEL_ActivityGift.String())
	if err != nil {
		log.Debug("ChargeFire err : %s", err)
		return
	}
	p.PlayMod.save()
	p.initAcitivity()
	p.BackDataActivity()
}

func (p *Player) PassFire(ChargeId int) {
	ActivityInfo := p.GetActivityInfo(activity.ACT_TYPE_PASS)
	if ActivityInfo == nil {
		return
	}
	Now := GoUtil.Now()
	if Now < ActivityInfo.StartT || Now > ActivityInfo.EndT {
		return
	}
	PassMod := p.PlayMod.getPassMod()
	var Items []*item.Item
	switch ChargeId {
	case passCfg.GetLowChargeId(ActivityInfo.Id):
		Items = PassMod.GetLowChargeItems()
	case passCfg.GetHighChargeId(ActivityInfo.Id):
		Items = PassMod.GetHighChargeItems()
	}
	if len(Items) == 0 {
		return
	}
	err := p.HandleItem(Items, proto.ITEM_POP_LABEL_PassCharge.String())
	if err != nil {
		log.Debug("PassFire err : %s", err)
		return
	}
	p.PlayMod.save()
}

func (p *Player) PlayroomFire(ChargeId int) {
	PlayroomMod := p.PlayMod.getPlayroomMod()
	Item := PlayroomMod.Fire(ChargeId)
	if Item == nil {
		return
	}
	err := p.HandleItem(Item, proto.ITEM_POP_LABEL_Playroom.String())
	if err != nil {
		log.Debug("PlayroomFire err : %s", err)
	}
	p.TeLog("get_assist_battery", map[string]interface{}{
		"assist_battery _type": "charge",
	})
	p.PlayMod.save()
}

func (p *Player) PiggyBankFire(ChargeId int) {
	PiggyBankMod := p.PlayMod.getPiggyBankMod()
	Item := PiggyBankMod.Fire(ChargeId)
	if Item == nil {
		return
	}
	err := p.HandleItem(Item, proto.ITEM_POP_LABEL_PiggyBank.String())
	if err != nil {
		log.Debug("PiggyBankFire err : %s", err)
	}
	p.LimitedTimePiggyBankTrigger()
	p.TeLog("piggy_bank_open", map[string]interface{}{
		"piggy_bank_type": piggyBank.PIGGY_BANK_TYPE_CHARGE,
		"item_list":       Item,
		"open_cost":       ChargeId,
	})
	p.PlayMod.save()

}

// 处理玩家充值
func (p *Player) ChargeFire(ChargeId int) {
	ChargeMod := p.PlayMod.getChargeMod()
	Item := ChargeMod.Fire(ChargeId)
	if Item == nil {
		return
	}
	err := p.HandleItem(Item, proto.ITEM_POP_LABEL_Charge.String())
	if err != nil {
		log.Debug("ChargeFire err : %s", err)
	}
	p.PlayMod.save()
	p.ChargeBackData()
}

func (p *Player) ChargeItem(ChargeId int) []*item.Item {
	ChargeMod := p.PlayMod.getChargeMod()
	Item := ChargeMod.Fire(ChargeId)
	return Item
}

// 处理无尽礼包充值
func (p *Player) EndlessFire(ChargeId int) {
	EndlessMod := p.PlayMod.getEndlessMod()
	Item := EndlessMod.Fire(ChargeId)
	if Item == nil {
		return
	}
	err := p.HandleItem(Item, proto.ITEM_POP_LABEL_Endless.String())
	if err != nil {
		log.Debug("EndlessFire err : %s", err)
	}
	p.PlayMod.save()
	p.PushClientRes(EndlessMod.BackData())
}

// 创建订单
func (p *Player) CreateOrderSn(req *proto.ReqCreateOrderSn) (string, error) {
	Uid := int(p.M_DwUin)
	OrderSn := GoUtil.CreateOrderSn(Uid)

	Price, Currency := chargeCfg.GetChargeInfo(int(req.ChargeId))
	Extra := &ChargeExtra{
		Type: int(req.Type),
		Uid:  req.Uid,
	}
	ExtraData, _ := json.Marshal(Extra)
	err := db.CreateOrderSn(Uid, int(req.ChargeId), OrderSn, req.PlatForm, req.Channel, Price, Currency, string(ExtraData))
	if err != nil {
		return "", err
	}
	return OrderSn, nil
}

func (p *Player) GoogleVerify(OrderSn, ProduceId, Token string) (*db.SqlChargeOrderStruct, error) {
	Order, err := db.GetPlayerChargeData(OrderSn)
	if err != nil {
		return nil, err
	}
	if Order.PayStatus == MergeConst.ORDER_STATUS_SHIP {
		return nil, fmt.Errorf("订单已经发货")
	}
	if !conf.Server.GoogleVerify {
		Order.PayStatus = MergeConst.ORDER_STATUS_PAY
		return Order, nil
	}
	if Order.PayStatus != MergeConst.ORDER_STATUS_IDLE {
		return nil, fmt.Errorf("订单已经支付")
	}
	cmd := exec.Command(conf.Server.AppPath+"/script/verifyOrder", ProduceId, Token)

	// 获取命令的输出
	output, err := cmd.Output()
	if err != nil {
		return nil, err
	}
	// 将输出转换为字符串
	outputStr := string(output)

	// 替换单引号为双引号
	outputStr = strings.ReplaceAll(outputStr, "'", "\"")
	type VerifyData struct {
		PurchaseState    int    `json:"purchaseState"`
		DeveloperPayload string `json:"developerPayload"`
		OrderId          string `json:"orderId"`
		ConsumptionState int    `json:"consumptionState"`
	}
	r := &VerifyData{}
	err = json.Unmarshal([]byte(outputStr), &r)
	if err != nil {
		log.Debug("output %s", string(output))
		return nil, err
	}
	_, err = db.GetPlayerPayChannelOrderId(r.OrderId)
	if err == nil {
		return nil, fmt.Errorf("订单已支付发货 param: %v", r)
	}
	// if r.DeveloperPayload != OrderSn {
	// 	return nil, fmt.Errorf("订单号不匹配")
	// }
	if r.ConsumptionState != 1 {
		return nil, fmt.Errorf("订单未消费")
	}
	Order.PayStatus = MergeConst.ORDER_STATUS_PAY
	Order.PayChannelOrderId = r.OrderId
	Order.PayTime = GoUtil.Now()
	return Order, nil
}

func (p *Player) CancelOrder(OrderSn string) error {
	Order, err := db.GetPlayerChargeData(OrderSn)
	if err != nil {
		return err
	}
	if Order.PayStatus != MergeConst.ORDER_STATUS_IDLE {
		return fmt.Errorf("订单已支付")
	}
	Order.PayStatus = MergeConst.ORDER_STATUS_CANCEL
	return db.UpdatePlayerChargeData(Order)
}
