package logic

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
	"time"
)

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

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

func (l *UpdateExchangeOrderLogic) UpdateExchangeOrder(in *plant.UpdateExchangeOrderReq) (*plant.CommonResp, error) {
	updateMap := map[string]interface{}{"status": int(in.Status), "tracking_no": in.TrackingNo, "remark": in.Remark}
	if in.Status == 4 {
		now := time.Now()
		updateMap["completed_at"] = &now
	}
	if in.Status == 5 {
		err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
			var order plantModel.ExchangeOrder
			if err := tx.Set("gorm:query_option", "FOR UPDATE").Where("id = ?", in.Id).First(&order).Error; err != nil {
				return err
			}
			if order.Status == 5 {
				return errors.New("订单已取消")
			}
			cost := order.CostSunlight
			if cost == 0 {
				cost = order.Cost
			}
			if err := tx.Model(&plantModel.UserProfile{}).Where("user_id = ?", order.UserID).
				Update("current_sunlight", gorm.Expr("current_sunlight + ?", cost)).Error; err != nil {
				return err
			}
			if order.Quantity <= 0 {
				order.Quantity = 1
			}
			if err := tx.Model(&plantModel.ExchangeItem{}).Where("id = ? AND stock >= 0", order.ItemID).
				Update("stock", gorm.Expr("stock + ?", order.Quantity)).Error; err != nil {
				return err
			}
			return tx.Model(&plantModel.ExchangeOrder{}).Where("id = ?", in.Id).Updates(updateMap).Error
		})
		if err != nil {
			return nil, err
		}
		return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
	}
	if err := l.svcCtx.DB.Model(&plantModel.ExchangeOrder{}).Where("id = ?", in.Id).Updates(updateMap).Error; err != nil {
		return nil, err
	}
	return &plant.CommonResp{Code: 0, Msg: "ok"}, nil
}
