package advice

import (
	"ai_scheduler/internal/biz"
	"ai_scheduler/internal/config"
	errorcode "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/file_download"
	"context"
	"errors"

	"net/url"

	"github.com/gofiber/fiber/v2"
)

// FileService 文件处理
type FileService struct {
	adviceBiz        *biz.AdviceFileBiz
	cfg              *config.Config
	adviceProjectBiz *biz.AdviceProjectBiz
}

// NewFileService
func NewFileService(
	adviceBiz *biz.AdviceFileBiz,
	cfg *config.Config,
	adviceProjectBiz *biz.AdviceProjectBiz,
) *FileService {
	return &FileService{
		adviceBiz:        adviceBiz,
		cfg:              cfg,
		adviceProjectBiz: adviceProjectBiz,
	}
}

func (a *FileService) WordAna(c *fiber.Ctx) error {
	req := &entitys.WordAnaReq{}
	if err := c.BodyParser(req); err != nil {
		return err
	}
	if req.ProjectId == 0 {
		return errorcode.ParamErr("ProjectId is empty")
	}
	//项目信息
	projectInfo, err := a.adviceProjectBiz.Info(c.UserContext(), &entitys.AdvicerProjectInfoReq{
		ProjectId: req.ProjectId,
	})
	if err != nil {
		return err
	}
	// URL 解码
	fileURL, err := url.PathUnescape(req.WordFileUrl)
	if err != nil {
		return errors.New("URL 解码失败")
	}
	result, _, err := file_download.GetWordTextFromURL(fileURL, file_download.IsWordFile)
	if err != nil {
		return err
	}
	ana, err := a.adviceBiz.WordAna(context.Background(), result, projectInfo)
	if err != nil {
		return err
	}
	err = c.JSON(ana)
	return err
}

func (a *FileService) WordAnat(path string) ([]byte, error) {

	// URL 解码
	projectInfo, err := a.adviceProjectBiz.Info(context.Background(), &entitys.AdvicerProjectInfoReq{
		ProjectId: 127,
	})
	fileURL, err := url.PathUnescape(path)
	if err != nil {
		return nil, errors.New("URL 解码失败")
	}
	result, _, err := file_download.GetWordTextFromURL(fileURL, file_download.IsWordFile)
	if err != nil {
		return nil, err
	}
	ana, err := a.adviceBiz.WordAna(context.Background(), result, projectInfo)
	if err != nil {
		return nil, err
	}

	return pkg.JsonByteIgonErr(ana), err
}
