package com.yn.bftl.thirdparty.common.repository;

import com.yn.bftl.common.modules.order.entity.Shipping;
import com.yn.bftl.common.modules.order.enums.ShippingType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 发货表Repository
 *
 * @author chendehuihuo
 * @date 2021/11/22
 **/
@Repository
public interface ShippingRepository extends JpaRepository<Shipping, Long> {

    /**
     * 修改发货单分账标记
     *
     * @param signTime
     */
    @Transactional
    @Modifying
    @Query(nativeQuery = true, value = "update order_shipping m set m.separate_flag = 1 where m.is_separate_accounts = 0 and m.separate_flag = 0 and m.shipping_type = 'NORMAL' and m.receive_status = 'RECEIVED' and m.sign_time < ?1 " +
            " and orders in (select id from order_order o where o.seller_company = ?2)")
    void updateSeparateFlagBySignTime(LocalDateTime signTime, Long sellerCompanyId);

    @Transactional
    @Modifying
    @Query(nativeQuery = true, value = "update order_shipping m set m.is_separate_accounts = 1 where m.id = ?1")
    void updateIsSeparateAccountsById(Long id);

    List<Shipping> findAllByShippingTypeAndIsSeparateAccountsAndSeparateFlagAndOrdersSellerCompanyId(ShippingType shippingType, Boolean isSeparateAccounts, Boolean separateFlag, Long companyId);

    Shipping findFirstByShippingSn(String shippingSn);

}
