package logic

import (
	"bytes"
	"encoding/json"
	"fmt"
	"fusenapi/model/gmodel"
	"fusenapi/service/repositories"
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"fusenapi/utils/file"
	"fusenapi/utils/hash"
	"image"
	"image/jpeg"
	"io"
	"net/http"

	"context"

	"fusenapi/server/resource/internal/svc"
	"fusenapi/server/resource/internal/types"

	"github.com/disintegration/imaging"
	"github.com/zeromicro/go-zero/core/logx"
)

type LogoResizeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLogoResizeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoResizeLogic {
	return &LogoResizeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 处理进入前逻辑w,r
// func (l *LogoResizeLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }

func (l *LogoResizeLogic) LogoResize(req *types.LogoResizeReq, userinfo *auth.UserInfo) (resp *basic.Response) {
	// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
	// userinfo 传入值时, 一定不为null

	var userId int64
	var guestId int64

	// 检查用户是否是游客
	if userinfo.IsGuest() {
		// 如果是,使用游客ID和游客键名格式
		guestId = userinfo.GuestId
	} else {
		// 否则,使用用户ID和用户键名格式
		userId = userinfo.UserId
	}

	resourceModel := gmodel.NewFsResourceModel(l.svcCtx.MysqlConn)
	resourceInfo, err := resourceModel.FindOneById(l.ctx, req.ResourceId)
	if err != nil {
		logx.Errorf("find resource err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}
	response, err := http.Get(*resourceInfo.ResourceUrl)
	if err != nil {
		logx.Errorf("http get err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}
	defer response.Body.Close()

	imgByte, err := io.ReadAll(response.Body)
	if err != nil {
		logx.Errorf("io readall err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}

	src, _, err := image.Decode(bytes.NewReader(imgByte))
	if err != nil {
		logx.Errorf("image decode err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}

	// Resize the cropped image to width = 200px preserving the aspect ratio.
	src = imaging.Resize(src, int(req.Width), int(req.Height), imaging.Lanczos)
	if err != nil {
		logx.Errorf("imaging esize err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}

	emptyBuff := bytes.NewBuffer(nil) //开辟一个新的空buff
	jpeg.Encode(emptyBuff, src, nil)  //img写入到buff

	var hashKeyDataMap = make(map[string]interface{})

	hashKeyDataB, _ := json.Marshal(req)
	json.Unmarshal(hashKeyDataB, &hashKeyDataMap)
	var resourceId string = hash.JsonHashKey(hashKeyDataMap)
	fmt.Println(resourceId)

	// 上传文件
	var upload = file.Upload{
		Ctx:        l.ctx,
		MysqlConn:  l.svcCtx.MysqlConn,
		AwsSession: l.svcCtx.AwsSession,
	}
	uploadRes, err := upload.UploadFileByByte(&file.UploadBaseReq{
		FileHash:     resourceId,
		FileByte:     emptyBuff.Bytes(),
		UploadBucket: 1,
		ApiType:      2,
		UserId:       userId,
		GuestId:      guestId,
		Source:       "logo-resize",
	})
	if err != nil {
		logx.Errorf("upload UploadFileByByte err: %v", err)
		return resp.SetStatus(basic.CodeFileNoFoundErr)
	}
	metadataChild := make(map[string]interface{}, 1)
	metadataChildData := make(map[string]interface{}, 1)
	metadataChildKey := fmt.Sprintf("%d*%d", req.Width, req.Height)
	metadataChildData[metadataChildKey] = repositories.Cropping{
		ResourceId:  uploadRes.ResourceId,
		ResourceUrl: uploadRes.ResourceUrl,
		Width:       req.Width,
		Height:      req.Height,
	}
	metadataChild["cropping"] = metadataChildData

	// 原图metadata 更新
	_, err = l.svcCtx.Repositories.NewResource.UpdateMetadata(l.ctx, &repositories.UpdateMetadataReq{
		ResourceId:    req.ResourceId,
		MetadataChild: metadataChild,
	})

	if err != nil {
		return resp.SetStatus(basic.CodeServiceErr, "原图metadata更新失败")
	}

	// 返回成功的响应
	return resp.SetStatus(basic.CodeOK, map[string]interface{}{
		"resource_id":  uploadRes.ResourceId,
		"resource_url": uploadRes.ResourceUrl,
	})
}

// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *LogoResizeLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }