package com.heketai.website.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.heketai.website.common.exception.BussinessException;
import com.heketai.website.entity.dto.NavigationTree;
import com.heketai.website.entity.Navigation;
import com.heketai.website.mapper.NavigationMapper;
import com.heketai.website.service.INavigationService;
import com.heketai.website.common.utils.ListUtils;
import com.heketai.website.common.utils.TreeUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 导航表 服务实现类
 * </p>
 *
 * @author xjl
 * @since 2019-11-18
 */
@Service
public class NavigationServiceImpl extends ServiceImpl<NavigationMapper, Navigation> implements INavigationService {

    @Override
    public void insertInfo(Navigation navigation) {
        if (Objects.nonNull(navigation.getId())) {
            Navigation parentNavigation = this.selectOne(
                    new EntityWrapper<Navigation>().eq("parent_id", navigation.getParentId()));
            if (Objects.isNull(parentNavigation)) {
                throw new BussinessException("parentId不存在");
            }
        }
        this.insert(navigation);
    }

    @Override
    public void deleteNavigationById(Integer id) {
        List<Navigation> parentNavigations = this.selectList(
                new EntityWrapper<Navigation>().eq("parent_id", id));
        if (!StringUtils.isEmpty(parentNavigations)) {
            throw new BussinessException("下级有数据不能删除");
        }
        this.deleteById(id);
    }

    @Override
    public List<NavigationTree> findTrees() {
        List<Navigation> navigationList = this.selectList(new EntityWrapper<>());
        List<NavigationTree> navigationTreeList= ListUtils.copyList(navigationList, NavigationTree.class);
        //0为根节电
        return TreeUtil.buildByRecursive(navigationTreeList, 0);
    }
}
