package agent

import (
	"context"
	"bdqr-server/app/main/model"
	"bdqr-server/common/ctxdata"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"
	"bdqr-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

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

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

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

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

func (l *GetSubordinateListLogic) GetSubordinateList(req *types.GetSubordinateListReq) (resp *types.GetSubordinateListResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	// 1. 获取代理信息
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("您不是代理"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 2. 构建查询条件（查询直接下级）
	builder := l.svcCtx.AgentRelationModel.SelectBuilder().
		Where("parent_id = ? AND relation_type = ? AND del_state = ?", agent.Id, 1, globalkey.DelStateNo).
		OrderBy("create_time DESC")

	// 3. 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (page - 1) * pageSize

	// 4. 查询总数
	total, err := l.svcCtx.AgentRelationModel.FindCount(l.ctx, builder, "id")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询下级总数失败, %v", err)
	}

	// 5. 查询列表
	builder = builder.Limit(uint64(pageSize)).Offset(uint64(offset))
	relations, err := l.svcCtx.AgentRelationModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询下级列表失败, %v", err)
	}

	// 6. 组装响应
	var list []types.SubordinateItem
	for _, relation := range relations {
		subordinate, err := l.svcCtx.AgentModel.FindOne(l.ctx, relation.ChildId)
		if err != nil {
			continue
		}

		levelName := ""
		switch subordinate.Level {
		case 1:
			levelName = "普通"
		case 2:
			levelName = "黄金"
		case 3:
			levelName = "钻石"
		}

		// 解密手机号
		mobile := ""
		if subordinate.Mobile != "" {
			decrypted, err := crypto.DecryptMobile(subordinate.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
			if err == nil {
				mobile = decrypted
			}
		}

		// 统计订单数和金额
		totalOrders := int64(0)
		totalAmount := 0.0
		orderBuilder := l.svcCtx.AgentOrderModel.SelectBuilder().
			Where("agent_id = ? AND del_state = ?", subordinate.Id, globalkey.DelStateNo)
		orders, err := l.svcCtx.AgentOrderModel.FindAll(l.ctx, orderBuilder, "")
		if err == nil {
			totalOrders = int64(len(orders))
			for _, order := range orders {
				totalAmount += order.OrderAmount
			}
		}

		list = append(list, types.SubordinateItem{
			AgentId:     subordinate.Id,
			Level:       subordinate.Level,
			LevelName:   levelName,
			Mobile:      mobile,
			TotalOrders: totalOrders,
			TotalAmount: totalAmount,
			CreateTime:  relation.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.GetSubordinateListResp{
		Total: total,
		List:  list,
	}, nil
}
