package com.izouma.nineth.repo.collection;

import com.izouma.nineth.domain.CollectionCategory;
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;
import java.util.Map;

/**
 * 藏品分类表
 * @author  ZouYuHong
 */
public interface CollectionCategoryRepo extends JpaRepository<CollectionCategory, Long>, JpaSpecificationExecutor<CollectionCategory> {

    /**
     * 根据分类名查找
     * @param name 分类名称
     * @return 结果
     */
    CollectionCategory findByNameAndProjectId(String name,Integer projectId);

    @Query(value = "select category  from collection_info ci group by ci.category ", nativeQuery = true)
    List<String> getTypes();


    /**
     * 获取一个目录下全部藏品种类
     * @param categoryId 目录ID
     * @return 藏品
     */
    @Query(value = "select\n" +
            "\tci.name,\n" +
            "\tANY_VALUE(ci.id) as id\n" +
            "from\n" +
            "\tcollection_info ci\n" +
            "where\n" +
            "\tci.collection_category_id = ?1 \n" +
            "\tand source = 'OFFICIAL'\n" +
            "group by\n" +
            "\tci.name", nativeQuery = true)
    List<Map<String,Object>> allCollection(Long categoryId);


    /**
     * 根据父Id 查找 父ID下的目录
     * @param parentId 父级ID
     * @return 目录
     */
    List<CollectionCategory> findByParentIdAndDelFalse(Long parentId);

    @Query(value = "select t from CollectionCategory t where t.projectId = ?1 and t.del = false and t.parentId = 0 order by sort")
    List<CollectionCategory> findFirstCategory(int projectId);

    @Query("update CollectionCategory t set t.del = true where t.id = ?1 ")
    @Modifying
    @Transactional
    void softDelete(Long id);

    @Query("select new CollectionCategory(t.id,t.parentId) from CollectionCategory t where t.del = false and t.id = ?1 ")
    CollectionCategory getByParentId(Long parentId);
}