package gen

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
	"tryon/model"
)

const (
	API_URL           = "https://dashscope.aliyuncs.com/api/v1/services/aigc/virtualmodel/generation/"
	DASHSCOPE_API_KEY = "sk-36a7725c51be4ffe8d3374ea534014b6"
)

type OutPutRes struct {
	OutPut    OutPut `json:"output"`
	RequestId string `json:"request_id"`
}
type OutPut struct {
	TaskStatus string `json:"task_status"`
	TaskId     string `json:"task_id"`
}

func Generate(model string, shoes []string, scale float64) (string, error) {
	fmt.Println(scale)
	// 设置请求体
	data := map[string]interface{}{
		"model": "shoemodel-v1",
		"input": map[string]interface{}{
			"template_image_url": model,
			"shoe_image_url":     shoes,
			"scale":              scale,
		},
		"parameters": map[string]interface{}{
			"n": 1,
		},
	}
	// 将请求体编码为 JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		return "", nil
	}

	req, err := http.NewRequest("POST", API_URL, bytes.NewBuffer(jsonData))
	if err != nil {
		return "", nil
	}

	// 设置请求头
	req.Header.Set("X-DashScope-Async", "enable")
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", DASHSCOPE_API_KEY))
	req.Header.Set("Content-Type", "application/json")

	// 发起 POST 请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	bodyObj := OutPutRes{}
	err = json.Unmarshal(body, &bodyObj)
	if err != nil {
		return "", err
	}
	fmt.Println(bodyObj)
	return bodyObj.OutPut.TaskId, nil

}

func GetReslut(taskId string, outPut string) (string, error) {
	if len(taskId) == 0 {
		return "", errors.New("taskId is empty")
	}

	// 获取任务 ID
	// taskID := "6488c66d-2a0c-4134-90bb-39ab957d6cdf"
	returl := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/tasks/%s", taskId)

	// 创建 GET 请求
	getReq, err := http.NewRequest("GET", returl, nil)
	if err != nil {
		return "", err
	}

	// 设置 GET 请求头
	getReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", DASHSCOPE_API_KEY))

	// 发起 GET 请求
	client := &http.Client{}
	getResp, err := client.Do(getReq)
	if err != nil {
		return "", err
	}
	defer getResp.Body.Close()

	// 读取响应
	getBody, err := io.ReadAll(getResp.Body)
	if err != nil {
		return "", err
	}
	bodyObj := model.Response{}
	err = json.Unmarshal(getBody, &bodyObj)
	if err != nil {
		return "", err
	}
	fmt.Printf("%#v\n", bodyObj)
	if bodyObj.Output.TaskStatus == "SUCCEEDED" {
		// 下载到本地
		return bodyObj.Output.Results[0].URL, nil
	}
	return bodyObj.Output.TaskStatus, errors.New("后台处理中。。。")

	// {
	//     "request_id": "a052b714-29d5-92c0-b981-43dc027523db",
	//     "output": {
	//         "task_id": "5f6316e3-ef6c-4143-abb5-81ffefdbfcd0",
	//         "task_status": "SUCCEEDED",
	//         "submit_time": "2024-11-04 16:27:38.824",
	//         "scheduled_time": "2024-11-04 16:27:38.852",
	//         "end_time": "2024-11-04 16:27:54.092",
	//         "results": [
	//             {
	//                 "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/7d/08/20241104/18d9de26/2024-11-04/42b28ff3-8e67-44fa-805e-72cab9e204fc-1/res_img.png?Expires=1730795274&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=KlU2NsBfFKDcl9NwklzH1i2X8bk%3D"
	//             }
	//         ],
	//         "task_metrics": {
	//             "TOTAL": 1,
	//             "SUCCEEDED": 1,
	//             "FAILED": 0
	//         }
	//     },
	//     "usage": {
	//         "image_count": 1
	//     }
	// }
}

func Download(url string, outPut string) (string, error) {
	// 创建 GET 请求
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close() // 确保在函数返回时关闭响应体

	key := time.Now().Format("20060102_150405")
	outPutFile := fmt.Sprintf("%s/%s.png", outPut, key)

	out, err := os.Create(outPutFile)
	if err != nil {
		return "", err
	}
	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return "", err
	}

	return outPutFile, nil

}
