package card_info_walmart

import (
	"bytes"
	"context"
	"fmt"

	"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"

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

func (c *ControllerV1) OrderExport(ctx context.Context, req *v1.OrderExportReq) (res *v1.OrderExportRes, 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
	}
	_, list, err := service.CardRedeemOrder().List(ctx, &model.RedeemCardListInput{
		CommonPageReq: commonApi.CommonPageReq{
			Current:  0,
			PageSize: 0,
		},
		GiftCardPwd:     req.GiftCardPwd,
		MerchantId:      req.MerchantId,
		Attach:          req.Attach,
		DateRange:       req.DateRange,
		AccountNickName: req.AccountNickName,
		AccountCk:       req.AccountCk,
		UserId:          userInfo.Id,
		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", "用户名", "卡号", "卡密", "商户订单号", "ck唯一id", "ck账号", "充值状态", "状态明细",
		"拉单金额", "实际金额", "创建时间",
	})
	slice.ForEach(list, func(index int, item *model.RedeemCardOrderOutput) {
		status := consts.RedeemOrderStatus(item.Status)
		orderStatus := consts.RedeemOrderStatus(item.OrderStatus)
		_ = sw.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
}
