package data

import (
	"context"
	"fmt"

	pb "bsm/full/module/base/initial/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
)

// 区域数据,默认级别：市
func Areas(ctx context.Context, in *pb.AreasRequest) (reply *pb.AreasReply, err error) {
	// 参数检查 - 如果都没有提供，默认使用中国(ID=1)
	if in.GetCountryCode() == "" && in.GetCountryId() == 0 {
		in.CountryId = 1 // 默认中国
	}

	// 查询条件:国家代码优先
	areas, err := GetAreasByCache(in)
	if err != nil {
		printer.Error("GetAreasByCache", err)
		return nil, errcode.ErrDB
	}

	// 转换为响应格式
	var data []*pb.AreasItem
	for _, area := range areas {
		data = append(data, &pb.AreasItem{
			Id:           fmt.Sprintf("%d", area.Id),
			Pid:          fmt.Sprintf("%d", area.Pid),
			Deep:         area.Deep,
			Name:         area.Name,
			PinyinPrefix: area.PinyinPrefix,
			Pinyin:       area.Pinyin,
			ExtId:        area.ExtId,
			ExtName:      area.ExtName,
		})
	}

	return &pb.AreasReply{
		Areas: data,
	}, nil
}
