package card_info_walmart

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"time"

	v1 "kami/api/card_info_walmart/v1"
	"kami/api/commonApi"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

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

func (c *ControllerV1) GroupExport(ctx context.Context, req *v1.GroupExportReq) (res *v1.GroupExportRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	if req.UserId != "" && userInfo.Id == "" {
		userInfo.Id = req.UserId
	}
	_, output, err := service.CardRedeemAccount().GroupStats(ctx, &model.RedeemAccountGroupStatsInput{
		Category:      consts.CardRedeemAccountCategoryWalMart,
		CreatedUserId: userInfo.Id,
		GroupStatReq: &v1.GroupStatReq{
			CommonPageReq: commonApi.CommonPageReq{
				Current:  0,
				PageSize: 0,
			},
			Username: req.Username,
			Date:     req.Date,
			UserId:   userInfo.Id,
			Name:     req.Name,
		},
	}, nil)
	if err != nil {
		return nil, err
	}

	excel := excelize.NewFile()
	sw, _ := excel.NewStreamWriter("Sheet1")
	err = sw.SetRow("A1", []any{
		"id", "上传人昵称", "分组名称", "正常账户数量", "异常账户数量", "已删除账户数量", "充值金额", "充值笔数", "充值日期",
	})
	if err != nil {
		return nil, err
	}

	slice.ForEach(output, func(index int, item *model.RedeemAccountGroupStatsOutput) {
		_ = sw.SetRow(fmt.Sprintf("A%d", index+2), []any{
			item.GroupId, item.CreatedUserName, item.GroupName, item.Account.Normal, item.Account.UnNormal,
			item.Account.Deleted, item.Sum, item.Count, item.OrderDate,
		})
	})
	_ = sw.Flush()
	var buffer bytes.Buffer
	_ = excel.Write(&buffer)
	_ = excel.Close()
	// 数据下载到本地
	fileName := fmt.Sprintf("沃尔玛充值卡分组统计_%s.xlsx", time.Now().Format("20060102150405"))
	err = os.WriteFile(fileName, buffer.Bytes(), 0644)
	if err != nil {
		return nil, err
	}
	// 数据缓冲到本地
	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
}
