package service

import (
	"context"
	"sim-server/app/main/api/internal/config"
	"sim-server/app/main/model"
	"sim-server/pkg/lzkit/lzUtils"
	"time"

	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

// AgentService 新代理系统服务
// 系统简化：移除团队关系、返佣、升级、提现、实名认证、邀请码功能
type AgentService struct {
	config                  config.Config
	OrderModel              model.OrderModel
	AgentModel              model.AgentModel
	AgentWalletModel        model.AgentWalletModel
	AgentLinkModel          model.AgentLinkModel
	AgentOrderModel         model.AgentOrderModel
	AgentCommissionModel    model.AgentCommissionModel
	AgentConfigModel        model.AgentConfigModel
	AgentProductConfigModel model.AgentProductConfigModel
}

// NewAgentService 创建新的代理服务
// 系统简化：移除团队关系、返佣、升级、提现、实名认证、邀请码功能
func NewAgentService(
	c config.Config,
	orderModel model.OrderModel,
	agentModel model.AgentModel,
	agentWalletModel model.AgentWalletModel,
	agentLinkModel model.AgentLinkModel,
	agentOrderModel model.AgentOrderModel,
	agentCommissionModel model.AgentCommissionModel,
	agentConfigModel model.AgentConfigModel,
	agentProductConfigModel model.AgentProductConfigModel,
) *AgentService {
	return &AgentService{
		config:                  c,
		OrderModel:              orderModel,
		AgentModel:              agentModel,
		AgentWalletModel:        agentWalletModel,
		AgentLinkModel:          agentLinkModel,
		AgentOrderModel:         agentOrderModel,
		AgentCommissionModel:    agentCommissionModel,
		AgentConfigModel:        agentConfigModel,
		AgentProductConfigModel: agentProductConfigModel,
	}
}

// AgentProcess 处理代理订单（简化版）
// 系统简化：只计算代理自己的推广佣金，不再有等级、团队、返佣等复杂逻辑
func (s *AgentService) AgentProcess(ctx context.Context, order *model.Order) error {
	// 1. 检查是否是代理推广订单
	agentOrder, err := s.AgentOrderModel.FindOneByOrderId(ctx, order.Id)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 不是代理订单，直接返回
			return nil
		}
		return errors.Wrapf(err, "查询代理订单失败, orderId: %s", order.Id)
	}

	// 2. 检查订单是否已处理
	if agentOrder.ProcessStatus == 1 {
		logx.Infof("订单已处理, orderId: %s", order.Id)
		return nil
	}

	// 3. 获取产品配置（必须存在）
	productConfig, err := s.AgentProductConfigModel.FindOneByProductId(ctx, order.ProductId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return errors.Wrapf(err, "产品配置不存在, productId: %s，请先在后台配置产品价格参数", order.ProductId)
		}
		return errors.Wrapf(err, "查询产品配置失败, productId: %s", order.ProductId)
	}

	// 4. 使用事务处理订单
	err = s.AgentWalletModel.Trans(ctx, func(transCtx context.Context, session sqlx.Session) error {
		// 4.1 计算代理收益 = 设置价 - 底价 - 提价成本
		basePrice := productConfig.BasePrice

		// 计算提价成本
		priceThreshold := 0.0
		priceFeeRate := 0.0
		if productConfig.PriceThreshold.Valid {
			priceThreshold = productConfig.PriceThreshold.Float64
		}
		if productConfig.PriceFeeRate.Valid {
			priceFeeRate = productConfig.PriceFeeRate.Float64
		}
		priceCost := s.calculatePriceCost(agentOrder.SetPrice, priceThreshold, priceFeeRate)

		// 代理收益
		agentProfit := agentOrder.SetPrice - basePrice - priceCost

		// 4.2 更新代理订单记录
		agentOrder.ProcessStatus = 1
		agentOrder.ProcessTime = lzUtils.TimeToNullTime(time.Now())
		agentOrder.ProcessRemark = lzUtils.StringToNullString("处理成功")
		if err := s.AgentOrderModel.UpdateWithVersion(transCtx, session, agentOrder); err != nil {
			return errors.Wrapf(err, "更新代理订单失败")
		}

		// 4.3 发放代理佣金
		err := s.giveAgentCommission(transCtx, session, agentOrder.AgentId, order.Id, order.ProductId, agentProfit)
		if err != nil {
			return errors.Wrapf(err, "发放代理佣金失败")
		}

		return nil
	})

	return err
}

// calculatePriceCost 计算提价成本
func (s *AgentService) calculatePriceCost(setPrice, priceThreshold, priceFeeRate float64) float64 {
	if setPrice <= priceThreshold {
		return 0
	}
	return (setPrice - priceThreshold) * priceFeeRate
}

// giveAgentCommission 发放代理佣金
// 系统简化：移除佣金冻结功能，直接发放全部金额
func (s *AgentService) giveAgentCommission(ctx context.Context, session sqlx.Session, agentId, orderId, productId string, amount float64) error {
	// 1. 创建佣金记录
	commission := &model.AgentCommission{
		Id:        uuid.NewString(),
		AgentId:   agentId,
		OrderId:   orderId,
		ProductId: productId,
		Amount:    amount,
		Status:    1, // 已发放
	}
	_, err := s.AgentCommissionModel.Insert(ctx, session, commission)
	if err != nil {
		return errors.Wrapf(err, "创建佣金记录失败")
	}

	// 2. 更新钱包余额
	wallet, err := s.AgentWalletModel.FindOneByAgentId(ctx, agentId)
	if err != nil {
		return errors.Wrapf(err, "查询钱包失败, agentId: %s", agentId)
	}

	// 直接发放全部佣金金额到余额
	wallet.Balance += amount
	wallet.TotalEarnings += amount
	if err := s.AgentWalletModel.UpdateWithVersion(ctx, session, wallet); err != nil {
		return errors.Wrapf(err, "更新钱包失败")
	}

	return nil
}

// 系统简化：移除所有团队关系、返佣、升级功能
// 以下方法已删除：distributeLevelBonus, distributeNormalAgentBonus, giveRebate, findDirectParent, findDiamondParent, findGoldParent 等
// 以及佣金冻结功能：getConfigFloat, getConfigInt
