package services

import (
	"context"
	"fmt"
	"image/color"
	"sync"
	"time"

	"github.com/jmoiron/sqlx"

	"github.com/go-redis/redis/v8"
	"github.com/gorilla/sessions"
	"github.com/mojocn/base64Captcha"
)

var (
	// 配置信息
	AppConfig = struct {
		SessionSecret string
		SessionName   string
		CaptchaType   string
	}{
		SessionSecret: "your-very-secret-key-change-in-production",
		SessionName:   "auth_session",
		CaptchaType:   "digit", // math, digit, audio, string
	}

	// 全局服务实例
	sessionStore  *sessions.CookieStore
	captchaDriver base64Captcha.Driver
	initOnce      sync.Once

	RedisClient *redis.Client
	MYSQL_DB    *sqlx.DB
	JdbcClient  *DBClient
	MinioClient *MinioService
)

// 验证码配置
const (
	CaptchaExpireMin   = 5           // 验证码过期时间（分钟）
	CaptchaRedisPrefix = "code-key-" // 验证码结果存储键前缀
)

const (
	BucketName = "process"
)

// InitConfig 初始化配置
func InitConfig() {
	// 这里可以读取配置文件或环境变量
	// 例如：AppConfig.SessionSecret = os.Getenv("SESSION_SECRET")
}

// SessionStore 获取会话存储
func SessionStore() *sessions.CookieStore {
	initOnce.Do(func() {
		sessionStore = sessions.NewCookieStore([]byte(AppConfig.SessionSecret))
		sessionStore.Options = &sessions.Options{
			Path:     "/",
			MaxAge:   86400 * 7, // 7天
			HttpOnly: true,
			Secure:   false, // 开发环境设为false，生产环境设为true
		}
	})
	return sessionStore
}

// InitServices 初始化服务
func InitCaptcha() {
	// 初始化验证码驱动
	switch AppConfig.CaptchaType {
	case "digit":
		captchaDriver = base64Captcha.NewDriverDigit(80, 240, 4, 0.2, 10)
	case "math":
		captchaDriver = base64Captcha.NewDriverMath(
			70,  // 高度 - 适当高度，保证清晰度
			240, // 宽度 - 足够宽度显示数学公式
			0,   // 干扰线数量 - 设置为0提高可读性
			0,   // 干扰点数量 - 设置为0提高可读性
			&color.RGBA{R: 255, G: 255, B: 255, A: 255}, // 白色背景
			nil,                       // 字体列表 - 使用默认
			[]string{"RitaSmith.ttf"}, // 使用清晰字体
		)
	case "audio":
		captchaDriver = base64Captcha.NewDriverAudio(4, "en")
	default:
		captchaDriver = base64Captcha.NewDriverString(80, 240, 4, 0, 4, "1234567890", nil, nil, nil)
	}
}

func InitMyRedis(addr string, password string, dbn int) {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     addr,     // Redis地址
		Password: password, // Redis密码（无则留空）
		DB:       dbn,      // 使用的数据库
	})
	ctx := context.Background()
	err := RedisClient.Set(ctx, "mes", "mes-redis", 10*time.Second).Err()
	if err == nil {
		build_time := time.Now()
		build_time_str := build_time.Format(time.DateTime)
		fmt.Printf("%s redis客户端启动成功\n", build_time_str)
	} else {
		fmt.Printf("redis.err=====%v\n", err)
	}
}

func InitMysqlPool(user string, password string, host string, port int, dbname string, log bool) {
	db_config := DefaultConfig(user, password, host, port, dbname)
	MYSQL_DB = NewPool(db_config)
	JdbcClient = NewDBClient(MYSQL_DB, log)

	// // 准备预编译语句
	// stmt, err := MYSQL_DB.Preparex("SELECT VERSION()")
	// if err != nil {
	//     print(err)
	// }
	// defer stmt.Close()

	// var version string
	// err = stmt.QueryRowx().Scan(&version)
	// if err != nil {
	//     print(err)
	// }

	// print("Database Version: ", version,"\n")
}

func InitMinioServie(addr string, user string, password string, usessl bool) {
	MinioClient = NewMinioService(
		addr,
		user,
		password,
		usessl,
	)
	build_time := time.Now()
	build_time_str := build_time.Format(time.DateTime)
	ctx := context.Background()
	_, err := MinioClient.client.BucketExists(ctx, "process")
	if err == nil {
		fmt.Printf("%s minio客户端初始化成功\n", build_time_str)
	} else {
		fmt.Printf("minio客户端.err=====%v\n", err)
	}
}

// GetCaptchaDriver 获取验证码驱动
func GetCaptchaDriver() base64Captcha.Driver {
	return captchaDriver
}

// GetRedisClient 获取Redis客户端
func GetRedisClient() *redis.Client {
	return RedisClient
}

// func GetMysqlPool() *sqlx.DB {
// 	return MYSQL_DB
// }

func GetMinioClient() *MinioService {
	return MinioClient
}
