package com.zcloud.service.system.impl;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Route;
import com.zcloud.mapper.datasource.system.RouteMapper;
import com.zcloud.service.system.RouteService;
import com.zcloud.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 说明：菜单服务接口实现类
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Service
@Transactional //开启事物
public class RouteServiceImpl implements RouteService {

    @Autowired
    private RouteMapper routeMapper;

    /**
     * 新增菜单
     *
     * @param pd
     * @throws Exception
     */
    // @CacheEvict(value="routecache", allEntries=true)
    public void add(PageData pd) throws Exception {
        routeMapper.add(pd);
    }

    /**
     * 保存修改菜单
     *
     * @param pd
     * @throws Exception
     */
//	@CacheEvict(value="routecache", allEntries=true)
    public void edit(PageData pd) throws Exception {
        routeMapper.edit(pd);
    }

    /**
     * 通过菜单ID获取数据
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findById(PageData pd) throws Exception {
        return routeMapper.findById(pd);
    }

    /**
     * 获取最大的菜单ID
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData findMaxId(PageData pd) throws Exception {
        return routeMapper.findMaxId(pd);
    }

    /**
     * 通过ID获取其子一级菜单
     *
     * @param parentId
     * @return
     * @throws Exception
     */
    @Override
//    @Cacheable(key = "'route-'+#parentId", value = "routecache")
    public List<Route> listSubRouteByParentId(String parentId) throws Exception {
        return routeMapper.listSubRouteByParentId(parentId);
    }

    /**
     * 通过ID获取其子一级菜单
     *
     * @param parentId
     * @return
     * @throws Exception
     */
    @Override
//    @Cacheable(key = "'route-'+#parentId", value = "routecache")
    public List<PageData> listRouteByParentId(String parentId) throws Exception {
        return routeMapper.listRouteByParentId(parentId);
    }

    /**
     * 删除菜单
     *
     * @param ROUTE_ID
     * @throws Exception
     */
//	@CacheEvict(value="routecache", allEntries=true)
    public void delete(String ROUTE_ID) throws Exception {
        routeMapper.delete(ROUTE_ID);
    }

    /**
     * 保存菜单图标
     *
     * @param pd
     * @throws Exception
     */
    @CacheEvict(value = "routecache", allEntries = true)
    public void editicon(PageData pd) throws Exception {
        routeMapper.editicon(pd);
    }

    @Override
    public List<PageData> treeAll(PageData router) throws Exception {
        List<PageData> routeList = this.listRouteByParentId(router.get("ROUTE_ID").toString());
        if ("1".equals(router.getString("removePath"))) {
            routeList.removeIf((item) -> Tools.isEmpty(item.getString("path"))); //去掉path为空的项
        }
        for (PageData route : routeList) {
            if ("0".equals(route.getString("ROUTE_ID"))) {
                route.put("PARENT_NAME", "（无）");
            } else {
                JSONObject meta = JSONObject.parseObject(route.getString("meta"));
                route.put("PARENT_NAME", meta.getString("title"));
            }
            route.put("meta", JSONObject.parse(route.getString("meta")));
            if ("1".equals(router.getString("removePath"))) {
                route.put("removePath", router.getString("removePath"));
            }
            route.put("children", this.treeAll(route));
        }
        return routeList;
    }


//    @Override
//    public List<PageData> treeAll(PageData pd) throws Exception {
//        List<PageData> list = new ArrayList<PageData>();
//        List<PageData> routeList = routeMapper.listAll(pd);
//        Map<String, PageData> map = new HashMap<String, PageData>();
//        for (PageData r : routeList) {
//            r.put("meta", JSONObject.parse(r.getString("meta")));
//            map.put(r.getString("ROUTE_ID"), r);
//        }
//
//        Iterator<Map.Entry<String, PageData>> it = map.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<String, PageData> entry = it.next();
//            PageData root = entry.getValue();
//            if ("0".equals(root.getString("PARENT_ID"))) {
//                root.put("PARENT_NAME", "（无）");
//                list.add(entry.getValue());
//                it.remove();//使用迭代器的remove()方法删除元素
//            }
//        }
//        TreeAppendChildren(map, list);
//        return list;
//    }

    @Override
    public List<PageData> listAll(PageData pd) throws Exception {
        return routeMapper.listAll(pd);
    }

    @Override
    public List<Route> listSubRouteAll() throws Exception {
        return routeMapper.listSubRouteAll();
    }

    /**
     * 获取所有菜单并填充每个菜单的子菜单列表(系统菜单列表)(递归处理)
     *
     * @param MENU_ID
     * @return
     * @throws Exception
     */
    @Override
    public List<Route> listAllMenuJur(String MENU_ID) throws Exception {
        //数据库递归查询
       /* List<Route> routeList = this.listSubRouteByParentId(MENU_ID);
        for (Route route : routeList) {
            route.setChildren(this.listAllMenuJur(route.getROUTE_ID()));
            route.setTarget("treeFrame");
        }
        return routeList;*/

        //逻辑递归数据
        List<Route> routeList = this.listSubRouteAll();//获取所有级别菜单
        List<Route> routeListMenu = new ArrayList<>();//获取所有级别菜单
        //一级菜单
        for (Route route : routeList) {
            if("0".equals(route.getPARENT_ID())){
                routeListMenu.add(route);
                route.setTarget("treeFrame");
            }
        }
        //一级菜单增加子菜单
        for (Route routeMenu : routeListMenu) {
            List<Route> childList = TreeChildren(routeMenu.getROUTE_ID(),routeList);
            routeMenu.setChildren(childList);
        }
        return routeListMenu;
    }

    /**
     * 获取子菜单
     * @param parentId
     * @param routeList
     * @return 每个菜单的子菜单
     */
    private List<Route> TreeChildren(String parentId, List<Route> routeList) {
        List<Route> childList = new ArrayList<>();
        for (Route route : routeList) {
            //遍历所有节点，与上级传过来的父节点id比较
            if(parentId.equals(route.getPARENT_ID())){
                childList.add(route);
            }
        }
        //递归
        for (Route route : childList) {
            route.setChildren(TreeChildren(route.getROUTE_ID(),routeList));
            route.setTarget("treeFrame");
        }
        return childList;
    }


    private void TreeAppendChildren(Map<String, PageData> map, List<PageData> list) {
        if (!map.isEmpty()) {
            for (PageData parent : list) {
                List<PageData> children = new ArrayList<PageData>();
                Iterator<Map.Entry<String, PageData>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, PageData> entry = it.next();
                    PageData child = entry.getValue();
                    if (parent.getString("ROUTE_ID").equals(child.getString("PARENT_ID"))) {
                        child.put("PARENT_NAME", ((JSONObject) parent.get("meta")).getString("title"));
                        children.add(child);
                        it.remove();//使用迭代器的remove()方法删除元素
                    }
                }
                if (children.size() > 0) {
                    parent.put("children", children);
                    TreeAppendChildren(map, children);
                }
            }
        }
    }

//    private void TreeAppendChildren(Map<String, PageData> map, List<PageData> list) {
//        if (!map.isEmpty()) {
//            for (PageData parent : list) {
//                List<PageData> children = new ArrayList<PageData>();
//                Iterator<Map.Entry<String, PageData>> it = map.entrySet().iterator();
//                while (it.hasNext()) {
//                    Map.Entry<String, PageData> entry = it.next();
//                    PageData child = entry.getValue();
//                    if (parent.getString("ROUTE_ID").equals(child.getString("PARENT_ID"))) {
//                        child.put("PARENT_NAME", ((JSONObject) parent.get("meta")).getString("title"));
//                        children.add(child);
//                        it.remove();//使用迭代器的remove()方法删除元素
//                    }
//                }
//                if (children.size() > 0) {
//                    parent.put("children", children);
//                    TreeAppendChildren(map, children);
//                }
//            }
//        }
//    }
}
