package query import ( "context" "encoding/json" "fmt" "sort" "adm-vehicle-style/errors" "adm-vehicle-style/model" v1 "adm-vehicle-style/pb/v1" jsoniter "github.com/json-iterator/go" "git.getensh.com/common/gopkgsv2/database" "git.getensh.com/common/gopkgsv2/logger" "go.uber.org/zap" "google.golang.org/grpc/status" "gorm.io/gorm" ) type StyleListRequest struct { SeriesID string `json:"series_id"` } type styleItem struct { BrandID string `json:"brand_id"` Maker string `json:"maker"` ModelYear string `json:"model_year"` Price string `json:"price"` SeriesID string `json:"series_id"` StyleID string `json:"style_id"` StyleName string `json:"style_name"` } type styleList struct { ModelYear string `json:"model_year"` StyleList []styleItem `json:"style_list"` } type StyleListResponse struct { List []styleList `json:"list"` } func StyleList(ctx context.Context, params string) (reply *v1.QueryResponse, err error) { reply = &v1.QueryResponse{} // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err = fmt.Errorf("%+v", r) e := &status.Status{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { logger.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() var req StyleListRequest err = jsoniter.UnmarshalFromString(params, &req) if err != nil || req.SeriesID == "" { return nil, errors.ParamsError } list, err := model.NewSyStyleModel(). StyleList(database.DB().Where("series_id = ? AND is_on = 1", req.SeriesID), "brand_id, maker, model_year, price, series_id, style_id, style_name") if err != nil && err != gorm.ErrRecordNotFound { return reply, errors.SystemError } if err == gorm.ErrRecordNotFound { return reply, nil } yearMap := make(map[string][]styleItem) for _, v := range list { yearMap[v.ModelYear] = append(yearMap[v.ModelYear], styleItem{ BrandID: v.BrandId, Maker: v.Maker, ModelYear: v.ModelYear, Price: v.Price, SeriesID: v.SeriesId, StyleID: v.StyleId, StyleName: v.StyleName, }) } var keys []string keyLen := 0 for k := range yearMap { keys = append(keys, k) keyLen++ } sort.Strings(keys) res := StyleListResponse{} for i := keyLen - 1; i >= 0; i-- { st := styleList{ ModelYear: keys[i], StyleList: yearMap[keys[i]], } res.List = append(res.List, st) } reply.Data, _ = jsoniter.MarshalToString(res) return reply, nil }