package io.renren.modules.levelManage.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.datasource.annotation.DataSource;
import io.renren.modules.levelManage.dao.LevelDao;
import io.renren.modules.levelManage.entity.LevelEntity;
import io.renren.modules.levelManage.service.LevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("levelService")
@DataSource("heBing")
public class LevelServiceImpl extends ServiceImpl<LevelDao, LevelEntity> implements LevelService {

    @Autowired
    LevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<LevelEntity> page = this.page(
                new Query<LevelEntity>().getPage(params),
                new QueryWrapper<LevelEntity>()
        );

        return new PageUtils(page);
    }

    public List<LevelEntity> selectByName(Integer page, Integer size, String name)
    {
        if (page != null && size != null){
            page = (page - 1) * size;
        }
        return levelDao.selectByName(page,size,name);
    }

    public Integer getCountByName(String name)
    {
        return levelDao.getCountByName(name);
    }

    public List<LevelEntity> getSonLevel(Long id)
    {
        return levelDao.getSonLevel(id);
    }

    public Integer queryEnabledCount() {return levelDao.queryEnabledCount();}


    public List<LevelEntity> getAllParentById(Long id)
    {
        List<LevelEntity> allLevel=this.list();
        Map<Long,Long> parentMap=new HashMap<>();
        List<Long> ids=new ArrayList<>();
        for(LevelEntity level:allLevel)
        {
            parentMap.put(level.getId(), level.getParentId());
        }
        while (id!=0)
        {
            ids.add(id);
            id=parentMap.get(id);
        }
        return this.listByIds(ids);
    }


    public List<LevelEntity> getEnabledLevels()
    {
        return levelDao.getEnabledLevels();
    }

    public Integer queryEnabledCountWithParentId(Long id)
    {
        return levelDao.queryEnabledCountWithParentId(id);
    }

    public LevelEntity getEnabledSon(Long id)
    {
        return levelDao.getEnabledSon(id);
    }

    public List<LevelEntity> getEnabledLevelByProject(List<Long> ids){
        return levelDao.getEnabledLevelByProject(ids);
    }

    public List<LevelEntity> getRootLevel(Long id){
        QueryWrapper<LevelEntity> levelWrapper=new QueryWrapper<>();
        levelWrapper.eq("project_id",id)
                .eq("parent_id",0)
                .eq("enabled",1);
        return levelDao.selectList(levelWrapper);
    }
}