package model

import (
	"kpt-pasture/store/kptstore"
	"time"

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

type NeckRing struct {
	Id            int64                         `json:"id"`
	Number        string                        `json:"number"`
	CowId         int64                         `json:"cowId"`
	WearAt        int64                         `json:"wearAt"`
	Status        pasturePb.NeckRingStatus_Kind `json:"status"`
	ErrorReason   string                        `json:"errorReason"`
	OperationId   int32                         `json:"operationId"`
	OperationName string                        `json:"operationName"`
	CreatedAt     int64                         `json:"createdAt"`
	UpdatedAt     int64                         `json:"updatedAt"`
}

func (n *NeckRing) TableName() string {
	return "neck_ring"
}

func (n *NeckRing) Update(cowId int64) {
	n.CowId = cowId
	n.WearAt = time.Now().Unix()
}

func NewNeckRing(number string, cowId int64, operationUser *SystemUser) *NeckRing {
	return &NeckRing{
		Number:        number,
		CowId:         cowId,
		WearAt:        time.Now().Unix(),
		Status:        pasturePb.NeckRingStatus_Bind,
		OperationId:   int32(operationUser.Id),
		OperationName: operationUser.Name,
	}
}

type NeckRingSlice []*NeckRing

func (n NeckRingSlice) ToPB(
	neckRingStatus map[pasturePb.NeckRingStatus_Kind]string,
	db *kptstore.DB,
	getCowPenInfoByCowId func(DB *kptstore.DB, cowId int64) *Pen,
) []*pasturePb.SearchNeckRingList {
	res := make([]*pasturePb.SearchNeckRingList, len(n))
	for i, v := range n {
		penId := int32(0)
		penName := ""
		if v.CowId > 0 {
			penInfo := getCowPenInfoByCowId(db, v.CowId)
			if penInfo != nil {
				penId = penInfo.Id
				penName = penInfo.Name
			}
		}

		wearAtFormat := ""
		wearDays := int32(0)
		if v.WearAt > 0 {
			wearAtFormat = time.Unix(v.WearAt, 0).Format(LayoutDate2)
			wearDays = int32(time.Now().Sub(time.Unix(v.WearAt, 0)).Hours() / 24)
		}
		res[i] = &pasturePb.SearchNeckRingList{
			Id:           int32(v.Id),
			Number:       v.Number,
			PenId:        penId,
			PenName:      penName,
			CowId:        int32(v.CowId),
			WearAtFormat: wearAtFormat,
			WearDays:     wearDays,
			Status:       v.Status,
			StatusName:   neckRingStatus[v.Status],
			ErrorReason:  v.ErrorReason,
		}
	}
	return res
}