package utils

import (
	"errors"
	"fmt"
	"fonchain-fiee/pkg/e"
	"io"
	"net/http"
	"os"
	"strings"

	"go.uber.org/zap"
)

// SaveUrlFileDisk 保存图片到本地
func SaveUrlFileDisk(url string, path string, filename string) (fullPath string, err error) {
	if err = CreateDirPath(path); err != nil {
		zap.L().Error("SaveUrlFileDisk err ", zap.Error(err))
		return
	}
	if filename == "" {
		stepName := strings.Split(url, "/")
		if len(stepName) > 1 {
			filename = stepName[len(stepName)-1]
		}
	}

	resp, err := http.Get(url)
	if err != nil {
		err = errors.New(e.GetMsg(e.ERROR_DOWNLOAD_FILE))
		return
	}
	defer func() {
		if err := recover(); err != nil {

		}
		resp.Body.Close()
	}()
	bytes, err := io.ReadAll(resp.Body)
	fullPath = fmt.Sprintf("%s/%s", path, filename)
	// 写入数据
	err = os.WriteFile(fullPath, bytes, 0666)
	if err != nil {
		return
	}
	// Linux系统下需要显式设置文件权限
	if err = os.Chmod(fullPath, 0666); err != nil {
		// 权限设置失败不影响主流程
		err = nil
	}
	return
}
