package com.cim.idm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.response.BaseResponse;
import com.cim.idm.response.RespGenerator;
import com.cim.idm.service.QueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@EnableAutoConfiguration
@RequestMapping("/menu")
public class MenuController {
	
	@Autowired
	private QueryService queryServiceImpl;
	
	@RequestMapping(value = "/getHierarchicalMenuOfPermission", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> getHierarchicalMenuOfPermission(@RequestBody Map<String,Object> param)
	{
		
		String queryId = param.get("queryId").toString();
		String version = param.get("version").toString();
		Map bindMap = (Map) param.get("params");
		
		String userId = bindMap.get("USERID")== null ? null : bindMap.get("USERID").toString();
		String platform = bindMap.get("PLATFORM")== null ? null : bindMap.get("PLATFORM").toString();
		
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("USERID", userId);
		hashMap.put("PLATFORM", platform);
		
		JSONObject head = new JSONObject(true);
		try {
			
			List<Map<String,Object>> mapList = queryServiceImpl.getQueryResult(queryId, version, hashMap);
			// 使用Stream API按"SUPERMENUID"分组  
	        Map<Object, List<Map<String, Object>>> groupedBySuperMenuId = mapList.stream()  
	            .collect(Collectors.groupingBy(  
	                map -> map.get("SUPERMENUID")  
	        ));
	        
	        String superMenuId = "root";
	        List<Map<String,Object>> map1List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
			JSONArray headArray = new JSONArray();
			
			for (Map<String, Object> map1 : map1List) {
				JSONObject boday = new JSONObject(true);
				formatter(map1, boday);
				
				superMenuId = map1.get("MENUID").toString();	
				List<Map<String,Object>> map2List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
				JSONArray jsonArray1 = new JSONArray();
				for (Map<String, Object> map2 : map2List) {
					JSONObject detail1 = new JSONObject(true);
					formatter(map2, detail1);
					
					superMenuId = map2.get("MENUID").toString();
					List<Map<String,Object>> map3List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
					JSONArray jsonArray2 = new JSONArray();
					for (Map<String, Object> map3 : map3List) {
						JSONObject detail2 = new JSONObject(true);
						formatter(map3, detail2);
						jsonArray2.add(detail2);
					}
					detail1.put("children", jsonArray2);
					jsonArray1.add(detail1);
				}
				boday.put("children", jsonArray1);
				headArray.add(boday);
			}
			head.put("menuList", headArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 BaseResponse returnOK = RespGenerator.returnOK(head);
        return returnOK;
	}


	private void formatter(Map<String, Object> map, JSONObject detail) {
		detail.put("id", map.get("MENUID"));
		detail.put("parentId",  map.get("SUPERMENUID"));
		detail.put("routeName",  map.get("ROUTENAME"));
		detail.put("routePath",  map.get("ROUTEPATH"));
		detail.put("componentPath",  map.get("COMPONENTPATH"));
		detail.put("menuName",  map.get("MENUNAME"));
		detail.put("leafFlag", map.get("LEAFFLAG"));
		detail.put("hiddenFlag", map.get("HIDDENFLAG"));
		detail.put("cacheFlag",  map.get("CACHEFLAG"));
		detail.put("platform",  map.get("PLATFORM"));
		detail.put("icon",  map.get("ICON"));
	}
	
	@RequestMapping(value = "/getHierarchicalMenuWithCheck", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> getHierarchicalMenuWithCheck(@RequestBody Map<String,Object> param)
	{
		
		String queryId = param.get("queryId").toString();
		String version = param.get("version").toString();
		Map bindMap = (Map) param.get("params");
		
		String userGroupName = bindMap.get("USERGROUPNAME")== null ? null : bindMap.get("USERGROUPNAME").toString();
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("USERGROUPNAME", userGroupName);
		
		JSONObject head = new JSONObject(true);
		try {
			List<Map<String,Object>> mapList = queryServiceImpl.getQueryResult(queryId, version, hashMap);
			// 使用Stream API按"SUPERMENUID"分组  
	        Map<Object, List<Map<String, Object>>> groupedBySuperMenuId = mapList.stream()  
	            .collect(Collectors.groupingBy(  
	                map -> map.get("SUPERMENUID")  
	        ));

			head.put("menuList", groupedBySuperMenuId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 BaseResponse returnOK = RespGenerator.returnOK(head);
        return returnOK;
	}
	
	@RequestMapping(value = "/getHierarchicalMenu", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> getHierarchicalMenu(@RequestBody Map<String,Object> param)
	{
		
		String queryId = param.get("queryId").toString();
		String version = param.get("version").toString();
		Map bindMap = (Map) param.get("params");
		
		String userId = bindMap.get("USERID")== null ? null : bindMap.get("USERID").toString();
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("USERID", userId);
		
		JSONObject head = new JSONObject(true);
		try {
			
			List<Map<String,Object>> mapList = queryServiceImpl.getQueryResult(queryId, version, hashMap);
			// 使用Stream API按"SUPERMENUID"分组  
	        Map<Object, List<Map<String, Object>>> groupedBySuperMenuId = mapList.stream()  
	            .collect(Collectors.groupingBy(  
	                map -> map.get("SUPERMENUID")  
	            ));
	        
	        String superMenuId = "root";
	        List<Map<String,Object>> map1List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
			JSONArray headArray = new JSONArray();
			
			for (Map<String, Object> map1 : map1List) {
				JSONObject boday = new JSONObject(true);
				JSONArray jsonArray = new JSONArray();
				formatter(map1, boday);
				
				superMenuId = map1.get("MENUID").toString();	
				List<Map<String, Object>> map2List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
				JSONArray jsonArray1 = new JSONArray();
				for (Map<String, Object> map2 : map2List) {
					JSONObject detail1 = new JSONObject(true);
					formatter(map2, detail1);
					
					superMenuId = map2.get("MENUID").toString();	
					List<Map<String, Object>> map3List = groupedBySuperMenuId.getOrDefault(superMenuId, new ArrayList<>());
					JSONArray jsonArray2 = new JSONArray();
					for (Map<String, Object> map3 : map3List) {
						JSONObject detail2 = new JSONObject(true);
						formatter(map3, detail2);
						jsonArray2.add(detail2);
					}
					detail1.put("children", jsonArray2);
					jsonArray1.add(detail1);
				}
				boday.put("children", jsonArray1);
				headArray.add(boday);
			}
			head.put("menuList", headArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 BaseResponse returnOK = RespGenerator.returnOK(head);
        return returnOK;
	}
	
	@RequestMapping(value = "/addMenu", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> addMenu(@RequestBody Map<String,Object> param){
		
		String id = (String)param.get("id");
		String parentId = (String)param.get("parentId");
		if(parentId == null) {
			parentId = "root";
		}
		String routeName = (String)param.get("routeName");
		String routePath = (String)param.get("routePath");
		String menuName = (String)param.get("menuName");
		String componentPath = (String)param.get("componentPath");
		Integer leafFlag = (Integer)param.get("leafFlag");
		Integer hiddenFlag = (Integer)param.get("hiddenFlag");
		Integer cacheFlag = (Integer)param.get("cacheFlag");
		String icon = (String)param.get("icon");
		String platform = (String)param.get("platform");

		String checkDuplicateSql = "SELECT COUNT(*) FROM menu WHERE menuid = ?";
		Long count = IDMFrameServiceProxy.getSqlTemplate().queryForObject(checkDuplicateSql, Long.class, id);
		if(count > 0) {
			BaseResponse returnError = RespGenerator.returnError("该数据已存在!");
			return returnError;
		}
		
		String sql = "INSERT INTO menu (menuid, supermenuid, routename, routepath, componentpath, " +  
                "menuname, leafflag, hiddenflag, cacheflag, platform, icon) " +  
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";  

		Object[] args = new Object[]{id, parentId, routeName, routePath, componentPath,   
                                menuName, leafFlag, hiddenFlag, cacheFlag, platform, icon};  

		IDMFrameServiceProxy.getSqlTemplate().update(sql, args);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;

	}
	
	@RequestMapping(value = "/editMenu", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> editMenu(@RequestBody Map<String,Object> param){
		
		String id = (String)param.get("id");
		String parentId = (String)param.get("parentId");
		String routeName = (String)param.get("routeName");
		String routePath = (String)param.get("routePath");
		String menuName = (String)param.get("menuName");
		String componentPath = (String)param.get("componentPath");
		Integer leafFlag = (Integer)param.get("leafFlag");
		Integer hiddenFlag = (Integer)param.get("hiddenFlag");
		Integer cacheFlag = (Integer)param.get("cacheFlag");
		String icon = (String)param.get("icon");
		String platform = (String)param.get("platform");

		String sql = "UPDATE menu " +  
                "SET supermenuid = ?, routename = ?, routepath = ?, componentpath = ?, " +  
                "menuname = ?, leafflag = ?, hiddenflag = ?, cacheflag = ?, icon = ?, platform = ? " +  
                "WHERE menuid = ?";  

		Object[] args = new Object[]{parentId, routeName, routePath, componentPath,   
                                menuName, leafFlag, hiddenFlag, cacheFlag, icon, platform, id};
		
		IDMFrameServiceProxy.getSqlTemplate().update(sql, args);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;
        
	}
	
	@RequestMapping(value = "/deleteMenu", method = RequestMethod.POST)
	public BaseResponse<Map<String, Object>> deleteMenu(@RequestBody Map<String,Object> param)
	{
		String id = (String)param.get("id");
		String sql = "DELETE FROM menu WHERE MENUID = ?";
		IDMFrameServiceProxy.getSqlTemplate().update(sql, id);
		BaseResponse returnOK = RespGenerator.returnOK(param);
        return returnOK;
	}

}
