package com.loan.system.repository;

import com.loan.system.domain.dto.DocumentDTO;
import com.loan.system.domain.entity.DictBusinessType;
import com.loan.system.domain.entity.Document;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

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

    List<Document> findByCaseId(Long caseId);

    @Query("select d from Document d where d.id = ?1")
    Document findByDocumentId(Long signId);

    @Transactional
    @Modifying
    @Query("UPDATE Document d SET " +
            "d.ownerId = CASE WHEN :#{#document.ownerId} IS NOT NULL THEN :#{#document.ownerId} ELSE d.ownerId END, " +
            "d.docType = CASE WHEN :#{#document.docType} IS NOT NULL THEN :#{#document.docType} ELSE d.docType END, " +
            "d.filePath = CASE WHEN :#{#document.filePath} IS NOT NULL THEN :#{#document.filePath} ELSE d.filePath END, " +
            "d.fileName = CASE WHEN :#{#document.fileName} IS NOT NULL THEN :#{#document.fileName} ELSE d.fileName END, " +
            "d.fileSize = CASE WHEN :#{#document.fileSize} IS NOT NULL THEN :#{#document.fileSize} ELSE d.fileSize END ," +
            "d.updateTime = CASE WHEN :#{#document.updateTime} IS NOT NULL THEN :#{#document.updateTime} ELSE d.updateTime END " +
            "WHERE d.caseId = :caseId AND d.dictType = :dictType")
    void updateByCaseIdAndDictType(Long caseId, String dictType, Document document);

    @Transactional
    @Modifying
    @Query("DELETE FROM Document d WHERE d.caseId = :caseId AND d.dictType = :fileType")
    void deleteFileByCaseIdAndDictType(Long caseId, String fileType);
}