package lxrod

import (
	"context"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"git.listensoft.net/tool/jspkit/common/clients"
	"git.listensoft.net/tool/jspkit/common/models"
	"git.listensoft.net/tool/jspkit/common/path"
	"github.com/go-rod/rod"
	"go.uber.org/zap"
)

// 截图并上传
func PostScreenshot(l *zap.Logger, p *rod.Page, task *models.TaxTask) error {
	l.Debug("尝试保存截图")
	imgPath := path.GetErrImgPath(task.TaxNo, task.Period)
	bin, err := p.Timeout(10*time.Second).Screenshot(false, nil)
	if err != nil {
		l.Error("截图创建失败", zap.Error(err))
		return err
	}
	err = os.WriteFile(imgPath, bin, 0666)
	if err != nil {
		l.Error("截图保存失败", zap.Error(err))
		return err
	}
	l.Info("截图保存成功", zap.String("path", imgPath))

	l.Debug("尝试上传截图")
	ctx, cancel := context.WithTimeout(p.GetContext(), 30*time.Second)
	defer cancel()

	fc := clients.FileClient{
		Client: http.DefaultClient,
		Logger: l,
	}
	businessImg, err := fc.PostScreenShotBytes(ctx, bin, clients.PostScreenShotReq{
		Name:   filepath.Base(imgPath),
		TaxNo:  task.TaxNo,
		Period: task.Period,
	})
	if err != nil {
		l.Error("截图上传失败", zap.Error(err))
		return err
	}

	l.Info("截图上传成功", zap.String("businessImg", businessImg))
	task.Result.BusinessImg = businessImg
	return nil
}
