package osscli

import (
	"bytes"
	"doc-service/common/log"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"time"
)

type IOssBucket interface {
	UploadFile(fpath string) (string, error)
}

type ossBucket struct {
	host string
}

func NewOssBucket(host string) IOssBucket {
	return &ossBucket{
		host: host,
	}
}

func (b *ossBucket) UploadFile(filePath string) (string, error) {
	// 检查文件是否存在
	_, err := os.Stat(filePath)
	if err != nil {
		return "", err
	}
	os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
	// 打开本地文件
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// 创建HTTP POST请求
	var reqBody bytes.Buffer
	writer := multipart.NewWriter(&reqBody)
	destFile, err := writer.CreateFormFile("file", file.Name())
	if err != nil {
		return "", err
	}
	if _, err = io.Copy(destFile, file); err != nil {
		return "", err
	}
	_ = writer.Close()

	request, err := http.NewRequest("POST", b.host+"/oss/upload/storage", &reqBody)
	if err != nil {
		return "", err
	}

	// 设置必要的请求头，特别是 Content-Type
	request.Header.Set("Content-Type", writer.FormDataContentType())

	// 设置 businessCode 请求头
	request.Header.Set("businessCode", "4001001")

	// 设置超时时间
	client := &http.Client{
		Timeout: 30 * time.Second,
	}

	// 发送HTTP POST请求
	resp, err := client.Do(request)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Info("oss上传响应异常：%d", resp.StatusCode)
		return "", fmt.Errorf("oss上传响应异常：%d", resp.StatusCode)
	}

	var response map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
		return "", err
	}
	if int(response["code"].(float64)) != 200 {
		return "", fmt.Errorf("oss上传失败: code=%d, msg=%s", response["code"].(float64), response["msg"].(string))
	}

	return response["data"].(string), nil
}
