package svc

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

	"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
	UserTempModel model.UserTempModel

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

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

	// 代理相关模型
	AgentModel                        model.AgentModel
	AgentAuditModel                   model.AgentAuditModel
	AgentClosureModel                 model.AgentClosureModel
	AgentCommissionModel              model.AgentCommissionModel
	AgentCommissionDeductionModel     model.AgentCommissionDeductionModel
	AgentWalletModel                  model.AgentWalletModel
	AgentLinkModel                    model.AgentLinkModel
	AgentOrderModel                   model.AgentOrderModel
	AgentRewardsModel                 model.AgentRewardsModel
	AgentMembershipConfigModel        model.AgentMembershipConfigModel
	AgentMembershipRechargeOrderModel model.AgentMembershipRechargeOrderModel
	AgentMembershipUserConfigModel    model.AgentMembershipUserConfigModel
	AgentProductConfigModel           model.AgentProductConfigModel
	AgentPlatformDeductionModel       model.AgentPlatformDeductionModel
	AgentActiveStatModel              model.AgentActiveStatModel
	AgentWithdrawalModel              model.AgentWithdrawalModel
	AgentRealNameModel                model.AgentRealNameModel
	AgentWithdrawalTaxModel           model.AgentWithdrawalTaxModel
	AgentWithdrawalTaxExemptionModel  model.AgentWithdrawalTaxExemptionModel
	AgentWalletTransactionModel       model.AgentWalletTransactionModel

	// 管理后台相关模型
	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
	AdminPromotionLinkModel             model.AdminPromotionLinkModel
	AdminPromotionLinkStatsTotalModel   model.AdminPromotionLinkStatsTotalModel
	AdminPromotionLinkStatsHistoryModel model.AdminPromotionLinkStatsHistoryModel
	AdminPromotionOrderModel            model.AdminPromotionOrderModel

	// 其他模型
	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
	AdminPromotionLinkStatsService *service.AdminPromotionLinkStatsService
	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)
	userTempModel := model.NewUserTempModel(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)
	queryUserRecordModel := model.NewQueryUserRecordModel(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)
	agentAuditModel := model.NewAgentAuditModel(db, cacheConf)
	agentClosureModel := model.NewAgentClosureModel(db, cacheConf)
	agentCommissionModel := model.NewAgentCommissionModel(db, cacheConf)
	agentCommissionDeductionModel := model.NewAgentCommissionDeductionModel(db, cacheConf)
	agentWalletModel := model.NewAgentWalletModel(db, cacheConf)
	agentLinkModel := model.NewAgentLinkModel(db, cacheConf)
	agentOrderModel := model.NewAgentOrderModel(db, cacheConf)
	agentRewardsModel := model.NewAgentRewardsModel(db, cacheConf)
	agentMembershipConfigModel := model.NewAgentMembershipConfigModel(db, cacheConf)
	agentMembershipRechargeOrderModel := model.NewAgentMembershipRechargeOrderModel(db, cacheConf)
	agentMembershipUserConfigModel := model.NewAgentMembershipUserConfigModel(db, cacheConf)
	agentProductConfigModel := model.NewAgentProductConfigModel(db, cacheConf)
	agentPlatformDeductionModel := model.NewAgentPlatformDeductionModel(db, cacheConf)
	agentActiveStatModel := model.NewAgentActiveStatModel(db, cacheConf)
	agentWithdrawalModel := model.NewAgentWithdrawalModel(db, cacheConf)
	agentRealNameModel := model.NewAgentRealNameModel(db, cacheConf)
	agentWithdrawalTaxModel := model.NewAgentWithdrawalTaxModel(db, cacheConf)
	agentWithdrawalTaxExemptionModel := model.NewAgentWithdrawalTaxExemptionModel(db, cacheConf)
	agentWalletTransactionModel := model.NewAgentWalletTransactionModel(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)
	adminPromotionLinkModel := model.NewAdminPromotionLinkModel(db, cacheConf)
	adminPromotionLinkStatsTotalModel := model.NewAdminPromotionLinkStatsTotalModel(db, cacheConf)
	adminPromotionLinkStatsHistoryModel := model.NewAdminPromotionLinkStatsHistoryModel(db, cacheConf)
	adminPromotionOrderModel := model.NewAdminPromotionOrderModel(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.InitTypeWxPayPubKey)
	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, agentAuditModel, agentClosureModel,
		agentCommissionModel, agentCommissionDeductionModel, agentWalletModel, agentLinkModel,
		agentOrderModel, agentRewardsModel, agentMembershipConfigModel, agentMembershipRechargeOrderModel,
		agentMembershipUserConfigModel, agentProductConfigModel, agentPlatformDeductionModel,
		agentActiveStatModel, agentWithdrawalModel, agentWalletTransactionModel, asynqService)
	userService := service.NewUserService(&c, userModel, userAuthModel, userTempModel, agentModel)
	dictService := service.NewDictService(adminDictTypeModel, adminDictDataModel)
	adminPromotionLinkStatsService := service.NewAdminPromotionLinkStatsService(adminPromotionLinkModel,
		adminPromotionLinkStatsTotalModel, adminPromotionLinkStatsHistoryModel)
	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(userModel).Handle,
		AdminAuthInterceptor: middleware.NewAdminAuthInterceptorMiddleware(c,
			adminUserModel, adminUserRoleModel, adminRoleModel, adminApiModel, adminRoleApiModel).Handle,

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

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

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

		// 代理相关模型
		AgentModel:                        agentModel,
		AgentAuditModel:                   agentAuditModel,
		AgentClosureModel:                 agentClosureModel,
		AgentCommissionModel:              agentCommissionModel,
		AgentCommissionDeductionModel:     agentCommissionDeductionModel,
		AgentWalletModel:                  agentWalletModel,
		AgentLinkModel:                    agentLinkModel,
		AgentOrderModel:                   agentOrderModel,
		AgentRewardsModel:                 agentRewardsModel,
		AgentMembershipConfigModel:        agentMembershipConfigModel,
		AgentMembershipRechargeOrderModel: agentMembershipRechargeOrderModel,
		AgentMembershipUserConfigModel:    agentMembershipUserConfigModel,
		AgentProductConfigModel:           agentProductConfigModel,
		AgentPlatformDeductionModel:       agentPlatformDeductionModel,
		AgentActiveStatModel:              agentActiveStatModel,
		AgentWithdrawalModel:              agentWithdrawalModel,
		AgentRealNameModel:                agentRealNameModel,
		AgentWithdrawalTaxModel:           agentWithdrawalTaxModel,
		AgentWithdrawalTaxExemptionModel:  agentWithdrawalTaxExemptionModel,
		AgentWalletTransactionModel:       agentWalletTransactionModel,

		// 管理后台相关模型
		AdminApiModel:                       adminApiModel,
		AdminMenuModel:                      adminMenuModel,
		AdminRoleModel:                      adminRoleModel,
		AdminRoleApiModel:                   adminRoleApiModel,
		AdminRoleMenuModel:                  adminRoleMenuModel,
		AdminUserModel:                      adminUserModel,
		AdminUserRoleModel:                  adminUserRoleModel,
		AdminDictDataModel:                  adminDictDataModel,
		AdminDictTypeModel:                  adminDictTypeModel,
		AdminPromotionLinkModel:             adminPromotionLinkModel,
		AdminPromotionLinkStatsTotalModel:   adminPromotionLinkStatsTotalModel,
		AdminPromotionLinkStatsHistoryModel: adminPromotionLinkStatsHistoryModel,
		AdminPromotionOrderModel:            adminPromotionOrderModel,

		// 其他模型
		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,
		AdminPromotionLinkStatsService: adminPromotionLinkStatsService,
		ImageService:                   imageService,
		AuthorizationService:           authorizationService,
	}
}

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