package system

import (
	"crypto/md5"
	"errors"
	"fmt"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"mime/multipart"
	"strings"
	"sundynix-go/global"
	common "sundynix-go/model/commom/request"
	"sundynix-go/model/system"
	sysReq "sundynix-go/model/system/request"
	"sundynix-go/utils/upload"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

type OssService struct {
}

var OssServiceApp = new(OssService)

func (o *OssService) Save(file system.Oss) error {
	return global.DB.Create(&file).Error
}

func (o *OssService) Upload(multipartFile multipart.File, header *multipart.FileHeader) (file system.Oss, err error) {
	//1.检查是否已有此文件
	temp, err := header.Open()
	if err != nil {
		return file, err
	}
	defer temp.Close()

	hasher := md5.New()
	if _, copyErr := io.Copy(hasher, temp); copyErr != nil {
		return file, copyErr
	}
	// 步骤3: 计算哈希值并转换为十六进制字符串
	hashBytes := hasher.Sum(nil)
	hashString := fmt.Sprintf("%x", hashBytes)
	var exist system.Oss
	findErr := global.DB.Where("md5 = ?", hashString).First(&exist).Error
	if findErr == nil && exist.Id != "" {
		return exist, nil
	}
	if errors.Is(findErr, gorm.ErrRecordNotFound) {
		//不存在的时候保存
		instance := upload.OssInstance()
		filepath, key, uploadErr := instance.UploadFile(header)
		if uploadErr != nil {
			return file, uploadErr
		}
		//文件后缀
		s := strings.Split(header.Filename, ".")
		//仅当可能是图片时 才计算图片宽高
		f := system.Oss{
			Key:    key, // uploads/2025-09-17/
			Name:   header.Filename,
			Suffix: s[len(s)-1],
			Tag:    s[len(s)-1],
			Url:    filepath, // http://127.0.0.1:9000/planting-fun/uploads/2025-09-17/211476f3837fc7acbaebf0f901c1bd68.png
			MD5:    hashString,
		}
		return f, global.DB.Create(&f).Error
	}
	return file, err
}

func (o *OssService) DeleteFileByIds(ids common.IdsReq) error {
	//循环删除
	instance := upload.OssInstance()
	for _, id := range ids.Ids {
		file, err := o.GetById(id)
		if err != nil {
			return err
		}
		if err = instance.DeleteFile(file.Key); err != nil {
			global.Logger.Error("删除文件失败!", zap.Error(err))
			return err
		}
	}
	err := global.DB.Where("id IN (?)", ids.Ids).Delete(&system.Oss{}).Error
	return err
}

func (o *OssService) GetById(id string) (system.Oss, error) {
	var file system.Oss
	err := global.DB.Where("id = ?", id).First(&file).Error
	//不存在的时候不要返回错误，而是返回nil
	if err != nil {
		return file, nil
	}
	return file, err
}

func (o *OssService) GetFileList(info sysReq.GetOssFileList) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Current - 1)
	db := global.DB.Model(&system.Oss{})
	var files []system.Oss
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&files).Error
	return files, total, err
}
