package com.kexue.skills.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kexue.skills.entity.SysDict;
import com.kexue.skills.entity.dto.SysDictDto;
import com.kexue.skills.mapper.SysDictMapper;
import com.kexue.skills.service.SysDictService;
import org.springframework.stereotype.Service;

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

/**
 * 系统字典表(SysDict)表服务实现类
 *
 * @author 王志维
 * @since 2025-02-21 23:01:48
 */
@Service("sysDictService")
public class SysDictServiceImpl implements SysDictService {

    @Resource
    private SysDictMapper sysDictMapper;

    /**
     * 分页查询数据
     *
     * @param queryDto
     * @return 数据分页列表
     */
    @Override
    public PageInfo<SysDict> getPageList(SysDictDto queryDto) {
        int pageNum = queryDto.getPageNum()==null?PAGENUM:queryDto.getPageNum();
        int pageSize = queryDto.getPageSize()==null? PAGESIZE :queryDto.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<SysDict> dataList = sysDictMapper.getPageList(queryDto);
        return new PageInfo<>(dataList);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysDict queryById(Long id) {
        return sysDictMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<SysDict> queryAllByLimit(int offset, int limit) {
        return sysDictMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param sysDict 实例对象
     * @return 实例对象
     */
    @Override
    public SysDict insert(SysDict sysDict) {
        sysDictMapper.insert(sysDict);
        return sysDict;
    }

    /**
     * 修改数据
     *
     * @param sysDict 实例对象
     * @return 实例对象
     */
    @Override
    public SysDict update(SysDict sysDict) {
        sysDictMapper.update(sysDict);
        return queryById(sysDict.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return sysDictMapper.deleteById(id) > 0;
    }

    @Override
    public List<SysDict> getAllDictCode() {
        return sysDictMapper.getPageList(null);
    }

    @Override
    public Map<String,List<SysDict>> getAllDictMap(){
        List<SysDict> allDictList = sysDictMapper.getPageList(null);
        //将字典按照dictCode进行分组
        Map<String, List<SysDict>> allDictMap = allDictList.stream().collect(Collectors.groupingBy(sysDict -> sysDict.getDictCode()));
        return allDictMap;
    }

    @Override
    public List<SysDict> getListByDictCode(String dictCode) {
        return sysDictMapper.getDictListByCode(dictCode);
    }
}
