package agent

import (
	"context"
	"strconv"

	"qnc-server/app/main/model"
	"qnc-server/common/ctxdata"
	"qnc-server/common/xerr"

	"github.com/pkg/errors"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetLevelPrivilegeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetLevelPrivilegeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLevelPrivilegeLogic {
	return &GetLevelPrivilegeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetLevelPrivilegeLogic) GetLevelPrivilege() (resp *types.GetLevelPrivilegeResp, err error) {
	// 1. 获取当前代理等级
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	var currentLevel int64 = 1 // 默认普通代理
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}
	if agent != nil {
		currentLevel = agent.Level
	}

	// 获取配置值的辅助函数
	getConfigFloat := func(key string, defaultValue float64) float64 {
		config, err := l.svcCtx.AgentConfigModel.FindOneByConfigKey(l.ctx, key)
		if err != nil {
			return defaultValue
		}
		value, err := strconv.ParseFloat(config.ConfigValue, 64)
		if err != nil {
			return defaultValue
		}
		return value
	}

	// 获取等级加成配置
	level1Bonus := getConfigFloat("level_1_bonus", 6.0)
	level2Bonus := getConfigFloat("level_2_bonus", 3.0)
	level3Bonus := getConfigFloat("level_3_bonus", 0.0)

	// 获取当前等级的加成
	var currentBonus float64
	switch currentLevel {
	case 1:
		currentBonus = level1Bonus
	case 2:
		currentBonus = level2Bonus
	case 3:
		currentBonus = level3Bonus
	default:
		currentBonus = level1Bonus
	}

	// 获取升级返佣与费用配置（同时作为邀请奖励金额）
	upgradeToGoldRebate := getConfigFloat("upgrade_to_gold_rebate", 139.0)
	upgradeToDiamondRebate := getConfigFloat("upgrade_to_diamond_rebate", 680.0)
	upgradeToGoldFee := getConfigFloat("upgrade_to_gold_fee", 199.0)
	upgradeToDiamondFee := getConfigFloat("upgrade_to_diamond_fee", 980.0)

	// 获取直接上级返佣配置
	directParentAmountDiamond := getConfigFloat("direct_parent_amount_diamond", 6.0)
	directParentAmountGold := getConfigFloat("direct_parent_amount_gold", 3.0)
	directParentAmountNormal := getConfigFloat("direct_parent_amount_normal", 2.0)

	// 获取不同等级的提价上限（用于计算各等级可设置的最高查询价）
	goldMaxUpliftAmount := getConfigFloat("gold_max_uplift_amount", 0.0)
	diamondMaxUpliftAmount := getConfigFloat("diamond_max_uplift_amount", 0.0)

	// 计算所有产品在各等级下的可设最高查询价（取所有产品中的最大值）
	var maxSetPriceLevel1, maxSetPriceLevel2, maxSetPriceLevel3 float64
	builder := l.svcCtx.AgentProductConfigModel.SelectBuilder()
	productConfigs, err := l.svcCtx.AgentProductConfigModel.FindAll(l.ctx, builder, "")
	if err == nil {
		for _, cfg := range productConfigs {
			// 普通等级：直接使用系统价格上限
			if cfg.SystemMaxPrice > maxSetPriceLevel1 {
				maxSetPriceLevel1 = cfg.SystemMaxPrice
			}
			// 黄金等级：系统价格上限 + gold_max_uplift_amount
			if cfg.SystemMaxPrice+goldMaxUpliftAmount > maxSetPriceLevel2 {
				maxSetPriceLevel2 = cfg.SystemMaxPrice + goldMaxUpliftAmount
			}
			// 钻石等级：系统价格上限 + diamond_max_uplift_amount
			if cfg.SystemMaxPrice+diamondMaxUpliftAmount > maxSetPriceLevel3 {
				maxSetPriceLevel3 = cfg.SystemMaxPrice + diamondMaxUpliftAmount
			}
		}
	} else if !errors.Is(err, model.ErrNotFound) {
		// 查询失败不影响主流程，仅记录日志，前端会看到 0
		l.Errorf("查询产品配置失败用于计算最高可设查询价, err: %v", err)
	}

	// 构建各等级特权信息
	levels := []types.LevelPrivilegeItem{
		{
			Level:            1,
			LevelName:        "普通代理",
			LevelBonus:       level1Bonus,
			PriceReduction:   l.calculatePriceReduction(currentBonus, level1Bonus),
			PromoteRebate:    l.buildPromoteRebateDesc(1, directParentAmountDiamond, directParentAmountGold, directParentAmountNormal),
			MaxPromoteRebate: directParentAmountDiamond, // 普通代理最高返佣是直接上级是钻石时的返佣
			UpgradeRebate:    l.buildUpgradeRebateDesc(1, upgradeToGoldRebate, upgradeToDiamondRebate),
			Privileges: []string{
				"基础代理特权",
				"可生成推广链接",
				"享受推广返佣",
				"可邀请下级代理",
			},
			CanUpgradeSubordinate: false,
			MaxSetPrice:           maxSetPriceLevel1,
			SubordinateRewardMax:  directParentAmountNormal,
			InviteGoldReward:      upgradeToGoldRebate,
			InviteDiamondReward:   upgradeToDiamondRebate,
		},
		{
			Level:            2,
			LevelName:        "黄金代理",
			LevelBonus:       level2Bonus,
			PriceReduction:   l.calculatePriceReduction(currentBonus, level2Bonus),
			PromoteRebate:    l.buildPromoteRebateDesc(2, directParentAmountDiamond, directParentAmountGold, directParentAmountNormal),
			MaxPromoteRebate: level2Bonus, // 黄金代理最高返佣是等级加成全部返佣给钻石上级
			UpgradeRebate:    l.buildUpgradeRebateDesc(2, upgradeToGoldRebate, upgradeToDiamondRebate),
			Privileges: []string{
				"高级代理特权",
				"更高的返佣比例",
				"享受推广返佣",
				"可邀请下级代理",
				"更多推广权益",
			},
			CanUpgradeSubordinate: false,
			MaxSetPrice:           maxSetPriceLevel2,
			SubordinateRewardMax:  directParentAmountGold,
			InviteGoldReward:      upgradeToGoldRebate,
			InviteDiamondReward:   upgradeToDiamondRebate,
		},
		{
			Level:            3,
			LevelName:        "钻石代理",
			LevelBonus:       level3Bonus,
			PriceReduction:   l.calculatePriceReduction(currentBonus, level3Bonus),
			PromoteRebate:    l.buildPromoteRebateDesc(3, directParentAmountDiamond, directParentAmountGold, directParentAmountNormal),
			MaxPromoteRebate: 0, // 钻石代理无返佣
			UpgradeRebate:    l.buildUpgradeRebateDesc(3, upgradeToGoldRebate, upgradeToDiamondRebate),
			Privileges: []string{
				"尊享代理特权",
				"最高返佣比例",
				"独立团队管理",
				"可调整下级级别",
				"可免费升级下级为黄金代理",
			},
			CanUpgradeSubordinate: true,
			MaxSetPrice:           maxSetPriceLevel3,
			SubordinateRewardMax:  directParentAmountDiamond,
			InviteGoldReward:      upgradeToGoldRebate,
			InviteDiamondReward:   upgradeToDiamondRebate,
		},
	}

	return &types.GetLevelPrivilegeResp{
		Levels:                 levels,
		UpgradeToGoldFee:       upgradeToGoldFee,
		UpgradeToDiamondFee:    upgradeToDiamondFee,
		UpgradeToGoldRebate:    upgradeToGoldRebate,
		UpgradeToDiamondRebate: upgradeToDiamondRebate,
	}, nil
}

// buildPromoteRebateDesc 构建推广返佣说明
func (l *GetLevelPrivilegeLogic) buildPromoteRebateDesc(level int64, diamondAmount, goldAmount, normalAmount float64) string {
	switch level {
	case 1: // 普通代理：等级加成6元
		return "更高的推广返佣，最高可达¥" + l.formatFloat(diamondAmount)
	case 2: // 黄金代理：等级加成3元
		return "更高的推广返佣，最高可达¥" + l.formatFloat(3.0)
	case 3: // 钻石代理：等级加成0元
		return "无等级加成，享受最低底价"
	default:
		return ""
	}
}

// buildUpgradeRebateDesc 构建下级升级返佣说明
func (l *GetLevelPrivilegeLogic) buildUpgradeRebateDesc(level int64, goldRebate, diamondRebate float64) string {
	switch level {
	case 1: // 普通代理
		return "下级升级为黄金代理返佣¥" + l.formatFloat(goldRebate) + "，升级为钻石代理返佣¥" + l.formatFloat(diamondRebate)
	case 2: // 黄金代理
		return "下级升级为钻石代理返佣¥" + l.formatFloat(diamondRebate)
	case 3: // 钻石代理
		return "可免费升级下级为黄金代理"
	default:
		return ""
	}
}

// calculatePriceReduction 计算底价降低（相对于当前等级）
func (l *GetLevelPrivilegeLogic) calculatePriceReduction(currentBonus, targetBonus float64) float64 {
	reduction := currentBonus - targetBonus
	if reduction < 0 {
		return 0
	}
	return reduction
}

// formatFloat 格式化浮点数，去掉末尾的0
func (l *GetLevelPrivilegeLogic) formatFloat(f float64) string {
	s := strconv.FormatFloat(f, 'f', -1, 64)
	return s
}
