package com.cool.store.service.dict.impl;

import cn.hutool.core.collection.CollStreamUtil;
import com.cool.store.dao.dict.SysDictColumnDAO;
import com.cool.store.dao.dict.SysDictGroupDAO;
import com.cool.store.dao.dict.SysDictTableDAO;
import com.cool.store.entity.dict.SysDictGroupDO;
import com.cool.store.entity.dict.SysDictTableDO;
import com.cool.store.request.dict.DictGroupQueryRequest;
import com.cool.store.service.dict.DictGroupService;
import com.cool.store.utils.BeanUtil;
import com.cool.store.vo.dict.DictGroupVO;
import com.cool.store.vo.dict.DictTableVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典分组 实现类
 * </p>
 *
 * @author wangff
 * @since 2025/2/20
 */
@Service
@RequiredArgsConstructor
public class DictGroupServiceImpl implements DictGroupService {
    private final SysDictGroupDAO groupDAO;
    private final SysDictTableDAO tableDAO;
    private final SysDictColumnDAO columnDAO;

    @Override
    public DictGroupVO getById(Long id) {
        SysDictGroupDO group = groupDAO.getById(id);
        return BeanUtil.toBean(group, DictGroupVO.class);
    }


    @Override
    public List<DictGroupVO> getList(DictGroupQueryRequest queryDTO) {
        List<SysDictGroupDO> list = groupDAO.getList(queryDTO);
        List<DictGroupVO> result = BeanUtil.toList(list, DictGroupVO.class);
        // 查询字典表
        List<Long> groupIds = CollStreamUtil.toList(result, DictGroupVO::getId);
        List<SysDictTableDO> tableList = tableDAO.getListByGroupIds(groupIds, queryDTO.getDictTableOpenStatus());
        List<DictTableVO> tableVOList = BeanUtil.toList(tableList, DictTableVO.class);
        // 查询字典项数量
        List<Long> tableIds = CollStreamUtil.toList(tableVOList, DictTableVO::getId);
        Map<Long, Integer> columnNumMap = columnDAO.getColumnNumMapByTableIds(tableIds);

        tableVOList.forEach(v -> v.setColumnNum(columnNumMap.getOrDefault(v.getId(), 0)));

        Map<Long, List<DictTableVO>> tableMap = CollStreamUtil.groupByKey(tableVOList, DictTableVO::getDictGroupId);
        result.forEach(v -> v.setTableList(tableMap.getOrDefault(v.getId(), Collections.emptyList())));
        return result;
    }
}
