package model

import (
	"time"

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

type EventWeight struct {
	ID            int64  `json:"id"`
	PastureId     int64  `json:"pastureId"`
	CowId         int64  `json:"cowId"`
	EarNumber     string `json:"earNumber"`
	DayAge        int32  `json:"dayAge"`
	LactationDay  int64  `json:"lactationDay"`
	PenId         int32  `json:"penId"`
	Lact          int32  `json:"lact"`
	Weight        int32  `json:"weight"`
	Height        int32  `json:"height"`
	WeightAt      int64  `json:"weightAt"`
	Remarks       string `json:"remarks"`
	OperationId   int32  `json:"operationId"`
	OperationName string `json:"operationName"`
	MessageId     int64  `json:"messageId"`
	MessageName   string `json:"messageName"`
	CreatedAt     int64  `json:"created_at"`
	UpdatedAt     int64  `json:"updated_at"`
}

func (c *EventWeight) TableName() string {
	return "event_weight"
}

func NewEventWeight(pastureId int64, cow *Cow, currentUser *SystemUser, item *pasturePb.EventWeight) *EventWeight {
	return &EventWeight{
		PastureId:     pastureId,
		CowId:         cow.Id,
		EarNumber:     cow.EarNumber,
		Weight:        int32(item.Weight * 1000),
		Height:        item.Height,
		Lact:          cow.Lact,
		DayAge:        cow.GetDayAge(),
		WeightAt:      int64(item.WeightAt),
		Remarks:       item.Remarks,
		MessageId:     currentUser.Id,
		MessageName:   currentUser.Name,
		OperationId:   item.OperationId,
		OperationName: item.OperationName,
	}
}

type EventWeightSlice []*EventWeight

func (e EventWeightSlice) ToPB() []*pasturePb.CowGrowthCurveData {
	res := make([]*pasturePb.CowGrowthCurveData, len(e))
	for i, v := range e {
		weightAtFormat := ""
		if v.WeightAt > 0 {
			weightAtFormat = time.Unix(v.WeightAt, 0).Format(LayoutTime)
		}

		avgWeight := float32(0)
		if i > 0 {
			avgWeight = float32(v.Weight-e[i-1].Weight) / float32(v.WeightAt-e[i-1].WeightAt) / 24 / 1000
		}

		res[i] = &pasturePb.CowGrowthCurveData{
			Weight:          float32(v.Weight) / 1000,
			WeightAtFormat:  weightAtFormat,
			AvgWeight:       0,              // 平均体重
			DayAddWeight:    0,              // 日增重
			AvgDayAddWeight: avgWeight,      // 阶段日增重
			MonthAddWeight:  avgWeight * 30, // 月增重
		}
	}

	return res
}