package camel_oil

import (
	"context"
	"fmt"

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

	v1 "kami/api/camel_oil/v1"
	"kami/internal/errHandler"
	"kami/internal/service"
)

func (c *ControllerV1) ExportOrder(ctx context.Context, req *v1.ExportOrderReq) (res *v1.ExportOrderRes, err error) {
	// 权限检查
	_, err = service.SysAuth().LoginOnlyIFrame(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}

	// 调用service层方法获取Excel文件内容
	fileName, content, err := service.CamelOil().ExportOrder(ctx, req)
	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.ExportOrderRes{}, nil
}