package card_info_apple

import (
	"bytes"
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/model"
	"kami/internal/service"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/xuri/excelize/v2"

	"kami/api/card_info_apple/v1"
)

func (c *ControllerV1) RechargeListDownload(ctx context.Context, req *v1.RechargeListDownloadReq) (res *v1.RechargeListDownloadRes, err error) {
	rechargeService := service.AppleOrder()
	_, list, err := rechargeService.List(ctx, model.AppleCardRechargeParamsInput{
		RechargeListReq: v1.RechargeListReq{
			StartDate:  req.StartDate,
			EndDate:    req.EndDate,
			Account:    req.Account,
			AccountID:  req.AccountID,
			MerchantId: req.MerchantId,
			Attach:     req.Attach,
			OrderNo:    req.OrderNo,
			CardNo:     req.CardNo,
			CardPass:   req.CardPass,
		},
	})
	excel := excelize.NewFile()
	sw, _ := excel.NewStreamWriter("Sheet1")
	err = sw.SetRow("A1", []interface{}{
		"序号", "兑换订单号", "系统订单号", "商户订单号", "分配账号",
		"卡密", "卡面金额", "支付金额", "创建时间", "状态",
	})
	for i, info := range list {
		_ = sw.SetRow(fmt.Sprintf("A%d", i+2), []interface{}{
			i + 1, info.OrderNo, info.Attach, info.MerchantId, info.AccountName, info.CardPass, info.CardAmount,
			info.ActualAmount, info.CreatedAt, consts.GetAppleRechargeOrderStatus(info.Status),
		})
	}
	_ = sw.Flush()
	var buffer bytes.Buffer
	_ = excel.Write(&buffer)
	_ = excel.Close()
	g.RequestFromCtx(ctx).Response.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	g.RequestFromCtx(ctx).Response.Header().Add("Content-Disposition", "attachment; filename=apple_card_info_v1_recharge_list_download.xlsx")
	g.RequestFromCtx(ctx).Response.WriteOverExit(buffer.Bytes())
	g.RequestFromCtx(ctx).Response.Flush()
	return
}
