package utils

import (
	"crypto/md5"
	"crypto/sha1"
	"database/sql"
	"encoding/hex"
	"fmt"
	"io"
	"mime/multipart"
	"os"
	"regexp"
	"time"
)

const (
	Person  = iota + 1 // 个人版
	std                //标准版
	ent                //企业版
	cluster            // 分布式
	lite    = 6        //敏捷版本
)

func SwitchLicenseType(license string) int {
	if regexp.MustCompile("(?i)标准").MatchString(license) {
		return std
	}
	if regexp.MustCompile("(?i)分布式").MatchString(license) {
		return cluster
	}
	if regexp.MustCompile("(?i)企业").MatchString(license) {
		return ent
	}
	if regexp.MustCompile("(?i)敏捷").MatchString(license) {
		return lite
	}
	if regexp.MustCompile("(?i)个人").MatchString(license) {
		return Person
	}
	return 0
}

const maxFileNameLength = 255

// GenerateFileName 生成新的文件名并确保不超过最大长度限制
func GenerateFileName(name, timestamp, ext string) string {
	newFileName := name + "_" + timestamp + ext

	if len(newFileName) > maxFileNameLength {
		trimLength := len(newFileName) - maxFileNameLength
		if len(name) > trimLength {
			name = name[:len(name)-trimLength]
		} else {
			name = ""
		}
		newFileName = name + "_" + timestamp + ext
	}

	return newFileName
}

// CalculateFileMd5 计算文件的 MD5 值
func CalculateFileMd5(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}

	return hex.EncodeToString(hash.Sum(nil)), nil
}

// calculateFileHeaderMd5 计算 *multipart.FileHeader 的 MD5 值
func CalculateFileHeaderMd5(fileHeader *multipart.FileHeader) (string, error) {
	file, err := fileHeader.Open()
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}

	return hex.EncodeToString(hash.Sum(nil)), nil
}

func GenerateShortIdentifier(username, email, telephone string) string {
	// 获取当前时间的时间戳
	timestamp := time.Now().UnixNano()

	// 将时间戳加入输入字符串
	input := fmt.Sprintf("%s%s%s%d", timestamp, email, telephone, username)

	// 生成哈希值
	hasher := sha1.New()
	hasher.Write([]byte(input))

	// 返回哈希的前12位作为唯一标识符
	return hex.EncodeToString(hasher.Sum(nil))[:12]
}

func ToString(ns sql.NullString) string {
	if ns.Valid {
		return ns.String
	}
	return ""
}

func ToInt64(ni sql.NullInt64) int64 {
	if ni.Valid {
		return ni.Int64
	}
	return 0
}

func ToTimeString(nt sql.NullTime) string {
	if nt.Valid {
		return nt.Time.Format(time.RFC3339)
	}
	return ""
}

// StringToNullString 将字符串转换为 sql.NullString
func StringToNullString(s string) sql.NullString {
	if s == "" {
		return sql.NullString{
			String: "",
			Valid:  false,
		}
	}
	return sql.NullString{
		String: s,
		Valid:  true,
	}
}

// IntToNullInt64 将 int64 转换为 sql.NullInt64
func IntToNullInt64(i int64) sql.NullInt64 {
	return sql.NullInt64{
		Int64: i,
		Valid: true,
	}
}