package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"strconv"
)

type SoulNeuralRequest struct {
	Auth    string `json:"auth"`
	Type    int    `json:"type"`
	ISLIUid string `json:"ISLIUid"`
	//CFN     string `json:"CFN,omitempty"` // omitempty 表示如果 CFN 为空，则在 JSON 中省略这个字段
	CFN string `json:"CFN"`
}

type SoulNeuralResponse struct {
	Code int `json:"code"` // 仅当网络状态码为201时有效
}

// SoulNeuralFileTransfer 神经网络记忆文件上载
func SoulNeuralFileUpload(Neuralurl string, request SoulNeuralRequest, fileName string) ([]byte, error) {
	fmt.Println("NeuralFileUpload request_url", Neuralurl)
	// 创建一个HTTP客户端
	client := &http.Client{}

	// 创建一个buffer，用于存储请求的multipart/form-data数据
	var bodyBuf bytes.Buffer
	writer := multipart.NewWriter(&bodyBuf)

	// 添加参数字段
	writer.WriteField("auth", request.Auth)
	writer.WriteField("type", strconv.Itoa(request.Type))
	writer.WriteField("ISLIUid", request.ISLIUid)

	// 如果是上载（还魂）操作，需要添加静态意识网络文件
	// 这里假设你已经有一个名为 "static_network.cfn" 的文件

	staticNetworkFile, err := os.Open(fileName)
	if err != nil {
		fmt.Println("Failed to open file:", err)
		return nil, err
	}
	defer staticNetworkFile.Close()

	fileWriter, err := writer.CreateFormFile("CFN", fileName)
	if err != nil {
		fmt.Println("Failed to create form file:", err)
		return nil, err
	}

	_, err = io.Copy(fileWriter, staticNetworkFile)
	if err != nil {
		fmt.Println("Failed to copy file data:", err)
		return nil, err
	}

	// 关闭multipart writer
	writer.Close()

	// 创建POST请求
	req, err := http.NewRequest("POST", Neuralurl, &bodyBuf)
	if err != nil {
		fmt.Println("Failed to create request:", err)
		return nil, err
	}

	// 设置请求头
	req.Header.Set("Content-Type", writer.FormDataContentType())

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	// 解析JSON
	var response SoulNeuralResponse

	// 根据不同的响应状态码处理数据
	if resp.StatusCode == 201 {
		err = json.Unmarshal(body, &response)
		log.Println("response.Code: ", response.Code)
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("error from server: %v", response.Code)
	} else if resp.StatusCode == 200 {
		// 正常响应，返回body
		fmt.Printf("响应状态码%d, 神经网络记忆文件上传【 %d字节 】 \n", resp.StatusCode, len(body))

		//log.Println("意识文件上传成功!", resp.StatusCode)
		return body, nil
	}

	return nil, fmt.Errorf("unexpected server response: %v", resp.Status)

}

// SoulNeuralFileUpload 神经网络记忆文件下载
func SoulNeuralFileDownload(Neuralurl string, request SoulNeuralRequest, fileName string) error {

	fmt.Println("NeuralFileDownload request_url", Neuralurl)
	// 创建一个HTTP客户端
	client := &http.Client{}

	// 创建一个buffer，用于存储请求的multipart/form-data数据
	bodyBuf := &bytes.Buffer{}
	writer := multipart.NewWriter(bodyBuf)

	// 添加参数字段
	writer.WriteField("auth", request.Auth)
	writer.WriteField("type", fmt.Sprintf("%d", request.Type))
	writer.WriteField("ISLIUid", request.ISLIUid)

	// 关闭multipart writer
	err := writer.Close()
	if err != nil {
		fmt.Println("Failed to close writer:", err)
		return err
	}

	// 创建POST请求
	req, err := http.NewRequest("POST", Neuralurl, bodyBuf)
	if err != nil {
		fmt.Println("Failed to create request:", err)
		return err
	}

	// 设置请求头
	req.Header.Set("Content-Type", writer.FormDataContentType())

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	// 解析JSON
	var response SoulNeuralResponse

	// 检查网络状态码
	if resp.StatusCode == 200 {
		// 创建文件
		file, err := os.Create(fileName)
		if err != nil {
			fmt.Println("Failed to create file:", err)
			return err
		}
		defer file.Close()

		// 将响应体中的数据写入文件
		_, err = file.Write(body)
		if err != nil {
			fmt.Println("Failed to write file:", err)
			return err
		}
		fmt.Println("文件下载完成")
		fmt.Printf("响应状态码%d, 神经网络记忆文件下载【%d字节】\n", resp.StatusCode, len(body))

	} else {
		err = json.Unmarshal(body, &response)
		fmt.Printf("请求失败，状态码:", resp.StatusCode, " response.Code: ", response.Code, "0传载失效 2凭证无效 3信息格式有误 4非法的服务商")

		//log.Println("response.Code: ", response.Code)

		return fmt.Errorf("error from server: %v", response.Code)
	}

	return nil
}

// SoulNeuralFileReset 记忆文件重置
func SoulNeuralFileReset(Neuralurl string, request SoulNeuralRequest) (error, int) {

	fmt.Println("SoulNeuralFileReset request_url", Neuralurl)
	// 创建一个HTTP客户端
	client := &http.Client{}

	// 创建一个buffer，用于存储请求的multipart/form-data数据
	bodyBuf := &bytes.Buffer{}
	writer := multipart.NewWriter(bodyBuf)

	// 添加参数字段
	writer.WriteField("auth", request.Auth)
	writer.WriteField("type", fmt.Sprintf("%d", request.Type))
	writer.WriteField("ISLIUid", request.ISLIUid)

	// 关闭multipart writer
	err := writer.Close()
	if err != nil {
		fmt.Println("Failed to close writer:", err)
		return err, -1
	}

	// 创建POST请求
	req, err := http.NewRequest("POST", Neuralurl, bodyBuf)
	if err != nil {
		fmt.Println("Failed to create request:", err)
		return err, -1
	}

	// 设置请求头
	req.Header.Set("Content-Type", writer.FormDataContentType())

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return err, -1
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err, -1
	}

	// 解析JSON
	var response SoulNeuralResponse

	// 检查网络状态码
	if resp.StatusCode == 200 {

		err = json.Unmarshal(body, &response)
		if err != nil {
			log.Println("响应解析失败!", err)
			return err, -1
		}
		fmt.Println("请求成功，状态码:", resp.StatusCode, " response.Code: ", response.Code)
		return nil, 1

	} else {
		err = json.Unmarshal(body, &response)
		fmt.Println("请求失败，状态码:", resp.StatusCode, " response.Code: ", response.Code)

		//log.Println("response.Code: ", response.Code)
		return fmt.Errorf("error from server: %v", response.Code), -1

	}

	return nil, 1
}
