package app

import (
    "fmt"
    "net/http"

    "bindbox-game/internal/code"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/validation"
    "bindbox-game/internal/repository/mysql/model"
)

type listCouponsRequest struct {
	Page     int `form:"page"`
	PageSize int `form:"page_size"`
}
type listCouponsResponse struct {
    Page     int                  `json:"page"`
    PageSize int                  `json:"page_size"`
    Total    int64                `json:"total"`
    List     []couponItem         `json:"list"`
}

type couponItem struct {
    ID          int64  `json:"id"`
    Name        string `json:"name"`
    Amount      int64  `json:"amount"`
    ValidStart  string `json:"valid_start"`
    ValidEnd    string `json:"valid_end"`
    Status      int32  `json:"status"`
    Rules       string `json:"rules"`
}

// ListUserCoupons 查看用户优惠券
// @Summary 查看用户优惠券
// @Description 查看用户持有的优惠券列表
// @Tags APP端.用户
// @Accept json
// @Produce json
    // @Param user_id path integer true "用户ID"
    // @Security LoginVerifyToken
// @Param page query int true "页码" default(1)
// @Param page_size query int true "每页数量，最多100" default(20)
// @Success 200 {object} listCouponsResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/users/{user_id}/coupons [get]
func (h *handler) ListUserCoupons() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listCouponsRequest)
		rsp := new(listCouponsResponse)
		if err := ctx.ShouldBindForm(req); err != nil {
			ctx.AbortWithError(core.Error(http.StatusBadRequest, code.ParamBindError, validation.Error(err)))
			return
		}
        userID := int64(ctx.SessionUserInfo().Id)
        items, total, err := h.user.ListCoupons(ctx.RequestContext(), userID, req.Page, req.PageSize)
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 10003, err.Error()))
            return
        }
        rsp.Page = req.Page
        rsp.PageSize = req.PageSize
        rsp.Total = total
        if len(items) == 0 {
            rsp.List = []couponItem{}
            ctx.Payload(rsp)
            return
        }
        ids := make([]int64, 0, len(items))
        for _, it := range items {
            ids = append(ids, it.CouponID)
        }
        rows, err := h.readDB.SystemCoupons.WithContext(ctx.RequestContext()).Where(h.readDB.SystemCoupons.ID.In(ids...)).Find()
        if err != nil {
            ctx.AbortWithError(core.Error(http.StatusBadRequest, 10003, err.Error()))
            return
        }
        mp := make(map[int64]*model.SystemCoupons, len(rows))
        for i := range rows {
            c := rows[i]
            mp[c.ID] = c
        }
        rsp.List = make([]couponItem, 0, len(items))
        for _, it := range items {
            sc := mp[it.CouponID]
            name := ""
            amount := int64(0)
            rules := ""
            if sc != nil {
                name = sc.Name
                amount = sc.DiscountValue
                rules = buildCouponRules(sc)
            }
            vi := couponItem{
                ID:         it.ID,
                Name:       name,
                Amount:     amount,
                ValidStart: it.ValidStart.Format("2006-01-02 15:04:05"),
                ValidEnd:   it.ValidEnd.Format("2006-01-02 15:04:05"),
                Status:     it.Status,
                Rules:      rules,
            }
            rsp.List = append(rsp.List, vi)
        }
        ctx.Payload(rsp)
    }
}

func buildCouponRules(c *model.SystemCoupons) string {
    switch c.DiscountType {
    case 1:
        return fmt.Sprintf("直减%v分，满%v分可用", c.DiscountValue, c.MinSpend)
    case 2:
        return fmt.Sprintf("满%v分减%v分", c.MinSpend, c.DiscountValue)
    case 3:
        p := float64(c.DiscountValue) / 10.0
        return fmt.Sprintf("折扣%0.1f%%，满%v分可用", p, c.MinSpend)
    default:
        return ""
    }
}
