package controllers

import (
	"aon_app_server/models"
	"aon_app_server/utils/aonsupabase"
	"aon_app_server/utils/mongo"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/fogleman/gg"
	"github.com/h2non/filetype"
	storage_go "github.com/supabase-community/storage-go"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"golang.org/x/image/webp"
	"gopkg.in/yaml.v2"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"time"
)

type TaskController struct {
	MainController
}

var supportModels map[string]*models.Model

func init() {
	err := readYAML("./conf/replicate_models_version.yaml", &supportModels)
	if err != nil {
		logs.Debug("Error reading YAML file: %v", err)
	}
}

var execTasks = make(chan *models.Task, 100)

func (server *TaskController) Prediction() {
	body := server.Ctx.Input.RequestBody
	task := models.Task{}
	err := json.Unmarshal(body, &task) //解析body中数据
	logs.Debug("appRequest", task)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	asyncString := server.Ctx.Input.Header("Async")
	async := false
	if asyncString == "true" {
		async = true
	}
	task.CreatedTime = time.Now().UTC()
	task.UpdatedTime = task.CreatedTime
	id, err := mongo.Insert(&task)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	task.Id = id
	whois, _ := beego.AppConfig.String("whoisApi")
	var result interface{}
	if whois == "aonet" {
		result, err = sendTask(&task, async)
	} else if whois == "replicate" {
		result, err = sendReplicate(&task, async)
	}

	if err != nil {
		server.respond(http.StatusOK, err.Error())
		return
	}
	if async {
		response := struct {
			Task     *models.TaskReturn `json:"task"`
			ExcuteId string             `json:"excute_id"`
		}{
			Task: &models.TaskReturn{
				Async: async,
			},
			ExcuteId: task.ExcuteId,
		}
		server.respond(http.StatusOK, "", response)
		return
	}
	//if whois == "replicate" {
	//	temp := models.TaskResponseNew{}
	//	if err = json.Unmarshal(body, &temp); err != nil {
	//		server.respond(http.StatusInternalServerError, err.Error())
	//		return
	//	}
	//	if temp.Error != nil {
	//		server.respond(http.StatusInternalServerError, "", temp)
	//		return
	//	}
	//}
	server.respond(http.StatusOK, "", result)
}

func copyImages(images []string) []string {
	imagesToCopy := models.ImagesToCopy{
		Sources: images,
	}
	url, _ := beego.AppConfig.String("imageUrl")
	payload := new(bytes.Buffer)
	json.NewEncoder(payload).Encode(imagesToCopy)
	resp, err := http.Post(url, "application/json;charset=UTF-8", payload)
	if err != nil {
		logs.Info("Error sending request:", err)
		return images
	}
	defer resp.Body.Close()
	logs.Info("copyImages resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logs.Info("Error reading response:", err)
		return images
	}
	logs.Debug("copyImages body", string(body))

	var response []models.ImageCopied
	if err := json.Unmarshal(body, &response); err != nil {
		return images
	}
	var backImages []string
	for _, value := range response {
		if value.Code == 200 {
			backImages = append(backImages, value.Data)
		}
	}
	if len(backImages) > 0 {
		return backImages
	}
	return images
}

func transferImages(images []string) []string {

	imagesToCopy := models.ImagesToCopy{
		Sources: images,
	}
	url, _ := beego.AppConfig.String("imageTransferUrl")
	payload := new(bytes.Buffer)
	json.NewEncoder(payload).Encode(imagesToCopy)
	resp, err := http.Post(url, "application/json;charset=UTF-8", payload)
	if err != nil {
		logs.Info("Error sending request:", err)
		return images
	}
	defer resp.Body.Close()
	logs.Info("transferImages resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logs.Info("Error reading response:", err)
		return images
	}
	logs.Debug("transferImages body", string(body))

	var response []models.ImageCopied
	if err := json.Unmarshal(body, &response); err != nil {
		return images
	}
	var backImages []string
	for _, value := range response {
		if value.Code == 200 {
			backImages = append(backImages, value.Data)
		}
	}
	if len(backImages) > 0 {
		return backImages
	}
	return images
}

func FindWatermarkFields(node models.JSONNode, prefix string, result *[]string) {
	for key, value := range node {
		newPrefix := key
		if prefix != "" {
			newPrefix = prefix + "." + key
		}
		if subNode, ok := value.(map[string]interface{}); ok {
			FindWatermarkFields(subNode, newPrefix, result)
		} else if key == "watermark" && value == true {
			*result = append(*result, prefix)
		}
	}
}

func checkFileIsImage(files []string) int {
	for _, value := range files {
		_, ext := parseUrl(value)
		if ext == "jpeg" || ext == ".jpeg" || ext == ".jpg" || ext == "jpg" || ext == "png" || ext == ".png" || ext == "webp" || ext == ".webp" {
			return 1
		}
		if ext == "mp4" || ext == ".mp4" {
			return 2
		}
	}
	return 0
}

func findValueByPath(data interface{}, path string) (interface{}, bool) {
	// 分割路径成键的切片
	keys := strings.Split(path, ".")
	if len(keys) == 0 {
		return nil, false
	}

	// 遍历路径中的键
	for _, key := range keys {
		if key == "" || key == "properties" {
			continue
		}
		switch v := data.(type) {
		case map[string]interface{}:
			if nextData, ok := v[key]; ok {
				data = nextData
			} else {
				return nil, false
			}
		case models.JSONNode:
			if nextData, ok := v[key]; ok {
				data = nextData
			} else {
				return nil, false
			}
		default:
			return nil, false
		}
	}
	return data, true
}

func transferImagesToS3(images []string, task *models.Task) []string {
	watermarkURL := ""
	apps, count, err := aonsupabase.MyClient.From("app").Select("", "exact", false).Eq("app_id", task.AppId).Execute()
	if err == nil {
		var temp []models.App
		if err := json.Unmarshal(apps, &temp); err != nil {
			logs.Debug("apps  Unmarshal err = ", err)
		}
		if len(temp) > 0 {
			app := temp[0]
			logs.Debug("app = ", count, app)
			var result []string
			FindWatermarkFields(app.TemplateParams, "", &result)
			for _, path := range result {
				fmt.Println(path)
				value, found := findValueByPath(app.ParamsValue, path)
				if found {
					if str, ok := value.(string); ok {
						watermarkURL = str
					}
					fmt.Printf("Value at '%s': %v\n", path, value)
				}
			}
		}
	}

	var backImages []string
	for _, value := range images {
		url, _ := addWatermark(value, watermarkURL)
		if url != "" {
			backImages = append(backImages, url)
		}
	}
	if len(backImages) > 0 {
		return backImages
	}
	return images
}

func transferFileToS3(images []string, task *models.Task, needWatermark bool) []string {
	watermarkURL := ""
	apps, count, err := aonsupabase.MyClient.From("app").Select("", "exact", false).Eq("app_id", task.AppId).Execute()
	if err == nil {
		var temp []models.App
		if err := json.Unmarshal(apps, &temp); err != nil {
			logs.Debug("apps  Unmarshal err = ", err)
		}
		if len(temp) > 0 {
			app := temp[0]
			logs.Debug("app = ", count, app)
			var result []string
			FindWatermarkFields(app.TemplateParams, "", &result)
			for _, path := range result {
				fmt.Println(path)
				value, found := findValueByPath(app.ParamsValue, path)
				if found {
					if str, ok := value.(string); ok {
						watermarkURL = str
					}
					fmt.Printf("Value at '%s': %v\n", path, value)
				}
			}
		}
	}

	var backImages []string
	for _, value := range images {
		if needWatermark {
			fileData, data, mime, _ := addWatermarkNew(value, watermarkURL)
			if fileData != nil {
				url, err := uploadToS3New(fileData, data, mime)
				if err != nil {
					logs.Debug("uploadToS3New err = ", err)
					url, err = uploadToS3Supabase(fileData, data, mime)
				}
				if url != "" && err == nil {
					backImages = append(backImages, url)
				}
				defer fileData.Close()
				defer os.Remove(fileData.Name())
			}
		} else {
			srcImg, err := downloadFile(value)
			if err != nil {
				logs.Debug("addWatermark downloadImage faild =", value)
				continue
			}
			buffer := make([]byte, 1024)
			_, err = srcImg.Read(buffer)
			if err != nil {
				fmt.Println("Error reading file:", err)
				continue
			}
			contentType := http.DetectContentType(buffer)
			url, _ := uploadToS3New(srcImg, buffer, contentType)
			if url != "" {
				backImages = append(backImages, url)
			}
			defer srcImg.Close()
			defer os.Remove(srcImg.Name())
		}
	}
	if len(backImages) > 0 {
		return backImages
	}
	return images
}

func decodeWebP(file *os.File) (image.Image, error) {

	img, err := webp.Decode(file)
	if err != nil {
		return nil, err
	}

	return img, nil
}

func downloadImage(url string) (image.Image, string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, "", err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	kind, err := filetype.Match(body)
	if err != nil {
		logs.Debug("filetype.Match error = ", err)
		return nil, "", err
	}
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	file, err := os.Create("./" + timestampStr + "_download_replicate_img." + kind.Extension)
	defer file.Close()
	defer os.Remove(file.Name())
	if err != nil {
		fmt.Println("Error creating file:", err)
		return nil, "", err
	}
	_, err = file.Write(body)
	if err != nil {
		fmt.Println("Error writing to file:", err)
		return nil, "", err
	}
	img, format, err := image.Decode(resp.Body)
	if err != nil {
		mime := kind.MIME.Value
		if mime == "image/webp" {
			format = "webp"
			img, err = decodeWebP(file)
			if err != nil {
				return nil, "", err
			}
		} else if mime == "image/png" {
			img, err = png.Decode(file)
			if err != nil {
				return nil, "", err
			}
		} else {
			return nil, "", err
		}

	}
	return img, format, nil
}

func downloadFile(url string) (*os.File, error) {
	// 从 URL 下载文件
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 创建临时文件
	tmpFile, err := os.CreateTemp("", "downloaded-*"+filepath.Ext(url))
	if err != nil {
		return nil, err
	}

	// 将响应数据写入临时文件
	_, err = io.Copy(tmpFile, resp.Body)
	if err != nil {
		return nil, err
	}

	// 重置文件偏移量
	_, err = tmpFile.Seek(0, io.SeekStart)
	if err != nil {
		return nil, err
	}

	return tmpFile, nil
}

func ImageToFile(filename string, img image.Image, format string) (*os.File, []byte, error) {
	// 创建文件
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	width := img.Bounds().Dx()
	height := img.Bounds().Dy()
	filename = timestampStr + "_" + "width=" + strconv.Itoa(width) + "&height=" + strconv.Itoa(height) + "_" + filename
	file, err := os.Create(filename)
	if err != nil {
		return nil, nil, err
	}

	buf := new(bytes.Buffer)
	if format == "jpeg" || format == ".jpeg" || format == ".jpg" || format == "jpg" {
		err = jpeg.Encode(buf, img, nil)
	} else if format == "png" || format == ".png" {
		err = png.Encode(buf, img)
	} else {
		file.Close()
		return nil, nil, err
	}

	_, err = file.Write(buf.Bytes())
	if err != nil {
		fmt.Println("Error writing to file:", err)
		return nil, nil, err
	}

	// 返回文件指针
	return file, buf.Bytes(), nil
}

func uploadToS3(bucket, key string, img image.Image, format string) (string, error) {
	awsAccessKeyID, _ := beego.AppConfig.String("awsAccessKeyID")
	awsSecretAccessKey, _ := beego.AppConfig.String("awsSecretAccessKey")
	awsSsessionToken, _ := beego.AppConfig.String("awsSsessionToken")
	region, _ := beego.AppConfig.String("region")
	creds := credentials.NewStaticCredentialsProvider(awsAccessKeyID, awsSecretAccessKey, awsSsessionToken)
	cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region), config.WithCredentialsProvider(creds))
	//sess, err := session.NewSession(&aws.Config{
	//	Region:      region,
	//	Credentials: credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, ""),
	//})
	if err != nil {
		return "", err
	}

	client := s3.NewFromConfig(cfg)

	buf := new(bytes.Buffer)
	if format == "jpeg" || format == ".jpeg" || format == ".jpg" || format == "jpg" {
		err = jpeg.Encode(buf, img, nil)
	} else if format == "png" || format == ".png" {
		err = png.Encode(buf, img)
	} else {
		return "", err
	}
	if err != nil {
		return "", err
	}

	filePath := "watermark"

	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	width := img.Bounds().Dx()
	height := img.Bounds().Dy()
	key = filePath + "/" + timestampStr + "_" + "width=" + strconv.Itoa(width) + "&height=" + strconv.Itoa(height) + "_" + key

	_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		Body:   bytes.NewReader(buf.Bytes()),
		ACL:    types.ObjectCannedACLPublicRead, // 可根据需要更改
	})
	returnUrl := "https://" + bucket + ".s3.amazonaws.com/" + key
	return returnUrl, err
	//presignClient := s3.NewPresignClient(client)
	//presignResult, err := presignClient.PresignGetObject(context.TODO(), &s3.GetObjectInput{
	//	Bucket: &bucket,
	//	Key:    &key,
	//})
	//if err != nil {
	//	logs.Debug("failed to presign request, %v", err)
	//	return "", err
	//}
	//return presignResult.URL, err
}

func uploadToS3New(file *os.File, data []byte, mime string) (string, error) {
	awsAccessKeyID, _ := beego.AppConfig.String("awsAccessKeyID")
	awsSecretAccessKey, _ := beego.AppConfig.String("awsSecretAccessKey")
	awsSsessionToken, _ := beego.AppConfig.String("awsSsessionToken")
	bucketName, _ := beego.AppConfig.String("bucketName")
	region, _ := beego.AppConfig.String("region")
	creds := credentials.NewStaticCredentialsProvider(awsAccessKeyID, awsSecretAccessKey, awsSsessionToken)
	cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region), config.WithCredentialsProvider(creds))
	//sess, err := session.NewSession(&aws.Config{
	//	Region:      region,
	//	Credentials: credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, ""),
	//})
	if err != nil {
		return "", err
	}
	fileInfo, err := file.Stat()
	if err != nil {
		return "", err
	}

	client := s3.NewFromConfig(cfg)

	filePath := "watermark"

	key := filePath + "/" + fileInfo.Name()

	//size := fileInfo.Size()
	_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:      aws.String(bucketName),
		Key:         aws.String(key),
		Body:        bytes.NewReader(data),
		ContentType: aws.String(mime),
		ACL:         types.ObjectCannedACLPublicRead, // 可根据需要更改
	})
	returnUrl := "https://" + bucketName + ".s3.amazonaws.com/" + key
	if err != nil {
		logs.Debug("S3 ", err)
		return "", err
	}
	return returnUrl, err
	//presignClient := s3.NewPresignClient(client)
	//presignResult, err := presignClient.PresignGetObject(context.TODO(), &s3.GetObjectInput{
	//	Bucket: &bucket,
	//	Key:    &key,
	//})
	//if err != nil {
	//	logs.Debug("failed to presign request, %v", err)
	//	return "", err
	//}
	//return presignResult.URL, err
}

func uploadToS3Supabase(file *os.File, data []byte, mime string) (string, error) {

	fileInfo, err := file.Stat()
	if err != nil {
		return "", err
	}
	kind, err := filetype.Match(data)
	if err != nil {
		logs.Debug("filetype.Match error = ", err)
		return "", err
	}
	temo := "no-cache"
	mime = kind.MIME.Value
	upsert := false
	options := storage_go.FileOptions{
		ContentType:  &mime,
		CacheControl: &temo,
		Upsert:       &upsert,
	}
	key := "watermark/" + fileInfo.Name()
	_, err = aonsupabase.MyClient.Storage.UploadFile("prediction_result", key, bytes.NewReader(data), options)
	if err != nil {
		return "", err
	}

	url := aonsupabase.MyClient.Storage.GetPublicUrl("prediction_result", key)

	return url.SignedURL, err
}

func addWatermark(sourceURL string, watermarkURL string) (string, error) {
	bucketName, _ := beego.AppConfig.String("bucketName")
	outputKey, ext := parseUrl(sourceURL)

	// 下载源图
	srcImg, _, err := downloadImage(sourceURL)
	if err != nil {

		logs.Debug("addWatermark downloadImage faild =", sourceURL)
		return "", err
	}

	// 下载水印图
	var watermarkImg image.Image
	if watermarkURL == "" {
		imgFile, err := os.Open("./watermark.png")
		if err != nil {
			logs.Debug("read watermark faild")
		}
		defer imgFile.Close()
		watermarkImg, err = png.Decode(imgFile)
		if err != nil {
			logs.Debug("Decode watermark faild")
		}
	} else {
		watermarkImg, _, err = downloadImage(watermarkURL)
		if err != nil {
			logs.Debug("downloadImage watermark faild", err)
		}
	}

	// 创建绘图上下文
	dc := gg.NewContextForImage(srcImg)

	width := watermarkImg.Bounds().Dx()
	height := watermarkImg.Bounds().Dy()
	// 添加水印
	if watermarkImg != nil {
		dc.DrawImageAnchored(watermarkImg, (dc.Width()-width)/2, dc.Height()-height-80, 0, 0) // 在中心添加水印
	}

	// 获取合成后的图像
	outputImg := dc.Image()

	// 上传到 S3
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	outputKey = timestampStr + ".png"
	s3Url, err := uploadToS3(bucketName, outputKey, outputImg, ".png")
	if err != nil {
		logs.Debug("uploadToS3 faild", err)
		file, data, err := ImageToFile(outputKey, outputImg, ext)

		if err != nil {
			return "", err
		}
		s3Url, err = uploadToS3Supabase(file, data, "")
		if err != nil {
			return "", err
		}
		defer file.Close()
		defer os.Remove(file.Name())
	}

	return s3Url, nil
}

func addWatermarkNew(sourceURL string, watermarkURL string) (*os.File, []byte, string, error) {
	// 下载源图
	srcImg, err := downloadFile(sourceURL)
	if err != nil {
		logs.Debug("addWatermarkNew downloadImage faild =", sourceURL)
		return nil, nil, "", err
	}

	// 下载水印图
	var watermarkImg *os.File
	if watermarkURL == "" {
		watermarkImg, err = os.Open("./watermark.png")
		if err != nil {
			logs.Debug("read watermark faild")
		}
		defer watermarkImg.Close()
	} else {
		watermarkImg, err = downloadFile(watermarkURL)
		if err != nil {
			logs.Debug("addWatermarkNew watermark faild", err)
		}
	}

	host, _ := beego.AppConfig.String("watermarkUrl")
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)

	partA, err := writer.CreateFormFile("input", filepath.Base(srcImg.Name()))
	if err != nil {
		fmt.Println("Error creating form file A:", err)
		return nil, nil, "", err
	}
	_, err = io.Copy(partA, srcImg)
	if err != nil {
		fmt.Println("Error copying file A:", err)
		return nil, nil, "", err
	}

	partB, err := writer.CreateFormFile("watermark", filepath.Base(watermarkImg.Name()))
	if err != nil {
		fmt.Println("Error creating form file B:", err)
		return nil, nil, "", err
	}
	_, err = io.Copy(partB, watermarkImg)
	if err != nil {
		fmt.Println("Error copying file B:", err)
		return nil, nil, "", err
	}
	err = writer.Close()
	if err != nil {
		fmt.Println("Error closing writer:", err)
		return nil, nil, "", err
	}
	client := &http.Client{}
	request, err := http.NewRequest("POST", host, payload)
	if err != nil {
		logs.Info("addWatermarkNew Error NewRequest request:", err)
		return nil, nil, "", err
	}
	request.Header.Set("Content-Type", writer.FormDataContentType())

	logs.Info("addWatermarkNew client sending request:")
	resp, err := client.Do(request)
	if err != nil {
		logs.Info("addWatermarkNew Error sending request:", err)
		return nil, nil, "", err
	}
	defer resp.Body.Close()
	logs.Info("addWatermarkNew resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	//logs.Info("addWatermarkNew body", string(body))
	if resp.StatusCode == 200 && body == nil {
		logs.Info("addWatermarkNew Body reading response:", err)
		return nil, nil, "", err
	}
	if err != nil {
		logs.Info("addWatermarkNew Error reading response:", err)
		return nil, nil, "", err
	}

	// 创建临时文件
	kind, err := filetype.Match(body)
	if err != nil {
		logs.Debug("filetype.Match error = ", err)
		return nil, nil, "", err
	}
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	file, err := os.Create("./" + timestampStr + "_watermarked_file." + kind.Extension)
	if err != nil {
		fmt.Println("Error creating file:", err)
		return nil, nil, "", err
	}
	//defer file.Close()
	_, err = file.Write(body)
	if err != nil {
		fmt.Println("Error writing to file:", err)
		return nil, nil, "", err
	}

	//tmpFile, err := os.CreateTemp("", timestampStr+"_watermarked-*."+kind.Extension)
	//if err != nil {
	//	return nil, nil, "", err
	//}
	//
	//// 将响应数据写入临时文件
	//_, err = io.Copy(tmpFile, resp.Body)
	//if err != nil {
	//	return nil, nil, "", err
	//}
	//
	//// 重置文件偏移量
	//_, err = tmpFile.Seek(0, io.SeekStart)
	//if err != nil {
	//	return nil, nil, "", err
	//}

	return file, body, kind.MIME.Value, nil
}

func parseUrl(urlStr string) (string, string) {
	// 解析 URL
	u, err := url.Parse(urlStr)
	if err != nil {
		fmt.Println("解析 URL 时出错:", err)
		return "", ""
	}

	// 从 URL 中提取路径
	filePath := u.Path

	// 提取文件名
	fileName := path.Base(filePath)

	// 提取扩展名
	ext := path.Ext(fileName)

	// 提取文件名（不包含扩展名）
	//nameWithoutExt := strings.TrimSuffix(fileName, ext)

	return fileName, ext
}

func sendTask(task *models.Task, async bool) (*models.TaskResponse, error) {
	host, _ := beego.AppConfig.String("taskUrl")
	url := host + task.ApiPath
	payload := new(bytes.Buffer)
	//var input interface{}
	//if err := json.Unmarshal([]byte(task.Input), &input); err != nil {
	//	setError(task, "task.Input Unmarshal error:"+err.Error())
	//	logs.Info("sendTask task.Input Unmarshal response:", err)
	//	return nil, err
	//}
	json.NewEncoder(payload).Encode(task.Input)
	client := &http.Client{}
	request, err := http.NewRequest("POST", url, payload)
	if err != nil {
		setError(task, "sendTask request create error:"+err.Error())
		logs.Info("sendTask Error NewRequest request:", err)
		return nil, err
	}
	apikey, _ := beego.AppConfig.String("apikey")
	request.Header.Add("apikey", apikey)

	logs.Info("sendTask client sending request:")
	resp, err := client.Do(request)
	if err != nil {
		setError(task, "Task sending error:"+err.Error())
		logs.Info("sendTask Error sending request:", err)
		return nil, err
	}
	defer resp.Body.Close()
	logs.Info("sendTask resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	logs.Info("sendTask body", string(body))
	if resp.StatusCode == 200 && body == nil {
		setError(task, "Task response body null")
		logs.Info("sendTask Body reading response:", err)
		return nil, err
	}
	if err != nil {
		setError(task, "Task read response body error:"+err.Error())
		logs.Info("sendTask Error reading response:", err)
		return nil, err
	}
	var response models.TaskResponse
	if err = json.Unmarshal(body, &response); err != nil {
		setError(task, "Task response Unmarshal error:"+err.Error())
		logs.Info("sendTask Error Unmarshal response:", err)
		return nil, err
	}
	taskId := resp.Header.Get("task-id")
	task.TaskId = taskId
	task.UpdatedTime = time.Now().UTC()
	if response.Task.IsSuccess {
		task.Status = 2
		var output []string
		if slice, ok := response.Output.([]string); ok {
			fmt.Println("i 是字符串数组类型，值为:", slice)
			output = slice
		}
		task.Output = copyImages(output)
		mongo.Update(task)
		response.Output = task.Output
	} else {
		task.Status = 3
		task.Error = response.Task
		_, err = mongo.Update(task)
		if err != nil {
			logs.Info("Update Task Error:", err)
		}
	}
	return &response, nil
}

func readYAML(filename string, out interface{}) error {
	data, err := os.ReadFile(filename)
	if err != nil {
		return err
	}

	err = yaml.Unmarshal(data, out)
	if err != nil {
		return err
	}

	return nil
}

func sendReplicate(task *models.Task, async bool) (*models.TaskResponse, error) {
	host, _ := beego.AppConfig.String("replicateUrl")
	url := host
	payload := new(bytes.Buffer)
	v := reflect.ValueOf(task.Input)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	var input interface{}
	for _, key := range v.MapKeys() {
		value := v.MapIndex(key).Interface()
		keyStr := fmt.Sprintf("%v", key.Interface())
		logs.Debug("keyStr: value\n", keyStr, value)
		if keyStr == "input" {
			input = value
		}
	}
	//versions := map[string]string{
	//	"pulid":     "43d309c37ab4e62361e5e29b8e9e867fb2dcbcec77ae91206a8d95ac5dd451a0",
	//	"idm-vton":  "906425dbca90663ff5427624839572cc56ea7d380343d13e2a4c4b09d3f0c30f",
	//	"face-swap": "bc479d7d8ecc50eb83839af0c28210db75cac9c23837e2722028df4cddfafa22",
	//}
	parts := strings.Split(task.ApiPath, "/")
	lastElement := task.ApiPath
	if len(parts) > 2 {
		lastElement = parts[len(parts)-1]
	}
	//version := versions[lastElement]
	//version, _ := beego.AppConfig.String(lastElement)
	//model, _ := config.GetSection(lastElement)
	model := supportModels[lastElement]
	taskReturn := &models.TaskReturn{
		Async: async,
	}
	taskResponse := &models.TaskResponse{
		Task: taskReturn,
	}
	if model == nil {
		task.Status = 3
		taskReturn.ExecError = "It`s not open yet."
		task.Error = taskResponse.Task
		_, err := mongo.Update(task)
		if err != nil {
			logs.Info("Update Task Error:", err)
		}
		return taskResponse, nil
	}
	data := models.ReplicateRequest{
		Version: model.Version,
		Input:   input,
		Stream:  model.Stream,
	}
	url = model.Url
	json.NewEncoder(payload).Encode(data)
	client := &http.Client{}
	request, err := http.NewRequest("POST", url, payload)
	if err != nil {
		setError(task, "sendReplicate request create error:"+err.Error())
		logs.Info("sendReplicate Error NewRequest request:", err)
		return nil, err
	}
	apikey, _ := beego.AppConfig.String("replicateToken")
	request.Header.Add("Authorization", "Bearer "+apikey)

	logs.Info("sendReplicate client sending request:")
	resp, err := client.Do(request)
	if err != nil {
		setError(task, "Task sending error:"+err.Error())
		logs.Info("sendReplicate Error sending request:", err)
		return nil, err
	}
	defer resp.Body.Close()
	logs.Info("sendReplicate resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	logs.Info("sendReplicate body", string(body))
	if resp.StatusCode == 200 && body == nil {
		setError(task, "Task response body null")
		logs.Info("sendReplicate Body reading response:", err)
		return nil, err
	}
	if err != nil {
		setError(task, "Task read response body error:"+err.Error())
		logs.Info("sendReplicate Error reading response:", err)
		return nil, err
	}
	var response models.ReplicateResponse
	if err = json.Unmarshal(body, &response); err != nil {
		setError(task, "Task response Unmarshal error:"+err.Error())
		logs.Info("sendReplicate Error Unmarshal response:", err)
		taskReturn.ExecError = string(body)
		taskResponse.Task = taskReturn
		return taskResponse, nil
	}
	if response.Urls.Get != "" || (model.Stream && response.Urls.Stream != "") {
		//replicateTimeout, _ := beego.AppConfig.Int("replicateTimeout")
		//
		//timeout := time.After(time.Duration(replicateTimeout) * time.Minute)
		//
		//for {
		//	select {
		//	case <-timeout:
		//		logs.Info("Operation timed out")
		//		task.Status = 4 // 4表示超时状态
		//		taskReturn.TaskError = "Operation timed out"
		//		taskResponse.Task = taskReturn
		//		task.Error = taskResponse.Task
		//		_, err := mongo.Update(task)
		//		if err != nil {
		//			logs.Info("Update Task Error:", err)
		//		}
		//		return taskResponse, nil
		//	default:
		//		temp, err := getReplicate(response.Urls.Get)
		//		if err != nil {
		//			logs.Info("getReplicate Task Error:", err)
		//		}
		//		logs.Info("getReplicate Task temp:", temp)
		//		if temp != nil && temp.Status == "succeeded" {
		//			//todo 返回
		//			var output []string
		//			if str, ok := temp.Output.(string); ok {
		//				fmt.Println("i 是字符串类型，值为:", str)
		//				output = append(output, str)
		//			}
		//			if slice, ok := temp.Output.([]string); ok {
		//				fmt.Println("i 是字符串数组类型，值为:", slice)
		//				output = slice
		//			}
		//			if slice, ok := temp.Output.([]interface{}); ok {
		//				fmt.Println("i 是interface{}数组类型，值为:", slice)
		//				for _, value := range slice {
		//					if str, ok := value.(string); ok {
		//						fmt.Println("i 是字符串类型，值为:", str)
		//						output = append(output, str)
		//					}
		//				}
		//			}
		//			if slice, ok := temp.Output.(map[string]string); ok {
		//				fmt.Println("i 是map类型，值为:", slice)
		//				for _, value := range slice {
		//					output = append(output, value)
		//				}
		//			}
		//			task.Status = 2
		//			task.Output = output
		//			mongo.Update(task)
		//			taskResponse.Output = task.Output
		//			taskResponse.Task.IsSuccess = true
		//			taskResponse.Task.ExecCode = 200
		//
		//			return taskResponse, nil
		//		} else if temp != nil && temp.Error != nil {
		//			task.Status = 3
		//			if response.Error != nil {
		//				data, err := json.Marshal(response.Error)
		//				if err != nil {
		//					logs.Info("sendTask response.Task Unmarshal response:", err)
		//				}
		//				if data != nil && len(data) > 0 {
		//					taskReturn.ExecError = string(data)
		//				}
		//				taskResponse.Task = taskReturn
		//				task.Error = taskResponse.Task
		//			}
		//			_, err = mongo.Update(task)
		//			if err != nil {
		//				logs.Info("Update Task Error:", err)
		//			}
		//			return taskResponse, nil
		//		}
		//		time.Sleep(time.Second)
		//	}
		//}

		if async {
			go doGetReplicate(response.Urls.Get, task, taskResponse, taskReturn)
			return taskResponse, nil
		}
		doGetReplicate(response.Urls.Get, task, taskResponse, taskReturn)
		return taskResponse, nil
	} else {
		task.Status = 3
		if response.Error != nil {
			data, err := json.Marshal(response.Error)
			if err != nil {
				logs.Info("sendTask response.Task Unmarshal response:", err)
			}
			if data != nil && len(data) > 0 {
				taskReturn.ExecError = string(data)
			}
			taskResponse.Task = taskReturn
			task.Error = taskResponse.Task
		}
		_, err = mongo.Update(task)
		if err != nil {
			logs.Info("Update Task Error:", err)
		}

	}
	return taskResponse, nil
}

func sendReplicateNew(task *models.Task, async bool) (*models.TaskResponseNew, error) {
	host, _ := beego.AppConfig.String("replicateUrl")
	url := host
	payload := new(bytes.Buffer)
	v := reflect.ValueOf(task.Input)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	var input interface{}
	for _, key := range v.MapKeys() {
		value := v.MapIndex(key).Interface()
		keyStr := fmt.Sprintf("%v", key.Interface())
		logs.Debug("keyStr: value\n", keyStr, value)
		if keyStr == "input" {
			input = value
		}
	}
	parts := strings.Split(task.ApiPath, "/")
	lastElement := task.ApiPath
	if len(parts) > 2 {
		lastElement = parts[len(parts)-1]
	}
	model := supportModels[lastElement]
	taskReturn := &models.TaskReturn{
		Async: async,
	}
	if model == nil {
		task.Status = 3
		taskReturn.ExecError = "It`s not open yet."
		task.Error = taskReturn
		_, err := mongo.Update(task)
		if err != nil {
			logs.Info("Update Task Error:", err)
		}
		return nil, errors.New("It`s not open yet.")
	}
	data := models.ReplicateRequest{
		Version: model.Version,
		Input:   input,
		Stream:  model.Stream,
	}
	url = model.Url
	json.NewEncoder(payload).Encode(data)
	client := &http.Client{}
	request, err := http.NewRequest("POST", url, payload)
	if err != nil {
		setError(task, "sendReplicate request create error:"+err.Error())
		logs.Info("sendReplicate Error NewRequest request:", err)
		return nil, err
	}
	apikey, _ := beego.AppConfig.String("replicateToken")
	request.Header.Add("Authorization", "Bearer "+apikey)

	logs.Info("sendReplicate client sending request:")
	resp, err := client.Do(request)
	if err != nil {
		setError(task, "Task sending error:"+err.Error())
		logs.Info("sendReplicate Error sending request:", err)
		return nil, err
	}
	defer resp.Body.Close()
	logs.Info("sendReplicate resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	logs.Info("sendReplicate body", string(body))
	if resp.StatusCode == 200 && body == nil {
		setError(task, "Task response body null")
		logs.Info("sendReplicate Body reading response:", err)
		return nil, err
	}
	if err != nil {
		setError(task, "Task read response body error:"+err.Error())
		logs.Info("sendReplicate Error reading response:", err)
		return nil, err
	}
	var response models.ReplicateResponse
	if err = json.Unmarshal(body, &response); err != nil {
		setError(task, "Task response Unmarshal error:"+err.Error())
		logs.Info("sendReplicate Error Unmarshal response:", err)
		return nil, err
	}
	taskResponse := &models.TaskResponseNew{}
	if response.Urls.Get != "" || (model.Stream && response.Urls.Stream != "") {
		if async {
			go doGetReplicateNew(response.Urls.Get, task, taskResponse, taskReturn)
			return taskResponse, nil
		}
		doGetReplicateNew(response.Urls.Get, task, taskResponse, taskReturn)
		return taskResponse, nil
	} else {
		task.Status = 3
		if response.Error != nil {
			task.Error = response.Error
			taskResponse.Error = response.Error
		}
		_, err = mongo.Update(task)
		if err != nil {
			logs.Info("Update Task Error:", err)
		}
	}
	return taskResponse, nil
}

func doGetReplicate(url string, task *models.Task, taskResponse *models.TaskResponse, taskReturn *models.TaskReturn) {
	replicateTimeout, _ := beego.AppConfig.Int("replicateTimeout")

	timeout := time.After(time.Duration(replicateTimeout) * time.Minute)

	for {
		select {
		case <-timeout:
			logs.Info("Operation timed out")
			task.Status = 4 // 4表示超时状态
			taskReturn.TaskError = "Operation timed out"
			taskResponse.Task = taskReturn
			task.Error = taskResponse.Task
			_, err := mongo.Update(task)
			if err != nil {
				logs.Info("Update Task Error:", err)
			}
			return
		default:
			temp, err := getReplicate(url)
			if err != nil {
				logs.Info("getReplicate Task Error:", err)
			}
			logs.Info("getReplicate Task temp:", temp)
			if temp != nil && temp.Status == "succeeded" {
				//todo 返回
				var output []string
				if str, ok := temp.Output.(string); ok {
					fmt.Println("i 是字符串类型，值为:", str)
					output = append(output, str)
				}
				if slice, ok := temp.Output.([]string); ok {
					fmt.Println("i 是字符串数组类型，值为:", slice)
					output = slice
				}
				if slice, ok := temp.Output.([]interface{}); ok {
					fmt.Println("i 是interface{}数组类型，值为:", slice)
					for _, value := range slice {
						if str, ok := value.(string); ok {
							fmt.Println("i 是字符串类型，值为:", str)
							output = append(output, str)
						}
					}
				}
				if slice, ok := temp.Output.(map[string]string); ok {
					fmt.Println("i 是map类型，值为:", slice)
					for _, value := range slice {
						output = append(output, value)
					}

				}
				if slice, ok := temp.Output.(map[string]interface{}); ok {
					fmt.Println("i 是map类型，值为:", slice)
					for _, value := range slice {
						logs.Info("getReplicate value:", value)
						if str, ok1 := value.(string); ok1 {
							fmt.Println("i 是字符串类型，值为:", str)
							output = append(output, str)
						}
						//output = append(output, value)
					}

				}
				task.Status = 2
				task.ReplicateOutput = temp.Output
				if len(output) > 0 {
					isImage := checkFileIsImage(output)
					if isImage == 1 {
						task.Output = transferFileToS3(output, task, true)
					} else if isImage == 2 {
						task.Output = transferFileToS3(output, task, true)
					} else {
						task.Output = transferImages(output)
					}
				} else {
					task.Output = temp.Output
				}

				mongo.Update(task)
				taskResponse.Output = task.Output
				taskResponse.Task.IsSuccess = true
				taskResponse.Task.ExecCode = 200
				return
			} else if temp != nil && temp.Error != nil {
				task.Status = 3
				if temp.Error != nil {
					data, err := json.Marshal(temp.Error)
					if err != nil {
						logs.Info("sendTask response.Task Unmarshal response:", err)
					}
					if data != nil && len(data) > 0 {
						taskReturn.ExecError = string(data)
					}
					taskResponse.Task = taskReturn
					task.Error = taskResponse.Task
				}
				_, err = mongo.Update(task)
				if err != nil {
					logs.Info("Update Task Error:", err)
				}
				return
			}
			time.Sleep(time.Second)
		}
	}

}

func doGetReplicateNew(url string, task *models.Task, taskResponse *models.TaskResponseNew, taskReturn *models.TaskReturn) {
	replicateTimeout, _ := beego.AppConfig.Int("replicateTimeout")

	timeout := time.After(time.Duration(replicateTimeout) * time.Minute)

	for {
		select {
		case <-timeout:
			logs.Info("Operation timed out")
			taskResponse.Error = errors.New("Operation timed out")
			task.Status = 4 // 4表示超时状态
			taskReturn.TaskError = "Operation timed out"
			task.Error = taskReturn
			_, err := mongo.Update(task)
			if err != nil {
				logs.Info("Update Task Error:", err)
			}
			return
		default:
			temp, err := getReplicate(url)
			if err != nil {
				logs.Info("getReplicate Task Error:", err)
			}
			logs.Info("getReplicate Task temp:", temp)
			if temp != nil && temp.Status == "succeeded" {
				//todo 返回
				var output []string
				if str, ok := temp.Output.(string); ok {
					fmt.Println("i 是字符串类型，值为:", str)
					output = append(output, str)
				}
				if slice, ok := temp.Output.([]string); ok {
					fmt.Println("i 是字符串数组类型，值为:", slice)
					output = slice
				}
				if slice, ok := temp.Output.([]interface{}); ok {
					fmt.Println("i 是interface{}数组类型，值为:", slice)
					for _, value := range slice {
						if str, ok := value.(string); ok {
							fmt.Println("i 是字符串类型，值为:", str)
							output = append(output, str)
						}
					}
				}
				if slice, ok := temp.Output.(map[string]string); ok {
					fmt.Println("i 是map类型，值为:", slice)
					for _, value := range slice {
						output = append(output, value)
					}

				}
				if slice, ok := temp.Output.(map[string]interface{}); ok {
					fmt.Println("i 是map类型，值为:", slice)
					for _, value := range slice {
						logs.Info("getReplicate value:", value)
						if str, ok1 := value.(string); ok1 {
							fmt.Println("i 是字符串类型，值为:", str)
							output = append(output, str)
						}
						//output = append(output, value)
					}

				}
				task.Status = 2
				task.ReplicateOutput = temp.Output
				isImage := checkFileIsImage(output)
				if isImage == 1 {
					task.Output = transferImagesToS3(output, task)
				} else {
					task.Output = transferImages(output)
				}

				mongo.Update(task)
				taskResponse.Output = temp.Output
				//taskResponse.Task.IsSuccess = true
				//taskResponse.Task.ExecCode = 200
				return
			} else if temp != nil && temp.Error != nil {
				task.Status = 3
				if temp.Error != nil {
					taskResponse.Error = temp.Error
					task.Error = temp.Error
				}
				_, err = mongo.Update(task)
				if err != nil {
					logs.Info("Update Task Error:", err)
				}
				return
			}
			time.Sleep(time.Second)
		}
	}

}

func getReplicate(url string) (*models.ReplicateResponse, error) {
	//host, _ := beego.AppConfig.String("replicateUrl")
	//url := host + task.ApiPath
	//payload := new(bytes.Buffer)
	//var input interface{}
	//if err := json.Unmarshal([]byte(task.Input), &input); err != nil {
	//	setError(task, "task.Input Unmarshal error:"+err.Error())
	//	logs.Info("sendTask task.Input Unmarshal response:", err)
	//	return nil, err
	//}
	//json.NewEncoder(payload).Encode(task.Input)
	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		logs.Info("getReplicate Error NewRequest request:", err)
		return nil, err
	}
	apikey, _ := beego.AppConfig.String("replicateToken")
	request.Header.Add("Authorization", "Bearer "+apikey)

	logs.Info("getReplicate client sending request:")
	resp, err := client.Do(request)
	if err != nil {
		logs.Info("getReplicate Error sending request:", err)
		return nil, err
	}
	defer resp.Body.Close()
	logs.Info("getReplicate resp code", resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	logs.Info("getReplicate body", string(body))
	if resp.StatusCode == 200 && body == nil {
		logs.Info("getReplicate Body reading response:", err)
		return nil, err
	}
	if err != nil {
		logs.Info("getReplicate Error reading response:", err)
		return nil, err
	}
	var response models.ReplicateResponse
	if err = json.Unmarshal(body, &response); err != nil {
		logs.Info("getReplicate Error Unmarshal response:", err)
		return nil, err
	}

	return &response, nil
}

func setError(task *models.Task, error string) {
	task.Status = 3
	task.Error = error
	_, err := mongo.Update(task)
	if err != nil {
		logs.Info("Update Task Error:", err)
	}
}

func (server *TaskController) AddResult() {
	body := server.Ctx.Input.RequestBody
	task := models.Task{}
	err := json.Unmarshal(body, &task) //解析body中数据
	logs.Debug("appRequest", task)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	task.CreatedTime = time.Now().UTC()
	task.UpdatedTime = task.CreatedTime
	_, err = mongo.Insert(&task)
	if err != nil {
		server.respond(models.BusinessFailed, err.Error())
		return
	}
	server.respond(http.StatusOK, "")
}

func convertToProperType(value interface{}) interface{} {
	switch v := value.(type) {
	case primitive.M:
		// 如果是 primitive.M，直接返回 map[string]interface{}
		return map[string]interface{}(v)

	case primitive.D:
		// 如果是 primitive.D，转换为 map[string]interface{}
		result := make(map[string]interface{})
		for _, elem := range v {
			result[elem.Key] = elem.Value
		}
		return result

	case primitive.A:
		// 如果是 primitive.A，判断其内部元素类型
		if len(v) > 0 {
			switch v[0].(type) {
			case primitive.M:
				// 如果是 []primitive.M，转换为 []map[string]interface{}
				var result []map[string]interface{}
				for _, elem := range v {
					result = append(result, elem.(primitive.M))
				}
				return result

			case primitive.D:
				// 如果是 []primitive.D，转换为 []map[string]interface{}
				var result []map[string]interface{}
				for _, elem := range v {
					converted := make(map[string]interface{})
					for _, innerElem := range elem.(primitive.D) {
						converted[innerElem.Key] = innerElem.Value
					}
					result = append(result, converted)
				}
				return result

			case string:
				// 如果是 []string，直接返回 []string
				var result []string
				for _, elem := range v {
					result = append(result, elem.(string))
				}
				return result
			}
		}

	case string:
		// 如果是字符串，返回字符串
		return v

	default:
		// 如果类型不匹配，返回 nil 或者一个错误提示
		fmt.Println("Unsupported type")
		return nil
	}

	return nil
}

func (server *TaskController) Result() {
	taskId := server.GetString("excute_id")
	if taskId == "" {
		server.respond(models.NoRequestBody, "excute_id is null")
		return
	}
	task := models.Task{
		ExcuteId: taskId,
	}
	filter := map[string]string{
		"excute_id": taskId,
	}
	err := mongo.Read(&task, filter)
	if err != nil {
		logs.Info("List Error:", err)
		server.respond(models.BusinessFailed, err.Error())
	}
	if task.Input != nil {
		raw, err := bson.Marshal(task.Input)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		// 将 bson.Raw 解码为 User 结构体
		var input map[string]interface{}
		err = bson.Unmarshal(raw, &input)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		task.Input = input
	}
	if task.Output != nil {
		output := convertToProperType(task.Output)
		task.Output = output
		//if _, ok := task.Output.(primitive.D); ok {
		//	raw, err := bson.Marshal(task.Output)
		//	if err != nil {
		//		server.respond(models.BusinessFailed, err.Error())
		//	}
		//	// 将 bson.Raw 解码为 User 结构体
		//	var output map[string]interface{}
		//	err = bson.Unmarshal(raw, &output)
		//	if err != nil {
		//		server.respond(models.BusinessFailed, err.Error())
		//	}
		//	task.Output = output
		//}
	}

	if task.Error != nil {
		raw, err := bson.Marshal(task.Error)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		// 将 bson.Raw 解码为 User 结构体
		var error1 models.TaskReturn
		err = bson.Unmarshal(raw, &error1)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		task.Error = error1
	}
	server.respond(http.StatusOK, "", task)
}

func (server *TaskController) List() {
	body := server.Ctx.Input.RequestBody
	request := models.ListRequest{}
	err := json.Unmarshal(body, &request) //解析body中数据
	logs.Debug("Request", string(body), request)
	if err != nil {
		server.respond(models.NoRequestBody, err.Error())
		return
	}

	if request.Page == 0 {
		request.Page = 1
	}
	if request.Size == 0 {
		request.Size = 10
	}

	total, data, err := mongo.Query("Task", request.Page, request.Size, request.Filter)
	if err != nil {
		logs.Info("List Error:", err)
		server.respond(models.BusinessFailed, err.Error())
	}
	var tasks []models.Task
	for _, bsonD := range data {
		var task models.Task
		// 将 bson.D 转换为 bson.Raw
		bsonRaw, err := bson.Marshal(bsonD)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		// 将 bson.Raw 解码为 User 结构体
		err = bson.Unmarshal(bsonRaw, &task)
		if err != nil {
			server.respond(models.BusinessFailed, err.Error())
		}
		if task.Input != nil {
			raw, err := bson.Marshal(task.Input)
			if err != nil {
				server.respond(models.BusinessFailed, err.Error())
			}
			// 将 bson.Raw 解码为 User 结构体
			var input map[string]interface{}
			err = bson.Unmarshal(raw, &input)
			if err != nil {
				server.respond(models.BusinessFailed, err.Error())
			}
			task.Input = input
		}

		if task.Output != nil {
			output := convertToProperType(task.Output)
			task.Output = output
			//if _, ok := task.Output.(primitive.D); ok {
			//	raw, err := bson.Marshal(task.Output)
			//	if err != nil {
			//		server.respond(models.BusinessFailed, err.Error())
			//	}
			//	// 将 bson.Raw 解码为 User 结构体
			//	var output map[string]interface{}
			//	err = bson.Unmarshal(raw, &output)
			//	if err != nil {
			//		server.respond(models.BusinessFailed, err.Error())
			//	}
			//	task.Output = output
			//}
		}

		if task.Error != nil {
			if str, ok := task.Error.(string); ok {
				fmt.Println("The string is:", str)
				taskError := models.TaskReturn{
					IsSuccess: false,
					TaskError: str,
					ExecCode:  0,
					ExecError: "",
				}
				task.Error = taskError
				continue
			}
			raw, err := bson.Marshal(task.Error)
			if err != nil {
				server.respond(models.BusinessFailed, err.Error())
			}
			// 将 bson.Raw 解码为 User 结构体
			var error1 models.TaskReturn
			err = bson.Unmarshal(raw, &error1)
			if err != nil {
				server.respond(models.BusinessFailed, err.Error())
			}
			task.Error = error1
		}

		tasks = append(tasks, task)
	}
	responseData := struct {
		Total int64       `json:"total"`
		Data  interface{} `json:"data,omitempty"`
	}{
		Total: total,
		Data:  tasks,
	}
	server.respond(http.StatusOK, "", responseData)
}
