package card_info_walmart

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

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

	v1 "kami/api/card_info_walmart/v1"

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

func (c *ControllerV1) AccountSummaryDownload(ctx context.Context, req *v1.AccountSummaryDownloadReq) (res *v1.AccountSummaryDownloadRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	_, output, err := service.CardRedeemAccount().GetSummary(ctx, &model.AccountDailySummaryGetInput{
		AccountDailySummaryReq: &v1.AccountDailySummaryReq{
			CommonPageReq: req.CommonPageReq,
			Username:      req.Username,
			Date:          req.Date,
			AccountName:   req.AccountName,
		},
		CreatedUserId: userInfo.Id,
		Category:      consts.CardRedeemAccountCategoryWalMart,
	}, nil)
	if err != nil {
		return
	}

	excel := excelize.NewFile()
	sw, _ := excel.NewStreamWriter("Sheet1")
	err = sw.SetRow("A1", []interface{}{
		"分组id", "分组名称", "id", "账户", "余额", "今日充值金额", "今日充值次数",
		"累计充值金额", "累计充值次数", "状态", "创建时间", "是否还在",
	})
	slice.ForEach(output, func(index int, item *model.AccountDailySummaryGetOutput) {
		_ = sw.SetRow(fmt.Sprintf("A%d", index+2), []interface{}{
			item.GroupId, item.GroupName, item.AccountInfo.Id, item.AccountInfo.Name,
			item.AccountInfo.Balance, item.AmountTodaySum,
			item.AmountTodayCount, item.AmountTotalSum, item.AmountTotalCount,
			consts.RedeemAccountStatus(item.AccountInfo.Status).GetStatusText(),
			item.Date.Format("2006-01-02"), isDeleted(item.DeletedAt),
		})
	})
	_ = 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
}

func isDeleted(deletedAt *gtime.Time) string {
	if deletedAt != nil {
		return "❌"
	}
	return "✅"
}
