package admin_agent

import (
	"context"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

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

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

func (l *AdminBatchUnfreezeAgentCommissionLogic) AdminBatchUnfreezeAgentCommission(req *types.AdminBatchUnfreezeAgentCommissionReq) (resp *types.AdminBatchUnfreezeAgentCommissionResp, err error) {
	// 构建查询条件：状态为1（冻结中）
	builder := l.svcCtx.AgentCommissionModel.SelectBuilder().Where(squirrel.Eq{"status": 1})

	// 如果指定了代理商ID，则只查询该代理商的冻结佣金
	if req.AgentId != nil && *req.AgentId > 0 {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}

	// 查询所有冻结中的佣金记录
	commissions, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, err
	}

	// 如果没有冻结的佣金，直接返回
	if len(commissions) == 0 {
		resp = &types.AdminBatchUnfreezeAgentCommissionResp{
			Success: true,
			Count:   0,
			Amount:  0,
		}
		return
	}

	// 计算总金额
	var totalAmount float64
	for _, commission := range commissions {
		totalAmount += commission.Amount
	}

	// 开始事务
	err = l.svcCtx.AgentCommissionModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 按代理商分组更新钱包余额
		agentWalletMap := make(map[int64]*model.AgentWallet)

		// 遍历所有冻结的佣金，更新状态
		for _, commission := range commissions {
			// 更新佣金状态为已结算
			commission.Status = 0
			err := l.svcCtx.AgentCommissionModel.UpdateWithVersion(ctx, session, commission)
			if err != nil {
				return err
			}

			// 累加到对应代理商的钱包数据
			if wallet, exists := agentWalletMap[commission.AgentId]; exists {
				wallet.Balance += commission.Amount
				wallet.FrozenBalance -= commission.Amount
			} else {
				// 查询该代理商的钱包
				wallet, err := l.svcCtx.AgentWalletModel.FindOneByAgentId(ctx, commission.AgentId)
				if err != nil {
					return err
				}
				wallet.Balance += commission.Amount
				wallet.FrozenBalance -= commission.Amount
				agentWalletMap[commission.AgentId] = wallet
			}
		}

		// 更新所有受影响代理商的钱包
		for _, wallet := range agentWalletMap {
			err := l.svcCtx.AgentWalletModel.UpdateWithVersion(ctx, session, wallet)
			if err != nil {
				return err
			}
		}

		return nil
	})

	if err != nil {
		return nil, xerr.NewErrMsg("批量解冻失败: " + err.Error())
	}

	resp = &types.AdminBatchUnfreezeAgentCommissionResp{
		Success: true,
		Count:   int64(len(commissions)),
		Amount:  totalAmount,
	}
	return
}
