package com.izouma.nineth.service.collection;

import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.domain.CollectionCategory;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.collection.CollectionCategoryRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 藏品分类表
 * @author ZouYuHong
 */
@Slf4j
@Service
@AllArgsConstructor
public class CollectionCategoryService {
    private CollectionCategoryRepo collectionCategoryRepo;

    public Page<CollectionCategory> all(PageQuery pageQuery) {
        return collectionCategoryRepo.findAll(JpaUtils.toSpecification(pageQuery, CollectionCategory.class), JpaUtils.toPageRequest(pageQuery));
    }



    public CollectionCategory saveOrUpdate(CollectionCategory category) {
        if (category.getParentId() == null) {
            category.setParentId(0L);
        }
        return collectionCategoryRepo.save(category);
    }



    public CollectionCategory detail(Long id) {
        return collectionCategoryRepo.findById(id).orElseThrow(new BusinessException("查询的分类不存在"));
    }
    /**
     * 获取一个目录下全部藏品种类
     * @param categoryId 目录ID
     * @return 藏品
     */
    public List<Collection> allCollection(Long categoryId) {
        Object list= collectionCategoryRepo.allCollection(categoryId);
        return (List<Collection>) list;
    }

    public List<CollectionCategory> categories(int projectId) {
        return collectionCategoryRepo.findFirstCategory(projectId);
    }

    public List<CollectionCategory> batchUpdate(List<CollectionCategory> categories) {
        this.update(categories);
        return categories;
    }
    public void update(List<CollectionCategory> categories){
        if (!categories.isEmpty()){
            for (int i = 0; i < categories.size(); i++) {
                CollectionCategory collectionCategory = categories.get(i);
                collectionCategory.setSort(i);
                if (collectionCategory.getChildren()!=null){
                    this.update(collectionCategory.getChildren());
                }
                collectionCategoryRepo.save(collectionCategory);
            }
        }
    }

    public void softDelete(Long id) {
        collectionCategoryRepo.softDelete(id);
    }

    public CollectionCategory getByParentId(Long parentId) {
        return collectionCategoryRepo.getByParentId(parentId);
    }

    public CollectionCategory getById(Long categoryId) {
        return collectionCategoryRepo.findById(categoryId).orElseThrow(new BusinessException("您选择的目录不存在"));
    }
}
