package utils

import (
	"context"
	"encoding/base64"
	"file_upload/simple_zap"
	"os"
	"strings"
)

func ParseBase64ImageString(input, name string) error {
	parts := strings.Split(input, ",")
	if len(parts) < 2 {
		panic("Invalid Base64 image string")
	}
	contentTypePart := strings.TrimSpace(parts[0])
	contentTypeParts := strings.Split(contentTypePart, ";")
	_ = strings.TrimSpace(contentTypeParts[0])

	data := parts[1]
	decodeString, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return err
	}
	optputpath := "./upload" + "/" + name + ".png"
	create, err := os.Create(optputpath)
	if err != nil {
		simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "创建文件失败")
		return err
	}
	defer create.Close()
	_, err = create.Write(decodeString)
	if err != nil {
		simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "写入文件失败")
		return err
	}
	return err
}
