package admin

import (
	"fmt"
	"net/http"
	"time"

	"bindbox-game/configs"
	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	"bindbox-game/internal/pkg/wechat"
)

type setJumpPathRequest struct {
	Path string `json:"path"`
}

type uploadVirtualShippingRequest struct {
	TransactionID string  `json:"transaction_id"`
	ItemDesc      *string `json:"item_desc"`
}

func (h *handler) SetMiniAppMsgJumpPath() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(setJumpPathRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if req.Path == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "path 不能为空"))
			return
		}
		cfg := configs.Get()
		wxc := &wechat.WechatConfig{AppID: cfg.Wechat.AppID, AppSecret: cfg.Wechat.AppSecret}
		if err := wechat.SetMsgJumpPath(ctx, wxc, req.Path); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 12011, err.Error()))
			return
		}
		ctx.Payload(map[string]any{"ok": true})
	}
}

func (h *handler) UploadVirtualShippingForTransaction() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(uploadVirtualShippingRequest)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
		if req.TransactionID == "" {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, "transaction_id 不能为空"))
			return
		}
		var itemDesc string
		tx, _ := h.readDB.PaymentTransactions.WithContext(ctx.RequestContext()).Where(h.readDB.PaymentTransactions.TransactionID.Eq(req.TransactionID)).First()
		if tx == nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 12012, "未找到交易"))
			return
		}
		ord, _ := h.readDB.Orders.WithContext(ctx.RequestContext()).Where(h.readDB.Orders.ID.Eq(tx.OrderID)).First()
		if ord == nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 12012, "未找到订单"))
			return
		}
		if req.ItemDesc != nil && *req.ItemDesc != "" {
			itemDesc = *req.ItemDesc
		} else {
			xs, _ := h.readDB.OrderItems.WithContext(ctx.RequestContext()).Where(h.readDB.OrderItems.OrderID.Eq(ord.ID)).Find()
			if len(xs) == 0 {
				itemDesc = "订单" + ord.OrderNo
			} else {
				s := ""
				for i, it := range xs {
					seg := it.Title + "*" + func(q int64) string { return fmt.Sprintf("%d", q) }(it.Quantity)
					if i == 0 {
						s = seg
					} else {
						s = s + ", " + seg
					}
				}
				if len(s) > 120 {
					s = s[:120]
				}
				itemDesc = s
			}
		}
		pre, _ := h.readDB.PaymentPreorders.WithContext(ctx.RequestContext()).Where(h.readDB.PaymentPreorders.OrderID.Eq(ord.ID)).Order(h.readDB.PaymentPreorders.ID.Desc()).First()
		payerOpenid := ""
		if pre != nil {
			payerOpenid = pre.PayerOpenid
		}
		cfg := configs.Get()
		wxc := &wechat.WechatConfig{AppID: cfg.Wechat.AppID, AppSecret: cfg.Wechat.AppSecret}
		if err := wechat.UploadVirtualShippingWithFallback(ctx, wxc, req.TransactionID, ord.OrderNo, payerOpenid, itemDesc, time.Now()); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, 12013, err.Error()))
			return
		}
		ctx.Payload(map[string]any{"ok": true})
	}
}
