package logic

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
)

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

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

func (l *CreateExchangeItemLogic) CreateExchangeItem(in *plant.CreateExchangeItemReq) (*plant.CommonResp, error) {
	cost := in.Cost
	if in.CostSunlight > 0 {
		cost = in.CostSunlight
	}
	itemType := in.Type
	if itemType == "" {
		itemType = "PHYSICAL"
	}
	imgID := in.ImgId
	if imgID == "" {
		imgID = in.ImageId
	}
	var startTime, endTime *time.Time
	if in.StartTime != "" {
		if t, err := time.Parse(time.DateTime, in.StartTime); err == nil {
			startTime = &t
		}
	}
	if in.EndTime != "" {
		if t, err := time.Parse(time.DateTime, in.EndTime); err == nil {
			endTime = &t
		}
	}
	item := plantModel.ExchangeItem{
		Name: in.Name, Desc: in.Desc, Description: in.Desc, ImgID: imgID, ImageID: imgID,
		Type: itemType, Cost: cost, CostSunlight: cost, Stock: int(in.Stock), Status: 1,
		LimitPerUser: int(in.LimitPerUser), Sort: int(in.Sort), StartTime: startTime, EndTime: endTime,
	}
	if err := l.svcCtx.DB.Create(&item).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
