package agent

import (
	"context"
	"fmt"
	"net/http"

	"hm-server/app/main/api/internal/svc"
	"hm-server/app/main/api/internal/types"
	"hm-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetAgentPromotionQrcodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	writer http.ResponseWriter
}

func NewGetAgentPromotionQrcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext, writer http.ResponseWriter) *GetAgentPromotionQrcodeLogic {
	return &GetAgentPromotionQrcodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		writer: writer,
	}
}

func (l *GetAgentPromotionQrcodeLogic) GetAgentPromotionQrcode(req *types.GetAgentPromotionQrcodeReq) error {
	// 1. 参数验证
	if req.QrcodeUrl == "" {
		return errors.Wrapf(xerr.NewErrMsg("二维码URL不能为空"), "二维码URL为空")
	}

	if req.QrcodeType == "" {
		req.QrcodeType = "promote" // 设置默认类型
	}

	// 3. 检查指定类型的背景图是否存在
	if !l.svcCtx.ImageService.CheckImageExists(req.QrcodeType) {
		l.Errorf("指定的二维码类型对应的背景图不存在: %s", req.QrcodeType)
		return errors.Wrapf(xerr.NewErrMsg("指定的二维码类型不支持"), "二维码类型: %s", req.QrcodeType)
	}

	// 4. 处理图片，添加二维码
	imageData, contentType, err := l.svcCtx.ImageService.ProcessImageWithQRCode(req.QrcodeType, req.QrcodeUrl)
	if err != nil {
		l.Errorf("处理图片失败: %v, 类型: %s, URL: %s", err, req.QrcodeType, req.QrcodeUrl)
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成推广二维码图片失败: %v", err)
	}

	// 5. 设置响应头
	l.writer.Header().Set("Content-Type", contentType)
	l.writer.Header().Set("Content-Length", fmt.Sprintf("%d", len(imageData)))
	l.writer.Header().Set("Cache-Control", "public, max-age=3600") // 缓存1小时
	l.writer.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"qrcode_%s.png\"", req.QrcodeType))

	// 6. 写入图片数据
	_, err = l.writer.Write(imageData)
	if err != nil {
		l.Errorf("写入图片数据失败: %v", err)
		return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "输出图片数据失败: %v", err)
	}

	l.Infof("成功生成代理推广二维码图片，类型: %s, URL: %s, 图片大小: %d bytes",
		req.QrcodeType, req.QrcodeUrl, len(imageData))

	return nil
}
