package logic

import (
	"context"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPlantListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPlantListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPlantListLogic {
	return &GetPlantListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 我的植物列表
func (l *GetPlantListLogic) GetPlantList(in *plant.PlantListReq) (*plant.PlantListResp, error) {
	db := l.svcCtx.DB.Model(&plantModel.MyPlant{}).Where("user_id = ?", in.UserId)
	if in.Name != "" {
		db = db.Where("name like ?", "%"+in.Name+"%")
	}

	var total int64
	db.Count(&total)

	pageSize := int(in.PageSize)
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (int(in.Current) - 1) * pageSize
	if offset < 0 {
		offset = 0
	}

	var list []plantModel.MyPlant
	if err := db.Limit(pageSize).Offset(offset).Order("created_at desc").Find(&list).Error; err != nil {
		return nil, err
	}

	var result []*plant.PlantInfo
	for _, item := range list {
		result = append(result, &plant.PlantInfo{
			Id:               item.ID,
			UserId:           item.UserID,
			Name:             item.Name,
			PlantTime:        item.PlantTime.Format("2006-01-02"),
			Status:           int32(item.Status),
			Placement:        item.Placement,
			PotMaterial:      item.PotMaterial,
			PotSize:          item.PotSize,
			Sunlight:         item.Sunlight,
			PlantingMaterial: item.PlantingMaterial,
			CreatedAt:        item.CreatedAt.Unix(),
		})
	}

	return &plant.PlantListResp{List: result, Total: total}, nil
}
