package com.xjrsoft.module.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.system.entity.DictionaryItem;
import com.xjrsoft.module.system.mapper.DictionarydetailMapper;
import com.xjrsoft.module.system.mapper.DictionaryitemMapper;
import com.xjrsoft.module.system.service.IDictionaryitemService;
import com.xjrsoft.module.system.vo.DictionaryDetailVo;
import com.xjrsoft.module.system.vo.DictionaryItemDetailTreeVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典项目 服务实现类
 * </p>
 *
 * @author tzx
 * @since 2022-03-17
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictionaryitemServiceImpl extends ServiceImpl<DictionaryitemMapper, DictionaryItem> implements IDictionaryitemService {

    private RedisUtil redisUtil;

    private DictionarydetailMapper dictionarydetailMapper;
    @Override
    public List<DictionaryItemDetailTreeVo> getTree() {

        List<DictionaryItem> itemList = list();
        List<DictionaryDetail> detailList = dictionarydetailMapper.selectList(null);

        List<DictionaryItemDetailTreeVo> result = new ArrayList<>();

        for (DictionaryItem dictionaryItem : itemList) {
            List<DictionaryDetail> child = detailList.stream().filter(x -> x.getItemId().equals(dictionaryItem.getId())).collect(Collectors.toList());
            DictionaryItemDetailTreeVo vo = BeanUtil.toBean(dictionaryItem, DictionaryItemDetailTreeVo.class);
            vo.setChildren(BeanUtil.copyToList(child, DictionaryDetailVo.class));
            result.add(vo);
        }

        return result;
    }

    @Async
    public void loadCaches() {
        log.info("XJRSOFT: 加载所有数据字典详情缓存开始");
        List<DictionaryItem> list = this.list();
        redisUtil.set(GlobalConstant.DIC_ITEM_CACHE_KEY, list);
        log.info("XJRSOFT: 加载所有数据字典详情缓存结束");
    }
}
