package com.loan.system.repository;

import com.loan.system.domain.dto.CustomersOtherDTO;
import com.loan.system.domain.entity.Customer;
import com.loan.system.domain.entity.CustomersOther;
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.Collection;
import java.util.List;

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

    @Query("select c from CustomersOther c where c.idNumber = ?1 AND c.isDelete = ?2")
    CustomersOther findByIdNumberAndIsDelete(String idNumber, boolean isDelete);

    @Transactional
    @Modifying
    @Query("UPDATE CustomersOther c SET " +
           "c.name = CASE WHEN :#{#customersOtherDTO.name} IS NOT NULL THEN :#{#customersOtherDTO.name} ELSE c.name END, " +
           "c.idNumber = CASE WHEN :#{#customersOtherDTO.idNumber} IS NOT NULL THEN :#{#customersOtherDTO.idNumber} ELSE c.idNumber END, " +
           "c.mobile = CASE WHEN :#{#customersOtherDTO.mobile} IS NOT NULL THEN :#{#customersOtherDTO.mobile} ELSE c.mobile END " +
           "WHERE c.id = :id")
    void updateCustomerById(@Param("customersOtherDTO") CustomersOtherDTO customersOtherDTO, @Param("id") Long id);

    @Query("select c from CustomersOther c where c.id = ?1 and c.isDelete = ?2")
    CustomersOther findByCustomerOtherId(Long Id, boolean isDelete);

    List<CustomersOther> findByCaseIdAndIsDelete(Long caseId, boolean isDelete);

    @Transactional
    @Modifying
    @Query("DELETE FROM CustomersOther c WHERE c.caseId = ?1")
    void deleteAllByCaseId(Long caseId);
}