package jd_cookie

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/frame/g"

	"kami/api/jd_cookie/v1"
	"kami/internal/service"
)

func (c *ControllerV1) ExportJdOrder(ctx context.Context, req *v1.ExportJdOrderReq) (res *v1.ExportJdOrderRes, err error) {
	// 调用service层方法获取Excel文件内容
	fileName, content, err := service.JdCookie().ExportJdOrder(ctx, req.Status, req.StartTime, req.EndTime, req.OrderId)
	if err != nil {
		return nil, err
	}

	// 设置响应头，告知浏览器这是一个文件下载
	r := g.RequestFromCtx(ctx)
	r.Response.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	r.Response.Header().Set("Content-Disposition", "attachment; filename="+fileName)
	r.Response.Header().Set("Content-Length", fmt.Sprintf("%d", len(content)))

	// 直接写入响应体
	r.Response.Write(content)

	// 返回一个空的响应，因为数据已经直接写入到响应体中
	return &v1.ExportJdOrderRes{}, nil
}
