package backend

import (
	"context"
	"kpt-pasture/model"
	"net/http"
	"strings"
	"time"

	"gitee.com/xuyiping_admin/pkg/xerr"

	pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
)

// GrowthCurve 生长曲线 获取图表数据
func (s *StoreEntry) GrowthCurve(ctx context.Context, req *pasturePb.SearchGrowthCurvesRequest) (*pasturePb.GrowthCurvesResponse, error) {
	// 查询数据
	cowList := make([]*model.Cow, 0)
	pref := s.DB.Model(new(model.Cow)).Where("is_remove = ?", pasturePb.IsShow_Ok)
	if req.GetCowId() != "" {
		pref.Where("id IN ?", strings.Split(req.CowId, ","))
	}

	if len(req.BirthDate) == 2 && req.BirthDate[0] != "" && req.BirthDate[1] != "" {
		t0, _ := time.Parse(time.RFC3339, req.BirthDate[0])
		t1, _ := time.Parse(time.RFC3339, req.BirthDate[1])

		pref.Where("birth_at BETWEEN ? AND ?", t0.Unix(), t1.Unix()+86399)
	}

	if err := pref.Find(&cowList).Error; err != nil {
		return nil, err
	}
	penList, err := s.GetPenList(ctx)
	if err != nil {
		return nil, xerr.WithStack(err)
	}
	// 计算图表数据
	chartsList := &pasturePb.Charts{
		CowId:  make([]int32, 0),
		Weight: make([]float32, 0),
		DayAge: make([]int32, 0),
	}
	cowData := make([]*pasturePb.CowList, 0)
	for _, cow := range cowList {
		currentWeight := float32(cow.CurrentWeight) / 100
		penName := ""
		for _, v := range penList {
			if cow.PenId != v.Id {
				continue
			}
			penName = v.Name
		}
		cowData = append(cowData, &pasturePb.CowList{
			CowId:                  int32(cow.Id),
			EarNumber:              cow.EarNumber,
			DayAge:                 cow.GetDayAge(),
			PenName:                penName,
			CurrentWeight:          currentWeight,
			BirthAt:                int32(cow.BirthAt),
			BirthWeight:            float32(cow.BirthWeight) / 100,
			LastWeightAt:           int32(cow.LastWeightAt),
			DailyWeightGain:        float32(cow.GetDayWeight() / 100),
			AverageDailyWeightGain: float32(cow.GetAverageDailyWeight() / 100),
		})

		chartsList.CowId = append(chartsList.CowId, int32(cow.Id))
		chartsList.Weight = append(chartsList.Weight, currentWeight)
		chartsList.DayAge = append(chartsList.DayAge, cow.GetDayAge())
	}

	// 返回数据
	return &pasturePb.GrowthCurvesResponse{
		Code:    http.StatusOK,
		Message: "success",
		Data: &pasturePb.GrowthCurveData{
			Table:  cowData,
			Charts: chartsList,
		},
	}, nil

}