package com.loan.system.repository;

import com.loan.system.domain.entity.LoanCase;
import com.loan.system.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author EdwinXu
 * @date 2020/9/2 - 15:35
 * @Description
 */
public interface LoanRepository extends JpaRepository<LoanCase,Long> {

    List<LoanCase> findByIsCompleteAndIsDelete(Boolean isComplete, boolean isDelete);

    @Transactional
    @Modifying
    @Query("UPDATE LoanCase l SET " +
           "l.customerId = CASE WHEN :#{#loanCase.customerId} IS NOT NULL THEN :#{#loanCase.customerId} ELSE l.customerId END, " +
           "l.businessType = CASE WHEN :#{#loanCase.businessType} IS NOT NULL THEN :#{#loanCase.businessType} ELSE l.businessType END, " +
           "l.businessAttrs = CASE WHEN :#{#loanCase.businessAttrs} IS NOT NULL THEN :#{#loanCase.businessAttrs} ELSE l.businessAttrs END, " +
           "l.channelName = CASE WHEN :#{#loanCase.channelName} IS NOT NULL THEN :#{#loanCase.channelName} ELSE l.channelName END, " +
           "l.recommenderId = CASE WHEN :#{#loanCase.recommenderId} IS NOT NULL THEN :#{#loanCase.recommenderId} ELSE l.recommenderId END, " +
           "l.totalLoanAmount = CASE WHEN :#{#loanCase.totalLoanAmount} IS NOT NULL THEN :#{#loanCase.totalLoanAmount} ELSE l.totalLoanAmount END, " +
           "l.isComplete = CASE WHEN :#{#loanCase.isComplete} IS NOT NULL THEN :#{#loanCase.isComplete} ELSE l.isComplete END, " +
           "l.updateTime = CASE WHEN :#{#loanCase.updateTime} IS NOT NULL THEN :#{#loanCase.updateTime} ELSE l.updateTime END " +
           "WHERE l.id = :caseId")
    void updateLoanCaseById(@Param("loanCase") LoanCase loanCase, @Param("caseId") Long caseId);

    @Query("SELECT lc FROM LoanCase lc LEFT JOIN FETCH lc.customer WHERE lc.id = :caseId AND lc.isDelete = :isDelete")
    LoanCase findLoanCaseById(@Param("caseId") Long caseId, @Param("isDelete") boolean isDelete);


    @Modifying
    @Transactional
    @Query("update LoanCase set updateTime = ?3 where id = ?1 and isDelete = ?2")
    void updateUpdatetimeByIdAndIsDeleted(Long id,boolean isDelete,String updateTime);

    @Modifying
    @Transactional
    @Query("UPDATE LoanCase SET updateTime = ?3, isDelete = ?2 WHERE id = ?1 AND isDelete = false")
    void logic_delete(Long id, boolean isDelete, String updateTime);
}