package svc

import (
	"jnc-server/app/main/api/internal/config"
	"jnc-server/app/main/api/internal/middleware"
	"jnc-server/app/main/api/internal/service"
	tianyuanapi "jnc-server/app/main/api/internal/service/tianyuanapi_sdk"
	"jnc-server/app/main/model"
	"time"

	"github.com/hibiken/asynq"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/rest"
)

// ServiceContext 服务上下文
type ServiceContext struct {
	Config config.Config
	Redis  *redis.Redis

	// 中间件
	AuthInterceptor      rest.Middleware
	UserAuthInterceptor  rest.Middleware
	AdminAuthInterceptor rest.Middleware

	// 用户相关模型
	UserModel     model.UserModel
	UserAuthModel model.UserAuthModel

	// 产品相关模型
	ProductModel        model.ProductModel
	FeatureModel        model.FeatureModel
	ProductFeatureModel model.ProductFeatureModel

	// 订单相关模型
	OrderModel              model.OrderModel
	OrderRefundModel        model.OrderRefundModel
	QueryModel              model.QueryModel
	QueryCleanupLogModel    model.QueryCleanupLogModel
	QueryCleanupDetailModel model.QueryCleanupDetailModel
	QueryCleanupConfigModel model.QueryCleanupConfigModel

	// 代理相关模型（新系统）
	AgentModel              model.AgentModel
	AgentWalletModel        model.AgentWalletModel
	AgentLinkModel          model.AgentLinkModel
	AgentOrderModel         model.AgentOrderModel
	AgentCommissionModel    model.AgentCommissionModel
	AgentConfigModel        model.AgentConfigModel
	AgentProductConfigModel model.AgentProductConfigModel
	AgentFreezeTaskModel    model.AgentFreezeTaskModel
	AgentShortLinkModel     model.AgentShortLinkModel
	AgentWithdrawModel      model.AgentWithdrawModel

	// 管理后台相关模型
	AdminApiModel      model.AdminApiModel
	AdminMenuModel     model.AdminMenuModel
	AdminRoleModel     model.AdminRoleModel
	AdminRoleApiModel  model.AdminRoleApiModel
	AdminRoleMenuModel model.AdminRoleMenuModel
	AdminUserModel     model.AdminUserModel
	AdminUserRoleModel model.AdminUserRoleModel
	AdminDictDataModel model.AdminDictDataModel
	AdminDictTypeModel model.AdminDictTypeModel

	// 其他模型
	ExampleModel               model.ExampleModel
	GlobalNotificationsModel   model.GlobalNotificationsModel
	AuthorizationDocumentModel model.AuthorizationDocumentModel

	// 服务
	AlipayService        *service.AliPayService
	WechatPayService     *service.WechatPayService
	ApplePayService      *service.ApplePayService
	EasyPayService       *service.EasyPayService
	ApiRequestService    *service.ApiRequestService
	AsynqServer          *asynq.Server
	AsynqService         *service.AsynqService
	VerificationService  *service.VerificationService
	AgentService         *service.AgentService
	UserService          *service.UserService
	DictService          *service.DictService
	ImageService         *service.ImageService
	AuthorizationService *service.AuthorizationService
}

// NewServiceContext 创建服务上下文
func NewServiceContext(c config.Config) *ServiceContext {
	// ============================== 基础设施初始化 ==============================
	db := sqlx.NewMysql(c.DataSource)
	cacheConf := c.CacheRedis

	// 初始化Redis客户端
	redisConf := redis.RedisConf{
		Host: cacheConf[0].Host,
		Pass: cacheConf[0].Pass,
		Type: cacheConf[0].Type,
	}
	redisClient := redis.MustNewRedis(redisConf)

	// ============================== 用户相关模型 ==============================
	userModel := model.NewUserModel(db, cacheConf)
	userAuthModel := model.NewUserAuthModel(db, cacheConf)

	// ============================== 产品相关模型 ==============================
	productModel := model.NewProductModel(db, cacheConf)
	featureModel := model.NewFeatureModel(db, cacheConf)
	productFeatureModel := model.NewProductFeatureModel(db, cacheConf)

	// ============================== 订单相关模型 ==============================
	orderModel := model.NewOrderModel(db, cacheConf)
	queryModel := model.NewQueryModel(db, cacheConf)
	orderRefundModel := model.NewOrderRefundModel(db, cacheConf)
	queryCleanupLogModel := model.NewQueryCleanupLogModel(db, cacheConf)
	queryCleanupDetailModel := model.NewQueryCleanupDetailModel(db, cacheConf)
	queryCleanupConfigModel := model.NewQueryCleanupConfigModel(db, cacheConf)

	// ============================== 代理相关模型（新系统） ==============================
	agentModel := model.NewAgentModel(db, cacheConf)
	agentWalletModel := model.NewAgentWalletModel(db, cacheConf)
	agentLinkModel := model.NewAgentLinkModel(db, cacheConf)
	agentOrderModel := model.NewAgentOrderModel(db, cacheConf)
	agentCommissionModel := model.NewAgentCommissionModel(db, cacheConf)
	agentConfigModel := model.NewAgentConfigModel(db, cacheConf)
	agentProductConfigModel := model.NewAgentProductConfigModel(db, cacheConf)
	agentFreezeTaskModel := model.NewAgentFreezeTaskModel(db, cacheConf)
	agentShortLinkModel := model.NewAgentShortLinkModel(db, cacheConf)
	agentWithdrawModel := model.NewAgentWithdrawModel(db, cacheConf)
	// ============================== 管理后台相关模型 ==============================
	adminApiModel := model.NewAdminApiModel(db, cacheConf)
	adminMenuModel := model.NewAdminMenuModel(db, cacheConf)
	adminRoleModel := model.NewAdminRoleModel(db, cacheConf)
	adminRoleApiModel := model.NewAdminRoleApiModel(db, cacheConf)
	adminRoleMenuModel := model.NewAdminRoleMenuModel(db, cacheConf)
	adminUserModel := model.NewAdminUserModel(db, cacheConf)
	adminUserRoleModel := model.NewAdminUserRoleModel(db, cacheConf)
	adminDictDataModel := model.NewAdminDictDataModel(db, cacheConf)
	adminDictTypeModel := model.NewAdminDictTypeModel(db, cacheConf)

	// ============================== 其他模型 ==============================
	exampleModel := model.NewExampleModel(db, cacheConf)
	globalNotificationsModel := model.NewGlobalNotificationsModel(db, cacheConf)
	authorizationDocumentModel := model.NewAuthorizationDocumentModel(db, cacheConf)

	// ============================== 第三方服务初始化 ==============================
	tianyuanapi, err := tianyuanapi.NewClient(tianyuanapi.Config{
		AccessID: c.Tianyuanapi.AccessID,
		Key:      c.Tianyuanapi.Key,
		BaseURL:  c.Tianyuanapi.BaseURL,
		Timeout:  time.Duration(c.Tianyuanapi.Timeout) * time.Second,
	})
	if err != nil {
		logx.Errorf("初始化天远API失败: %+v", err)
	}

	// ============================== 业务服务初始化 ==============================
	// 根据配置决定是否初始化支付宝服务
	var alipayService *service.AliPayService
	if c.Alipay.Enabled {
		alipayService = service.NewAliPayService(c)
		logx.Info("支付宝服务已启用")
	} else {
		logx.Info("支付宝服务已禁用")
	}

	// 根据配置决定是否初始化微信支付服务
	var wechatPayService *service.WechatPayService
	if c.Wxpay.Enabled {
		wechatPayService = service.NewWechatPayService(c, userAuthModel, service.InitTypeWxPayPubKey)
		logx.Info("微信支付服务已启用")
	} else {
		logx.Info("微信支付服务已禁用")
	}

	// 根据配置决定是否初始化Apple支付服务
	var applePayService *service.ApplePayService
	if c.Applepay.Enabled {
		applePayService = service.NewApplePayService(c)
		logx.Info("Apple支付服务已启用")
	} else {
		logx.Info("Apple支付服务已禁用")
	}

	// 根据配置决定是否初始化易支付服务
	var easyPayService *service.EasyPayService
	if c.EasyPay.Enabled {
		easyPayService = service.NewEasyPayService(c)
		logx.Info("易支付服务已启用")
	} else {
		logx.Info("易支付服务已禁用")
	}
	apiRequestService := service.NewApiRequestService(c, featureModel, productFeatureModel, tianyuanapi)
	verificationService := service.NewVerificationService(c, tianyuanapi, apiRequestService)
	asynqService := service.NewAsynqService(c)
	agentService := service.NewAgentService(c, orderModel, agentModel, agentWalletModel,
		agentLinkModel, agentOrderModel, agentCommissionModel, agentConfigModel, agentProductConfigModel)
	userService := service.NewUserService(&c, userModel, userAuthModel, agentModel)
	dictService := service.NewDictService(adminDictTypeModel, adminDictDataModel)
	imageService := service.NewImageService()
	authorizationService := service.NewAuthorizationService(c, authorizationDocumentModel)

	// ============================== 异步任务服务 ==============================
	asynqServer := asynq.NewServer(
		asynq.RedisClientOpt{Addr: c.CacheRedis[0].Host, Password: c.CacheRedis[0].Pass},
		asynq.Config{
			IsFailure: func(err error) bool {
				logx.Errorf("异步任务失败: %+v \n", err)
				return true
			},
			Concurrency: 10,
		},
	)

	// ============================== 返回服务上下文 ==============================
	return &ServiceContext{
		Config:              c,
		Redis:               redisClient,
		AuthInterceptor:     middleware.NewAuthInterceptorMiddleware(c).Handle,
		UserAuthInterceptor: middleware.NewUserAuthInterceptorMiddleware().Handle,
		AdminAuthInterceptor: middleware.NewAdminAuthInterceptorMiddleware(c,
			adminUserModel, adminUserRoleModel, adminRoleModel, adminApiModel, adminRoleApiModel).Handle,

		// 用户相关模型
		UserModel:     userModel,
		UserAuthModel: userAuthModel,

		// 产品相关模型
		ProductModel:        productModel,
		FeatureModel:        featureModel,
		ProductFeatureModel: productFeatureModel,

		// 订单相关模型
		OrderModel:              orderModel,
		QueryModel:              queryModel,
		OrderRefundModel:        orderRefundModel,
		QueryCleanupLogModel:    queryCleanupLogModel,
		QueryCleanupDetailModel: queryCleanupDetailModel,
		QueryCleanupConfigModel: queryCleanupConfigModel,

		// 代理相关模型（简化版 - 移除团队关系、返佣、升级、提现、实名认证、邀请码）
		AgentModel:              agentModel,
		AgentWalletModel:        agentWalletModel,
		AgentLinkModel:          agentLinkModel,
		AgentOrderModel:         agentOrderModel,
		AgentCommissionModel:    agentCommissionModel,
		AgentConfigModel:        agentConfigModel,
		AgentProductConfigModel: agentProductConfigModel,
		AgentFreezeTaskModel:    agentFreezeTaskModel,
		AgentShortLinkModel:     agentShortLinkModel,
		AgentWithdrawModel:      agentWithdrawModel,

		// 管理后台相关模型
		AdminApiModel:      adminApiModel,
		AdminMenuModel:     adminMenuModel,
		AdminRoleModel:     adminRoleModel,
		AdminRoleApiModel:  adminRoleApiModel,
		AdminRoleMenuModel: adminRoleMenuModel,
		AdminUserModel:     adminUserModel,
		AdminUserRoleModel: adminUserRoleModel,
		AdminDictDataModel: adminDictDataModel,
		AdminDictTypeModel: adminDictTypeModel,

		// 其他模型
		ExampleModel:               exampleModel,
		GlobalNotificationsModel:   globalNotificationsModel,
		AuthorizationDocumentModel: authorizationDocumentModel,

		// 服务
		AlipayService:        alipayService,
		WechatPayService:     wechatPayService,
		ApplePayService:      applePayService,
		EasyPayService:       easyPayService,
		ApiRequestService:    apiRequestService,
		AsynqServer:          asynqServer,
		AsynqService:         asynqService,
		VerificationService:  verificationService,
		AgentService:         agentService,
		UserService:          userService,
		DictService:          dictService,
		ImageService:         imageService,
		AuthorizationService: authorizationService,
	}
}

func (s *ServiceContext) Close() {
	if s.AsynqService != nil {
		s.AsynqService.Close()
	}
}
