package district

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"

	"git.noahlan.cn/n-admin/n-admin-server/api/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/api/internal/types"

	"net/http"
)

type GetDistrictTreeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetDistrictTreeLogic(r *http.Request, ctx context.Context, svcCtx *svc.ServiceContext) *GetDistrictTreeLogic {
	return &GetDistrictTreeLogic{
		r:      r,
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDistrictTreeLogic) GetDistrictTree(req *types.DistrictReq) (resp *types.DistrictTree, err error) {
	rpcResp, err := l.svcCtx.CoreRpc.GetDistrictTree(l.ctx, &core.DistrictCodeReq{Code: req.Code})
	if err != nil {
		return nil, err
	}
	resp = &types.DistrictTree{
		Tree: make([]*types.DistrictInfo, len(rpcResp.Tree)),
	}
	l.transTree(resp.Tree, rpcResp.Tree)
	return
}

func (l *GetDistrictTreeLogic) transTree(tree []*types.DistrictInfo, data []*core.DistrictInfo) {
	for i, info := range data {
		tmpInfo := l.svcCtx.Convert.ConvertDistrict(l.ctx, info)
		if len(info.Children) > 0 {
			l.transTree(tmpInfo.Children, info.Children)
		}
		tree[i] = tmpInfo
	}
}
