package com.izouma.dingdong.repo;

import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.enums.MerchantStatus;
import com.izouma.dingdong.enums.OrderStatus;
import com.izouma.dingdong.enums.RiderStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

public interface OrderInfoRepo extends JpaRepository<OrderInfo, Long>, JpaSpecificationExecutor<OrderInfo> {

    @Query("update OrderInfo t set t.enabled = false where t.id = ?1")
    @Modifying
    @Transactional
    void deleteById(Long id);

    //按商家查找
    List<OrderInfo> findAllByMerchantId(Long merchantId);

    //按用户查找
    List<OrderInfo> findAllByUserId(Long userId);

    //按骑手查找
    List<OrderInfo> findAllByRiderId(Long riderId);

    //按骑手查找状态不为完成的订单
    List<OrderInfo> findAllByRiderIdAndRiderStatusIsNot(Long riderId, RiderStatus riderStatus);

    //按商家和用户查找订单，判断是不是第一次购买
    List<OrderInfo> findAllByUserIdAndMerchantId(Long userId, Long merchantId);

    @Query("select sum (t.realAmount) from OrderInfo t where t.userId = ?1")
    BigDecimal sumRealAmountByUserId(Long userId);

    @Query("update OrderInfo t set t.enabled = false where t.merchantId = ?1")
    @Modifying
    @Transactional
    void deleteAllByMerchantId(Long merchantId);

    //查找所有五分钟内骑手未接单的订单
    List<OrderInfo> findAllByStatusAndOrderTimeAfterAndMerchantStatus(OrderStatus status, LocalDateTime time, MerchantStatus merchantStatus);

    //骑手未接单的订单
    List<OrderInfo> findAllByStatusAndMerchantStatus(OrderStatus status, MerchantStatus merchantStatus);

    //按商家和时间内的订单泪飙
    List<OrderInfo> findAllByMerchantIdAndOrderTimeAfter(Long merchantId, LocalDateTime dateTime);
}