package svc

import (
	"bdqr-server/app/main/api/internal/config"
	"bdqr-server/app/main/api/internal/middleware"
	"bdqr-server/app/main/api/internal/service"
	tianyuanapi "bdqr-server/app/main/api/internal/service/tianyuanapi_sdk"
	"bdqr-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
	AgentRelationModel        model.AgentRelationModel
	AgentLinkModel            model.AgentLinkModel
	AgentOrderModel           model.AgentOrderModel
	AgentCommissionModel      model.AgentCommissionModel
	AgentRebateModel          model.AgentRebateModel
	AgentUpgradeModel         model.AgentUpgradeModel
	AgentWithdrawalModel      model.AgentWithdrawalModel
	AgentConfigModel          model.AgentConfigModel
	AgentProductConfigModel   model.AgentProductConfigModel
	AgentRealNameModel        model.AgentRealNameModel
	AgentWithdrawalTaxModel   model.AgentWithdrawalTaxModel
	AgentInviteCodeModel      model.AgentInviteCodeModel
	AgentInviteCodeUsageModel model.AgentInviteCodeUsageModel
	AgentFreezeTaskModel      model.AgentFreezeTaskModel
	AgentShortLinkModel       model.AgentShortLinkModel

	// 管理后台相关模型
	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
	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
	TencentCloudService  *service.TencentCloudService
}

// 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)
	agentRelationModel := model.NewAgentRelationModel(db, cacheConf)
	agentLinkModel := model.NewAgentLinkModel(db, cacheConf)
	agentOrderModel := model.NewAgentOrderModel(db, cacheConf)
	agentCommissionModel := model.NewAgentCommissionModel(db, cacheConf)
	agentRebateModel := model.NewAgentRebateModel(db, cacheConf)
	agentUpgradeModel := model.NewAgentUpgradeModel(db, cacheConf)
	agentWithdrawalModel := model.NewAgentWithdrawalModel(db, cacheConf)
	agentConfigModel := model.NewAgentConfigModel(db, cacheConf)
	agentProductConfigModel := model.NewAgentProductConfigModel(db, cacheConf)
	agentRealNameModel := model.NewAgentRealNameModel(db, cacheConf)
	agentWithdrawalTaxModel := model.NewAgentWithdrawalTaxModel(db, cacheConf)
	agentInviteCodeModel := model.NewAgentInviteCodeModel(db, cacheConf)
	agentInviteCodeUsageModel := model.NewAgentInviteCodeUsageModel(db, cacheConf)
	agentFreezeTaskModel := model.NewAgentFreezeTaskModel(db, cacheConf)
	agentShortLinkModel := model.NewAgentShortLinkModel(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)
	}

	// ============================== 业务服务初始化 ==============================
	alipayService := service.NewAliPayService(c)
	wechatPayService := service.NewWechatPayService(c, userAuthModel, service.InitTypeWxPayPubKeyPure)
	applePayService := service.NewApplePayService(c)
	apiRequestService := service.NewApiRequestService(c, featureModel, productFeatureModel, tianyuanapi)
	verificationService := service.NewVerificationService(c, tianyuanapi, apiRequestService)
	asynqService := service.NewAsynqService(c)
	agentService := service.NewAgentService(c, orderModel, agentModel, agentWalletModel,
		agentRelationModel, agentLinkModel, agentOrderModel, agentCommissionModel, agentRebateModel,
		agentUpgradeModel, agentWithdrawalModel, agentConfigModel, agentProductConfigModel,
		agentRealNameModel, agentWithdrawalTaxModel, agentFreezeTaskModel)
	userService := service.NewUserService(&c, userModel, userAuthModel, agentModel)
	dictService := service.NewDictService(adminDictTypeModel, adminDictDataModel)
	imageService := service.NewImageService()
	authorizationService := service.NewAuthorizationService(c, authorizationDocumentModel)
	tencentCloudService := service.NewTencentCloudService(c)
	// ============================== 异步任务服务 ==============================
	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,
		AgentRelationModel:        agentRelationModel,
		AgentLinkModel:            agentLinkModel,
		AgentOrderModel:           agentOrderModel,
		AgentCommissionModel:      agentCommissionModel,
		AgentRebateModel:          agentRebateModel,
		AgentUpgradeModel:         agentUpgradeModel,
		AgentWithdrawalModel:      agentWithdrawalModel,
		AgentConfigModel:          agentConfigModel,
		AgentProductConfigModel:   agentProductConfigModel,
		AgentRealNameModel:        agentRealNameModel,
		AgentWithdrawalTaxModel:   agentWithdrawalTaxModel,
		AgentInviteCodeModel:      agentInviteCodeModel,
		AgentInviteCodeUsageModel: agentInviteCodeUsageModel,
		AgentFreezeTaskModel:      agentFreezeTaskModel,
		AgentShortLinkModel:       agentShortLinkModel,

		// 管理后台相关模型
		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,
		ApiRequestService:    apiRequestService,
		AsynqServer:          asynqServer,
		AsynqService:         asynqService,
		VerificationService:  verificationService,
		AgentService:         agentService,
		UserService:          userService,
		DictService:          dictService,
		ImageService:         imageService,
		AuthorizationService: authorizationService,
		TencentCloudService:  tencentCloudService,
	}
}

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