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/pointer"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/duke-git/lancet/v2/strutil"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/xuri/excelize/v2"

	v1 "kami/api/card_info_walmart/v1"
	"kami/api/commonApi"

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

func (c *ControllerV1) Download(ctx context.Context, req *v1.DownloadReq) (res *v1.DownloadRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil || pointer.IsNil(userInfo) {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}

	isAdmin := false
	if userInfo.Id == "" {
		isAdmin = true
	}
	if req.UserId != "" && userInfo.Id == "" {
		userInfo.Id = req.UserId
	}

	_, list, err := service.CardRedeemAccount().List(ctx, &model.RedeemAccountListInput{
		CommonPageReq: commonApi.CommonPageReq{
			Current:  0,
			PageSize: 0,
		},
		Name:            req.Name,
		NickName:        req.NickName,
		Cookie:          req.Cookie,
		UserId:          userInfo.Id,
		CreatedUserName: req.CreatedUserName,
		GroupId:         req.GroupId,
		Category:        consts.CardRedeemAccountCategoryWalMart,
	})
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "下载失败")
		return
	}

	excel := excelize.NewFile()
	sw, _ := excel.NewStreamWriter("Sheet1")
	err = sw.SetRow("A1", []interface{}{
		"用户id", "用户名", "名称", "昵称", "cookie", "余额", "今日充值金额", "今日充值次数",
		"累计充值金额", "累计充值次数", "状态", "创建时间",
	})
	slice.ForEach(list, func(index int, item *model.RedeemAccountOutput) {
		if isAdmin {
			item.Cookie = strutil.HideString(item.Cookie, 4, gstr.LenRune(item.Cookie)-4, "*")
		}
		_ = sw.SetRow(fmt.Sprintf("A%d", index+2), []interface{}{
			item.UploadUser.Id, item.UploadUser.Username, item.Name, item.Nickname, item.Cookie, item.Balance, item.AmountTodaySum, item.AmountTodayCount,
			item.AmountTotalSum, item.AmountTodayCount, consts.RedeemAccountStatus(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
}
