package card_info_walmart

import (
	"bytes"
	"context"
	"fmt"

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

func (c *ControllerV1) StatsOverviewDownload(ctx context.Context, req *v1.StatsOverviewDownloadReq) (res *v1.StatsOverviewDownloadRes, 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
	}

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

	excel := excelize.NewFile()
	if err = excel.SetSheetName("Sheet1", "账号列表"); err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "下载失败")
		return
	}
	sw, _ := excel.NewStreamWriter("账号列表")

	err = sw.SetRow("A1", []any{
		"用户id", "用户名", "名称", "昵称", "cookie", "余额", "今日充值金额", "今日充值次数",
		"累计充值金额", "累计充值次数", "状态", "创建时间",
	})
	slice.ForEach(accountList, 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,
		})
	})

	_, orderList, err := service.CardRedeemOrder().List(ctx, &model.RedeemCardListInput{
		CommonPageReq: commonApi.CommonPageReq{
			Current:  0,
			PageSize: 0,
		},
		UserId:   userInfo.Id,
		GroupId:  req.GroupId,
		Category: consts.CardRedeemAccountCategoryWalMart,
	})

	sheetName := "订单列表"
	_, err = excel.NewSheet(sheetName)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "下载失败")
		return
	}
	sw2, err := excel.NewStreamWriter(sheetName)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "下载失败")
		return
	}
	err = sw2.SetRow("A1", []any{
		"用户ID", "用户名", "卡号", "卡密", "商户订单号", "ck唯一id", "ck账号", "充值状态", "状态明细",
		"拉单金额", "实际金额", "创建时间",
	})
	slice.ForEach(orderList, func(index int, item *model.RedeemCardOrderOutput) {
		status := consts.RedeemOrderStatus(item.Status)
		orderStatus := consts.RedeemOrderStatus(item.OrderStatus)
		_ = sw2.SetRow(fmt.Sprintf("A%d", index+2), []interface{}{
			item.UserInfo.Id, item.UserInfo.Username, item.CardNo, item.GiftCardPwd, item.Attach,
			item.MerchantId, item.AccountName, status.String(), orderStatus.String(),
			item.OrderAmount, item.ActualAmount, 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
}
