package myPlant

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"sundynix-micro-go/app/plant/api/internal/svc"
	"sundynix-micro-go/app/plant/api/internal/types"
	"sundynix-micro-go/app/plant/rpc/plant"
)

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

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

func (l *CreatePlantLogic) CreatePlant(req *types.CreatePlantReq) error {
	userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
	imgIds := req.ImgIds
	if len(imgIds) == 0 {
		imgIds = req.OssIds
	}
	resp, err := l.svcCtx.PlantRpc.CreatePlant(l.ctx, &plant.CreatePlantReq{
		UserId: userId, Name: req.Name, PlantTime: req.PlantTime, Placement: req.Placement,
		PotMaterial: req.PotMaterial, PotSize: req.PotSize, Sunlight: req.Sunlight,
		PlantingMaterial: req.PlantingMaterial, ImgIds: imgIds,
	})
	if err != nil {
		return err
	}
	if resp == nil || resp.Msg == "" || resp.Msg == "ok" {
		return nil
	}
	for _, planReq := range req.CarePlans {
		if planReq.Name == "" || planReq.Period <= 0 {
			continue
		}
		if _, err = l.svcCtx.PlantRpc.AddCarePlan(l.ctx, &plant.AddCarePlanReq{
			UserId:       userId,
			PlantId:      resp.Msg,
			Name:         planReq.Name,
			Icon:         planReq.Icon,
			TargetAction: planReq.TargetAction,
			Period:       int32(planReq.Period),
		}); err != nil {
			return err
		}
	}
	return nil
}
