package player

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3/s3manager"
	jsoniter "github.com/json-iterator/go"
	mhayaString "github.com/mhaya/extend/string"
	cfacade "github.com/mhaya/facade"
	"github.com/mhaya/game/game_cluster/internal/data"
	clog "github.com/mhaya/logger"
	"github.com/mhaya/net/parser/pomelo"
	"io"
	"net/http"
	"time"
)

type (
	// ActorAvatar 玩家头像管理actor
	ActorAvatar struct {
		pomelo.ActorBase
		isOnline      bool
		openId        string
		avatar        string
		userName      string
		dirty         bool
		childExitTime time.Duration
	}

	UserAvatar struct {
		openId   string
		avatar   string
		userName string
	}
)

func (p *ActorAvatar) OnInit() {
	p.childExitTime = time.Minute * 3
	clog.Debugf("[ActorAvatar] path = %s init!", p.PathString())
	p.Remote().Register("setAvatar", p.setAvatar)
	p.Remote().Register("sessionClose", p.sessionClose)
	p.Timer().Add(10*time.Second, p.getAndUpdateAvatar)
	p.Timer().Add(30*time.Second, p.getAndUpdateAvatar)
	//p.Timer().Add(2*time.Minute, p.SetDb)
}

func (p *ActorAvatar) sessionClose() {
	if p.isOnline {
		p.isOnline = false
		p.Exit()
	}
}

func (p *ActorAvatar) setAvatar(req *UserAvatar) {
	p.isOnline = true
	p.openId = req.openId
	p.avatar = req.avatar
	p.dirty = true
	clog.Infof("[ActorAvatar] init userAvatar = %v", req)
}

// 获取和更新头像
func (p *ActorAvatar) getAndUpdateAvatar() {
	if p.isOnline && p.dirty {
		p.dirty = false
		go p.getAvatar()
	}
}

func (p *ActorAvatar) getAvatar() {
	openid, _ := mhayaString.ToInt64(p.openId)

	// 使用自定义 Transport 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 10 * time.Second, // 设置超时时间
	}

	sdkConfig := data.SdkConfig.Get(2).Params

	url := fmt.Sprintf("https://api.telegram.org/bot%s/getUserProfilePhotos?user_id=%d", sdkConfig.BotToken, openid)

	// 发起 HTTP 请求
	req, err := http.NewRequestWithContext(context.Background(), "GET", url, nil)
	if err != nil {
		clog.Warnf("Failed to create request: %v", err)
		return
	}

	resp, err := client.Do(req)
	if err != nil {
		clog.Warnf("Failed to send request: %v", err)
		return
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		clog.Warnf("Error reading body: %v", err)
		return
	}
	var result struct {
		Ok     bool `json:"ok"`
		Result struct {
			Photos [][]struct {
				FileID string `json:"file_id"`
			} `json:"photos"`
		} `json:"result"`
	}

	err = jsoniter.Unmarshal(body, &result)
	if err != nil {
		clog.Warnf("Error unmarshalling JSON: %v", err)
		return
	}

	if !result.Ok {
		clog.Warnf("Error: %s", string(body))
		return
	}
	if len(result.Result.Photos) == 0 {
		clog.Warnf("No photos found for user %d", openid)
		return
	}

	if len(result.Result.Photos) > 0 {
		// 获取第一张照片的最大尺寸
		photo := result.Result.Photos[0][len(result.Result.Photos[0])-1]

		//根据数据库记录判断是否需要更新图片库
		if photo.FileID != p.avatar {
			if p.uploadPhotoToS3(client, sdkConfig.BotToken, photo.FileID, openid) == true {
				p.avatar = photo.FileID
				targetPath := cfacade.NewChildPath(p.App().NodeId(), "player"+p.App().NodeId(), p.userName)
				p.Call(targetPath, "setAvatar", &UserAvatar{avatar: p.avatar, openId: p.openId, userName: p.userName})
			}
		}
	}
}

func (p *ActorAvatar) uploadPhotoToS3(client *http.Client, botToken, fileId string, openid int64) bool {

	s3 := data.SdkConfig.Get(2).S3

	url := fmt.Sprintf("https://api.telegram.org/bot%s/getFile?file_id=%s", botToken, fileId)

	// 发起 HTTP 请求
	req, err := http.NewRequestWithContext(context.Background(), "GET", url, nil)
	if err != nil {
		clog.Warnf("Failed to create request: %v", err)
		return false
	}

	resp, err := client.Do(req)

	if err != nil {
		clog.Warnf("Failed to send request: %v", err)
		return false
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		clog.Warnf("Error reading body: %v", err)
		return false
	}

	var fileInfo struct {
		Ok     bool `json:"ok"`
		Result struct {
			FilePath string `json:"file_path"`
		} `json:"result"`
	}

	err = jsoniter.Unmarshal(body, &fileInfo)
	if err != nil {
		clog.Warnf("Error unmarshalling JSON: %v", err)
		return false
	}

	if !fileInfo.Ok {
		clog.Warnf("Error: %s", string(body))
		return false
	}

	downloadUrl := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", botToken, fileInfo.Result.FilePath)

	resp, err = client.Get(downloadUrl)
	if err != nil {
		clog.Warnf("Error: %v", err)
		return false
	}
	defer resp.Body.Close()

	// 配置 AWS 凭证
	sess, err := session.NewSession(&aws.Config{
		Credentials: credentials.NewStaticCredentials(
			s3.AccessKey,
			s3.SecretKey,
			"",
		),
		Region: aws.String(s3.Region), // 替换为你的 S3 区域
	})

	uploader := s3manager.NewUploader(sess)

	// 上传文件到 S3
	_, err = uploader.Upload(&s3manager.UploadInput{
		Bucket: aws.String(s3.BucketName),                        // S3 存储桶名称
		Key:    aws.String(fmt.Sprintf("avatar/%d.jpg", openid)), //当前目录存储文件
		Body:   resp.Body,
		ACL:    aws.String("private"), // 可以根据需要设置 ACL
	})

	if err != nil {
		clog.Warnf("Error uploading file: %v", err)
		return false
	}
	return true

}

func (p *ActorAvatar) OnStop() {
	clog.Infof("ActorAvatar stop")
}
