package com.ff.weijinxiao.repository;


import com.ff.weijinxiao.domain.AccountBook;
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.util.List;

public interface AccountBookRepository extends JpaRepository<AccountBook, Integer>, JpaSpecificationExecutor<AccountBook> {

    @Transactional
    @Modifying
    @Query(value = "update tb_account_book set is_default = 0 where uid=:uid and id !=:id ", nativeQuery = true)
    void setNoneDefaultByUidAndId(String uid, Integer id);


    @Query(value = "select * from  tb_account_book  where uid=:uid and is_default = 1 limit 1", nativeQuery = true)
    AccountBook getDefaultAccountBook(String uid);


    @Query(value = "select ab.* from  tb_account_book ab left join tb_book_user_relation bur on bur.book_id = ab.id where (ab.uid=:uid or bur.uid=:uid) and ab.name like CONCAT('%',:name,'%') and ab.isDelete=0 GROUP BY ab.id", nativeQuery = true)
    List<AccountBook> searchAccountBooks(String uid, String name);

    @Query(value = "select ab.* from  tb_account_book ab left join tb_book_user_relation bur on bur.book_id = ab.id where (ab.uid=:uid or bur.uid=:uid) and ab.isDelete=0 GROUP BY ab.id", nativeQuery = true)
    List<AccountBook> searchAccountBooks(String uid);
}
