package logic

import (
	"context"
	"time"

	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"
	"gorm.io/gorm"
)

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

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

// 创建植物
func (l *CreatePlantLogic) CreatePlant(in *plant.CreatePlantReq) (*plant.CommonResp, error) {
	// 解析植时间
	plantTime, err := time.Parse("2006-01-02", in.PlantTime)
	if err != nil {
		plantTime = time.Now()
	}

	var myPlantID string
	txErr := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
		myPlant := plantModel.MyPlant{
			UserID:           in.UserId,
			Name:             in.Name,
			PlantTime:        plantTime,
			Status:           1,
			Placement:        in.Placement,
			PotMaterial:      in.PotMaterial,
			PotSize:          in.PotSize,
			Sunlight:         in.Sunlight,
			PlantingMaterial: in.PlantingMaterial,
		}
		if err := tx.Create(&myPlant).Error; err != nil {
			return err
		}
		myPlantID = myPlant.ID
		// 处理图片关联
		if len(in.ImgIds) > 0 {
			var relations []map[string]interface{}
			for _, id := range in.ImgIds {
				relations = append(relations, map[string]interface{}{
					"sundynix_my_plant_id": myPlant.ID,
					"sundynix_oss_id":      id,
				})
			}
			if err := tx.Table("sundynix_plant_my_plant_oss").Create(relations).Error; err != nil {
				return err
			}
		}
		// 更新用户 plant_count
		return tx.Model(&plantModel.UserProfile{}).Where("user_id = ?", in.UserId).
			Update("plant_count", gorm.Expr("plant_count + 1")).Error
	})
	if txErr != nil {
		return nil, txErr
	}
	return &plant.CommonResp{Code: 0, Msg: myPlantID}, nil
}
