package card_info_original_jd

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

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/xuri/excelize/v2"

	"kami/api/card_info_original_jd/v1"

	"github.com/gogf/gf/v2/errors/gcode"
)

func (c *ControllerV1) OriginalDownload(ctx context.Context, req *v1.OriginalDownloadReq) (res *v1.OriginalDownloadRes, err error) {
	userInfo, err := service.SysAuth().LoginOnlyIFrame(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	data, err := service.CardRedeemAccount().GetAllByUserId(ctx, userInfo.Id, consts.CardRedeemAccountCategoryOriginalJD, nil)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "下载失败")
		return
	}
	excel := excelize.NewFile()
	sw, _ := excel.NewStreamWriter("Sheet1")
	err = sw.SetRow("A1", []interface{}{
		"昵称", "cookie", "余额", "今日充值金额", "今日充值次数",
		"累计充值金额", "累计充值次数", "状态", "创建时间",
	})
	slice.ForEach(data, func(index int, item *entity.V1CardRedeemAccountInfo) {
		_ = sw.SetRow(fmt.Sprintf("A%d", index+2), []interface{}{
			item.Nickname, item.Cookie, item.Balance, item.AmountTodaySum, item.AmountTodayCount, item.AmountTotalSum, item.AmountTodayCount,
			consts.JDAccountStatus(item.Status).GetStatusText(), item.CreatedAt,
		})
	})
	_ = 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
}
