package com.gz.service.system.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.gz.common.DataGlobalVariable;
import com.gz.dto.system.MenuDTO;
import com.gz.mapper.system.MenuMapper;
import com.gz.service.system.MenuService;
import com.gz.utils.JwtUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单业务层
 * @author LiuchangLan
 * @date 2020/9/4 15:54
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public Integer insert(MenuDTO menuDTO) {
        // 创建人
        menuDTO.setCreated(JwtUtils.getCurrentUserJwtPayload().getId());
        // 执行入库
        return menuMapper.insertSelective(menuDTO);
    }

    @Override
    public Integer delete(Integer id) {
        return menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer update(MenuDTO menuDTO) {
        // 修改人
        menuDTO.setUpdated(JwtUtils.getCurrentUserJwtPayload().getId());
        // 修改时间
        menuDTO.setUpdateTime(DateUtil.now());
        // 执行入库
        return menuMapper.updateByPrimaryKeySelective(menuDTO);
    }

    @Override
    public List<MenuDTO> select() {
        return menuMapper.selectAll();
    }

    @Override
    public MenuDTO selectByPrimaryKey(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Tree<String>> getMenuTree() {
        List<MenuDTO> menuDTOS = selectByOrder();
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setIdKey("id");
        // 最大递归深度
        treeNodeConfig.setDeep(3);

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(menuDTOS, "-1", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getParentId().toString());
                    tree.setName(treeNode.getTitle());
                });
        return treeNodes;
    }

    @Override
    public List<MenuDTO> selectByOrder() {
        return menuMapper.getMenusOrder();
    }


}
