package com.zhgd.xmgl.modules.basicdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhgd.jeecg.common.execption.OpenAlertException;
import com.zhgd.jeecg.common.mybatis.EntityMap;
import com.zhgd.xmgl.modules.basicdata.dto.MenuTreeDto;
import com.zhgd.xmgl.modules.basicdata.entity.*;
import com.zhgd.xmgl.modules.basicdata.mapper.BaseActionMapper;
import com.zhgd.xmgl.modules.basicdata.mapper.BaseMenuMapper;
import com.zhgd.xmgl.modules.basicdata.service.IBaseMenuService;
import com.zhgd.xmgl.modules.basicdata.service.IBaseModuleService;
import com.zhgd.xmgl.modules.basicdata.service.ISystemRoleMenuService;
import com.zhgd.xmgl.modules.basicdata.service.ISystemUserRoleService;
import com.zhgd.xmgl.security.SecurityUser;
import com.zhgd.xmgl.security.SecurityUtil;
import com.zhgd.xmgl.util.ListUtils;
import com.zhgd.xmgl.util.MessageUtil;
import com.zhgd.xmgl.util.TreeUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 系统菜单
 * @author： pds
 * @date：   2020-10-12
 * @version： V1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BaseMenuServiceImpl extends ServiceImpl<BaseMenuMapper, BaseMenu> implements IBaseMenuService {
    @Autowired
    private BaseMenuMapper baseMenuMapper;
    @Autowired
    private BaseActionMapper baseActionMapper;
    @Autowired
    private IBaseModuleService baseModuleService;
    @Autowired
    private ISystemUserRoleService systemUserRoleService;
    @Autowired
    private ISystemRoleMenuService systemRoleMenuService;
//    @Autowired
//    private IBaseAuthorityService baseAuthorityService;
//    @Autowired
//    private CompanyConfigMapper companyConfigMapper;

    @Override
    public List<BaseMenu> selectBaseMenuList(Map<String, Object> map) {
        return baseMenuMapper.selectBaseMenuList(map);
    }

    @Override
    public JSONArray selectGroupList(Map<String, Object> map) {
        List<BaseMenu> list=baseMenuMapper.selectBaseMenuList(map);
        JSONArray result = ListUtils.listToTree(JSONArray.parseArray(JSON.toJSONString(list)),"menuId","parentId","children");
        return result;
    }

    @Override
    public List<MenuTreeDto> treeMenu(Integer type) {
        // 查询当前账号所属政务下的模块
        List<BaseModule> baseModules = baseModuleService.queryBySelf();
        if (baseModules.size() == 0) {
            return null;
        }
        List<MenuTreeDto> menuList = TreeUtil.formatModule(baseModules);
        // 查询相对应的菜单
        List<BaseMenu> baseMenus = baseMenuMapper.selectList(Wrappers.<BaseMenu>lambdaQuery().in(BaseMenu::getModuleId,
                baseModules.stream().map(m -> m.getModuleId()).collect(Collectors.toList())));
        menuList.addAll(TreeUtil.formatMenu(baseMenus));
        // 查询相对应的菜单
        List<BaseAction> baseAction = baseActionMapper.selectList(Wrappers.<BaseAction>lambdaQuery().in(BaseAction::getMenuId,
                baseMenus.stream().map(m -> m.getMenuId()).collect(Collectors.toList())));
        menuList.addAll(TreeUtil.formatAction(baseAction));
        return TreeUtil.build(menuList, type, 0L, 1);
    }

    @Override
    public List<MenuTreeDto> myTreeMenu(Long moduleId) {
        // 查询当前账号角色下的菜单,管理员账号默认全部菜单
        SecurityUser user = SecurityUtil.getUser();
        List<BaseMenu> baseMenus = new ArrayList<>();
        if (user.isManager()) {
            // 查询相对应的菜单
            baseMenus = baseMenuMapper.selectList(Wrappers.<BaseMenu>lambdaQuery().in(BaseMenu::getModuleId, moduleId));
        } else {
            List<Long> roleIds = systemUserRoleService.list(Wrappers.<SystemUserRole>lambdaQuery()
                    .eq(SystemUserRole::getUserId, user.getUserId())).stream().map(r -> r.getRoleId()).collect(Collectors.toList());
            List<Long> menuIds = systemRoleMenuService.list(Wrappers.<SystemRoleMenu>lambdaQuery()
                    .in(SystemRoleMenu::getRoleId, roleIds).eq(SystemRoleMenu::getModuleId, moduleId)
                    ).stream().map(r -> r.getMenuId()).collect(Collectors.toList());
            baseMenus = baseMenuMapper.selectList(Wrappers.<BaseMenu>lambdaQuery().in(BaseMenu::getModuleId, menuIds));
        }
        if (baseMenus.size() == 0) {
            return null;
        }
        // 查询相对应的菜单
        List<MenuTreeDto> menuList = TreeUtil.formatMenu(baseMenus);
        return TreeUtil.build(menuList, 1, moduleId, 2);
    }

    @Override
    public Set<Long> roleMenu(String roleId) {
        Set<Long> ids = new HashSet<>();
        // 查询角色下的菜单
        List<SystemRoleMenu> systemRoleMenus = systemRoleMenuService.list(Wrappers.<SystemRoleMenu>lambdaQuery()
                    .eq(SystemRoleMenu::getRoleId, roleId));
        for (SystemRoleMenu systemRoleMenu : systemRoleMenus) {
            ids.add(systemRoleMenu.getModuleId());
            ids.add(systemRoleMenu.getMenuId());
            ids.add(systemRoleMenu.getActionId());
        }
        ids.remove(null);
        return ids;
    }

    @Override
    public Map<String, Object> getProjectModuleAndMenu(Map<String, Object> map) {
        map.put("styleType",getStyleType(MapUtils.getString(map,"projectSn")));
        List<EntityMap> menuList=baseMenuMapper.getProjectBaseMenuList(map);
//        List<BaseModule> moduleList=baseModuleMapper.getProjectModuleList(map);
        Map<String, Object> data=new HashMap<>();
        data.put("menuList",menuList);
//        data.put("moduleList",moduleList);
        return data;
    }

    @Override
    public List<EntityMap> getProjectBaseMenuList(Map<String, Object> map) {
        return baseMenuMapper.getProjectBaseMenuList(map);
    }

    @Override
    public List<EntityMap> getProjectUserMenuList(Map<String, Object> param) {
        return baseMenuMapper.getProjectUserMenuList(param);
    }

    @Override
    public List<EntityMap> selectHeadquartersMenuList(Map<String, Object> param) {
        return baseMenuMapper.selectHeadquartersMenuList(param);
    }

    @Override
    public List<EntityMap> selectComapnyUserMenuList(Map<String, Object> param) {
        return baseMenuMapper.selectComapnyUserMenuList(param);
    }

    @Override
    public List<BaseModule> getProjectModuleGroupMenuList(Map<String, Object> map) {
        map.put("styleType",getStyleType(MapUtils.getString(map,"projectSn")));
        List<EntityMap> menuList=baseMenuMapper.getProjectBaseMenuList(map);
        List<EntityMap> actionList=baseActionMapper.getProjectBaseActionList(map);
        menuList=groupMenu(menuList,actionList);
//        List<BaseModule> moduleList=baseModuleMapper.getProjectModuleList(map);
        List<BaseModule> moduleList = new ArrayList<>();
        if(menuList!=null&&menuList.size()>0){
            for (BaseModule module:moduleList){
                List<EntityMap> tempList=new ArrayList<>();
                for (EntityMap menu:menuList){
                    if(MapUtils.getString(menu,"moduleId").equals(String.valueOf(module.getModuleId()))){
                        tempList.add(menu);
                    }
                }
                module.setMenuList(tempList);
            }
        }
        return moduleList;
    }

    @Override
    public List<EntityMap> groupMenu(List<EntityMap> list, List<EntityMap> actionList){
        List<EntityMap> tempList=new ArrayList<>();
        List<EntityMap> childList=new ArrayList<>();
        if(list!=null&&list.size()>0){
            for (EntityMap menu:list){
                if("0".equals(MapUtils.getString(menu,"parentId"))){
                    tempList.add(menu);
                }else{
                    childList.add(menu);
                }
            }
            tempList=groupList(tempList,childList,actionList);
        }
        return tempList;
    }

   /* @Override
    public Map<String,Object> getDefaultProjectMenu(){
        Map<String,Object> data=new HashMap<>();
        Map<String,Object> param=new HashMap<>();
        param.put("headquartersSn","-1");
        List<BaseModule> moduleList=baseModuleMapper.getCompanyModuleList(param);
        List<EntityMap> menuList=baseMenuMapper.selectHeadquartersMenuList(param);
        List<EntityMap> actionList=baseActionMapper.getHeadquartersActionList(param);
        menuList=groupMenu(menuList,actionList);
        moduleList=groupModuleMenu(moduleList,menuList);
        data.put("moduleList",moduleList);
        data.put("menuList",menuList);
        return data;
    }*/

    @Override
    public void saveBaseMenu(BaseMenu baseMenu) {
        if (baseMenu.getPriority() == null) {
            baseMenu.setPriority(0);
        }
        if (baseMenu.getStatus() == null) {
            baseMenu.setStatus(1);
        }
        baseMenuMapper.insert(baseMenu);
        // 同步权限表里的信息
      //  baseAuthorityService.saveOrUpdateAuthority(baseMenu.getMenuId(), "menu");
    }

    @Override
    public void editBaseMenu(BaseMenu baseMenu) {
        BaseMenu saved = baseMenuMapper.selectById(baseMenu.getMenuId());
        if (saved == null) {
            throw new OpenAlertException(MessageUtil.get("notFindErr"));
        }
        if (baseMenu.getPriority() == null) {
            baseMenu.setPriority(0);
        }
        baseMenuMapper.updateById(baseMenu);
        // 同步权限表里的信息
//        baseAuthorityService.saveOrUpdateAuthority(baseMenu.getMenuId(), "menu");

    }

    @Override
    public boolean delInfo(Long menuId) {
        baseActionMapper.delete(Wrappers.<BaseAction>lambdaQuery().eq(BaseAction::getMenuId, menuId));
        return this.removeById(menuId);
    }

    private List<BaseModule> groupModuleMenu(List<BaseModule> moduleList, List<EntityMap> menuList){
        if(menuList!=null&&menuList.size()>0){
            for (BaseModule module:moduleList){
                List<EntityMap> tempList=new ArrayList<>();
                for (EntityMap menu:menuList){
                    if(MapUtils.getString(menu,"moduleId").equals(String.valueOf(module.getModuleId()))){
                        tempList.add(menu);
                    }
                }
                module.setMenuList(tempList);
            }
        }
        return moduleList;
    }

    private List<EntityMap> groupList(List<EntityMap> list, List<EntityMap> childList, List<EntityMap> actionList){
        for(EntityMap menu:list){
            List<EntityMap> tempList=new ArrayList<>();
            List<EntityMap> List2=new ArrayList<>();
            for(EntityMap childMenu:childList){
                if(MapUtils.getString(menu,"menuId").equals(MapUtils.getString(childMenu,"parentId"))){
                    tempList.add(childMenu);
                }else{
                    List2.add(childMenu);
                }
            }
            if(List2.size()>0) {
                tempList = groupList(tempList, List2,actionList);
            }
            if(tempList.size()>0){
                menu.put("menu_list",tempList);
            }else{
                List<EntityMap> tempActionList=new ArrayList<>();
                for(EntityMap actionMenu:actionList){
                    if(MapUtils.getString(menu,"menuId").equals(MapUtils.getString(actionMenu,"menuId"))){
                        tempActionList.add(actionMenu);
                    }
                }
                menu.put("menu_list",tempActionList);
            }
        }
        return list;
    }

    private Integer getStyleType(String projectSn){
//        CompanyConfig companyConfig=companyConfigMapper.selectConfigByProject(projectSn);
//        if(companyConfig!=null&&companyConfig.getStyleType()!=null){
//            return companyConfig.getStyleType();
//        }else{
            return 1;
//        }
    }

}
