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 GetPlantDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

// 植物详情
func (l *GetPlantDetailLogic) GetPlantDetail(in *plant.IdReq) (*plant.PlantDetailResp, error) {
	var myPlant plantModel.MyPlant
	if err := l.svcCtx.DB.Where("id = ?", in.Id).First(&myPlant).Error; err != nil {
		return nil, err
	}

	// 魏护计划
	var carePlans []plantModel.CarePlan
	l.svcCtx.DB.Where("plant_id = ?", in.Id).Find(&carePlans)
	var planInfos []*plant.CarePlanInfo
	for _, cp := range carePlans {
		planInfos = append(planInfos, &plant.CarePlanInfo{
			Id:           cp.ID,
			PlantId:      cp.PlantID,
			Name:         cp.Name,
			Icon:         cp.Icon,
			TargetAction: cp.TargetAction,
			Period:       int32(cp.Period),
		})
	}

	// 成长记录
	var growthRecords []plantModel.GrowthRecord
	l.svcCtx.DB.Where("plant_id = ?", in.Id).Order("created_at desc").Find(&growthRecords)
	var growthInfos []*plant.GrowthRecordInfo
	for _, gr := range growthRecords {
		growthInfos = append(growthInfos, &plant.GrowthRecordInfo{
			Id:        gr.ID,
			PlantId:   gr.PlantID,
			Content:   gr.Content,
			CreatedAt: gr.CreatedAt.Unix(),
		})
	}

	return &plant.PlantDetailResp{
		Plant: &plant.PlantInfo{
			Id:               myPlant.ID,
			UserId:           myPlant.UserID,
			Name:             myPlant.Name,
			PlantTime:        myPlant.PlantTime.Format("2006-01-02"),
			Status:           int32(myPlant.Status),
			Placement:        myPlant.Placement,
			PotMaterial:      myPlant.PotMaterial,
			PotSize:          myPlant.PotSize,
			Sunlight:         myPlant.Sunlight,
			PlantingMaterial: myPlant.PlantingMaterial,
			CreatedAt:        myPlant.CreatedAt.Unix(),
		},
		CarePlans:     planInfos,
		GrowthRecords: growthInfos,
	}, nil
}
