package com.search.supersearch.controller;

import cn.hutool.core.bean.BeanUtil;
import com.search.supersearch.common.R;
import com.search.supersearch.domain.IamDataCategory;
import com.search.supersearch.model.vo.IamDataCategoryVO;
import com.search.supersearch.service.mysql.IamDataCategoryService;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
@Api(value = "菜单", tags = "菜单")
@Slf4j
public class DataCategoryController {
    @Resource
    private IamDataCategoryService iamDataCategoryService;
//    private Cache<String, List<IamDataCategoryVO>> cache = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.HOURS).maximumSize(10).build();

    @GetMapping("/dataCategory")
    @SneakyThrows
    public R<List<IamDataCategoryVO>> dataCategory() {
//        List<IamDataCategoryVO> o = cache.get("dataCategory", k -> {
        List<IamDataCategory> list = iamDataCategoryService.lambdaQuery().list();
        List<IamDataCategoryVO> result = list.stream()
                .filter(v -> v.getLevel() == 1)
                .sorted(Comparator.comparing(IamDataCategory::getSortNum))
                .map(v -> getIamDataCategoryVO(list, v))
                .collect(Collectors.toList());
//            cache.put("dataCategory", result);
//            return result;
//        });


        return R.data(result);
    }

    private IamDataCategoryVO getIamDataCategoryVO(List<IamDataCategory> list, IamDataCategory v) {
        IamDataCategoryVO vo = BeanUtil.copyProperties(v, IamDataCategoryVO.class);
        List<IamDataCategory> collect = list.stream().filter(v2 -> v2.getParentId().equals(v.getId())).sorted(Comparator.comparing(IamDataCategory::getSortNum)).collect(Collectors.toList());
        for (IamDataCategory iamDataCategory : collect) {
            getIamDataCategoryVO(list, iamDataCategory);
        }
        vo.setChildData(collect);
        return vo;
    }
}
