package com.pingpang.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingpang.redis.RedisPre;
import com.pingpang.service.UserMsgService;
import com.pingpang.service.UserService;
import com.pingpang.util.IPUtil;
import com.pingpang.util.PageUtil;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChartUser;
import com.pingpang.websocketchat.ChatUserBind;


@RestController
@RequestMapping("/userController")
public class UserController {

	//日志操作
	private Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@DubboReference
	private UserService userService;
	
	@DubboReference
	private UserMsgService userMsgService;
	
	@Value("${IPDBTargetPath}")
	private String IPDBTargetPath;
	
	/**
	 * 后台管理界面
	 * @return
	 */
	@RequestMapping("/adminView")
	public ModelAndView adminView() {
		return new ModelAndView("regist");
	}
	
	/**
	 * 后台管理主页   
	 * @return
	 */
	@RequestMapping("/welcome")
	public ModelAndView welcome() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return new ModelAndView("welcome");
	}
	
	
	@ResponseBody
	@RequestMapping(value="/welcome-index")
	public Map<String,Object> adminTable(){
		Map<String,Object> tableMap=new HashMap<String,Object>();
		/**
		   * 统计注册用户和登录用户数
		 */
		//int userCount=userService.getAllUserCount(new HashMap<String,String>());
		//int userCount=userService.getAllRedisUser();
		int userCount=userService.getAllUserCount(new HashMap<String,String>());
		//int loginCount=ChannelManager.getAllUser().size();
		int loginCount=userService.getAllLoginUserCount();
		
		/**
		  * 统计注册用户数据 开始
		 */
		List<Map<String,String>> registCount=userService.getUserRegsitCount(7);
		List<String> dayList=new ArrayList<String>();
		List<String> countList=new ArrayList<String>();
		for(Map<String,String> map:registCount) {
			dayList.add(map.get("TODAY"));
			countList.add(map.get("COUNT"));
		}

		/**
		   * 面板1
		 */
		tableMap.put("userDate", "['用户总数','上线总数']");
		tableMap.put("userCount","[{value:"+userCount+", name:'用户总数'},{value:"+loginCount+", name:'上线总数'}]");
		
		/**
		   * 面板2
		 */
		tableMap.put("dbRegistUserDate", "['"+String.join("','",dayList)+"']");
		tableMap.put("dbRegistUserCount","['"+String.join("','",countList)+"']");
		
		
		return tableMap;
	}
	
	
	/**
	 * ip地图统计  
	 * @return
	 */
	@RequestMapping("/viewIPMap")
	public ModelAndView ipMap() {
		return new ModelAndView("ipMap");
	}
	
	@ResponseBody
	@RequestMapping(value="/ipMap")
	public List<Map<String,String>> getIPMap(){
		List<Map<String,Object>> ipMap=this.userService.getIPCount();
		Map<String,String> mapCount=new HashMap<String,String>();
		if(null!=ipMap && ipMap.size()>0) {
			for(Map<String,Object> map : ipMap) {
				String address=IPUtil.getAddress(map.get("IP").toString(),IPDBTargetPath);
				logger.info("获取IP {} =>地址 {} ",map.get("IP"),address);
				if(!StringUtil.isNUll(address)) {
					String provice=address.split("\\|")[2];
					if("0".equals(provice)) {
						logger.info("局域网地址");
						continue;
					}
					if(provice.endsWith("省")) {
						provice=provice.substring(0,provice.length()-1);
					}
					if(StringUtil.isNUll(mapCount.get(provice))) {
						mapCount.put(provice, map.get("COUNT_IP").toString());	
					}else {
						mapCount.put(provice, Integer.valueOf(mapCount.get(provice))+Integer.valueOf(map.get("COUNT_IP").toString())+"");	
					}
				}
			}
		}
		List<Map<String,String>> listMapCount=new ArrayList<Map<String,String>>();
		for(String key : mapCount.keySet()) {
			Map<String,String> map=new HashMap<String,String>();
			map.put("name", key);
			map.put("value", mapCount.get(key));
			listMapCount.add(map);
		}
		return listMapCount;
	}
	
	
	/**
	 *  添加用户
	 * @return
	 */
	@RequestMapping(value="/regist")
	public ModelAndView userRegist(){
		return new ModelAndView("regist");
	}
	
	/**
	 *  添加用户
	 * @return
	 */
	@RequestMapping(value="/addUser")
	public ModelAndView addUser(HttpServletRequest request,ChartUser cu){
		cu.setUserStatus("0");//设置位离线
		Map<String,Object> addMap=userService.addUser(cu);
		
		ModelAndView mav = new ModelAndView();
		
		if(!"S".equals(addMap.get("CODE"))){
			mav.setViewName("index");
        	mav.addObject("errorMsg", addMap.get("MESSAGE"));
        	return mav;
		}
		
		ChatUserBind cub=new ChatUserBind(cu.getUserCode(),IPUtil.getIpAddr(request),"0");
		userMsgService.addUserBind(cub);
		
		return new ModelAndView("index");
	}
	
	
	//----------------------在线用户数据开始----------------------
	/**
	 * 会员列表页面
	 * @return
	 */
	@RequestMapping("/online-member-list")
	public ModelAndView onlineMemberList() {
		return new ModelAndView("online-member-list");
	}
	
	
	/**
	 * 获取用户信息
	 */
	@ResponseBody
	@RequestMapping(value="/online-list")
	public Map<String,Object> onlineGetlistData(@RequestBody Map<String,String> queryMap) throws JsonParseException, JsonMappingException, IOException{
		queryMap.putAll(PageUtil.getPage(queryMap.get("page"), queryMap.get("limit")));
		ObjectMapper mapper = new ObjectMapper(); 
		if(!StringUtil.isNUll(queryMap.get("search"))) {
			queryMap.putAll(mapper.readValue(queryMap.get("search"), Map.class));
			queryMap.remove("search");
		}
		
		//Set<ChartUser> userList=ChannelManager.getAllUser();
		Set<ChartUser> userList=this.userService.getAllUpUser();
		Set<ChartUser> userListSearch=new HashSet<ChartUser>();
		//userList.iterator().
		for(ChartUser cu:userList) {
			if(!StringUtil.isNUll(queryMap.get("userCode"))) {
				if(cu.getUserCode().contains(queryMap.get("userCode"))){
					userListSearch.add(cu);
					continue;
				}
			}
			
			if(!StringUtil.isNUll(queryMap.get("userName"))) {
				if(cu.getUserName().contains(queryMap.get("userName"))){
					userListSearch.add(cu);
					continue;
				}
			}
			
		}
		
		Map<String,Object>resultMap=new HashMap<String,Object>();
		resultMap.put("code", "0");
		resultMap.put("msg", "");
		resultMap.put("page", queryMap.get("page"));
		resultMap.put("limit", queryMap.get("limit"));
		
		if(!StringUtil.isNUll(queryMap.get("userCode")) || !StringUtil.isNUll(queryMap.get("userName"))) {
			resultMap.put("count", userListSearch.size());
			resultMap.put("data", userListSearch);
		}else {
			resultMap.put("count", userList.size());
			resultMap.put("data", userList);
		}
		return resultMap;
	}
	
	/**
	 * 下线
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-downUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDownUser(@RequestParam("id") String code) throws Exception {
		ChartUser cu=userService.getChartUser(code);
		cu.setUserStatus("2");//禁言
		
		userService.sendAlertMsgByCode(code, "系统消息此用户已禁言!");
		userService.dbDownUser(code, "2");
    	return StringUtil.returnSucess();
    }
    
    /**
	 * 上线
	 * @param code
	 * @return
	 * @throws Exception
	 */
   @RequestMapping(value="/online-upUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineUpUser(@RequestParam("id") String code) throws Exception {
		ChartUser cu=userService.getChartUser(code);
		cu.setUserStatus("1");//上线
		userService.sendAlertMsgByCode(code, "系统消息此用户已上线!");
		userService.dbDownUser(code, "1");
   	    return StringUtil.returnSucess();
	}
   
    /**
	 *  注销
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-delUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDelUser(@RequestParam("id") String code) throws Exception {
    	//ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已下线!");
    	userService.removeChannelByCode(code);
		userService.dbDownUser(code, "-1");
 	    return StringUtil.returnSucess();
	}
    
    
    /**
	 * 下线
	 * @param code
	 * @return
	 * @throws Exception
	 */
   @RequestMapping(value="/online-downUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDownUserAll(@RequestParam("ids") String code) throws Exception {
	    if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
        String[]codeArray=code.split(",",-1);
        
        for(String str:codeArray) {
        	ChartUser cu=userService.getChartUser(str);
        	cu.setUserStatus("2");//禁言
        	userService.sendAlertMsgByCode(str, "系统消息此用户已禁言!");
        	userService.dbDownUser(str, "2");
        }
   	    return StringUtil.returnSucess();
   }
   
   /**
	 * 上线
	 * @param code
	 * @return
	 * @throws Exception
	 */
  @RequestMapping(value="/online-upUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineUpUserAll(@RequestParam("ids") String code) throws Exception {
	  if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
      String[]codeArray=code.split(",",-1);
      
      for(String str:codeArray) {
      	ChartUser cu=userService.getChartUser(str);
      	cu.setUserStatus("1");//上线
      	userService.sendAlertMsgByCode(str, "系统消息此用户已上线!!");
        userService.dbDownUser(cu.getUserCode(),"1");
      }
  	    return StringUtil.returnSucess();
	}
  
   /**
	 *  注销
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-delUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDelUserAll(@RequestParam("ids") String code) throws Exception {
	   if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
       String[]codeArray=code.split(",",-1);
       
       for(String str:codeArray) {
    	   //ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已下线!");
    	   userService.removeChannelByCode(str);
    	   userService.dbDownUser(str,"-1");
       }
	    return StringUtil.returnSucess();
	}
   
    
    /**
	 * 消息广播
	 * @param code
	 * @return
	 * @throws Exception
	 */
  @RequestMapping(value="/online-sendUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlinsendUserAll(@RequestParam("ids") String code,@RequestParam("msg") String msg) throws Exception {
	   if(StringUtil.isNUll(code) || StringUtil.isNUll(msg)) {
	    	return StringUtil.returnSucess();
	    }
     String[]codeArray=code.split(",",-1);
     
     for(String str:codeArray) {
    	 userService.sendAlertMsgByCode(str, msg);
     }
	    return StringUtil.returnSucess();
	}
    
 //----------------------在线用户数据结束----------------------
   
   
   
 //----------------------DB用户数据开始----------------------
 	/**
 	 * 会员列表页面
 	 * @return
 	 */
 	@RequestMapping("/db-member-list")
 	public ModelAndView dbMemberList() {
 		return new ModelAndView("db-member-list");
 	}
 	
 	
 	/**
 	 * 获取用户信息
 	 */
 	@ResponseBody
 	@RequestMapping(value="/db-list")
 	public Map<String,Object> dbGetlistData(@RequestBody Map<String,String> queryMap) throws JsonParseException, JsonMappingException, IOException{
 		queryMap.putAll(PageUtil.getPage(queryMap.get("page"), queryMap.get("limit")));
 		ObjectMapper mapper = new ObjectMapper(); 
 		if(!StringUtil.isNUll(queryMap.get("search"))) {
 			queryMap.putAll(mapper.readValue(queryMap.get("search"), Map.class));
 			queryMap.remove("search");
 		}
 		
 		Map<String,Object>resultMap=new HashMap<String,Object>();
 		resultMap.put("code", "0");
 		resultMap.put("msg", "");
 		resultMap.put("page", queryMap.get("page"));
 		resultMap.put("limit", queryMap.get("limit"));
 		resultMap.put("count", this.userService.getAllUserCount(queryMap));
 		resultMap.put("data",this.userService.getAllUser(queryMap));
 		return resultMap;
 	}
 	
 	/**
 	  * 离线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
     @RequestMapping(value="/db-downUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDownUser(@RequestParam("id") String code) throws Exception {
 		ChartUser cu=userService.getChartOnUser(code);
 		if(null!=cu && !"0".equals(cu.getUserStatus())) {
 			userService.sendAlertMsgByCode(code, "系统消息此用户已离线!");
 			this.userService.addHashMap(RedisPre.DB_USER+code, "userStatus", "2");
 		}
 		cu=this.userService.getUserByDB(code);
 		cu.setUserStatus("2");
 		this.userService.updateUser(cu);
        		
     	return StringUtil.returnSucess();
     }
     
     /**
 	  * 上线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-upUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbUpUser(@RequestParam("id") String code) throws Exception {
 		ChartUser cu=userService.getChartOnUser(code);
 		String status="0";
 		if(null!=cu && !"0".equals(cu.getUserStatus())) {
 			userService.sendAlertMsgByCode(code, "系统消息此用户已恢复!");
 			this.userService.addHashMap(RedisPre.DB_USER+code, "userStatus", "1");
 			status="1";
 		}
 		
 		cu=this.userService.getUserByDB(code);
 		cu.setUserStatus(status);
 		this.userService.updateUser(cu);	
 		
    	return StringUtil.returnSucess();
 	}
    
     /**
 	   *  注销
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
     @RequestMapping(value="/db-delUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDelUser(@RequestParam("id") String code) throws Exception {
    	 userService.removeChannelByCode(code);
 		
 		Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.add(code);
 		
        this.userService.dbDownUser(userCodeSet, "-1"); 	
 		
  	    return StringUtil.returnSucess();
 	}
     
     
     /**
 	  * 禁言
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-downUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDownUserAll(@RequestParam("ids") String codes) throws Exception {
 	    if(StringUtil.isNUll(codes)) {
 	    	return StringUtil.returnSucess();
 	    }
         String[]codeArray=codes.split(",",-1);
         
         for(String code:codeArray) {
         	ChartUser cu=userService.getChartOnUser(code);
         	 if(null!=cu && !"0".equals(cu.getUserStatus())) {
         		userService.sendAlertMsgByCode(code, "系统消息此用户已禁言!");
         	   this.userService.addHashMap(RedisPre.DB_USER+code, "userStatus", "2");
         	 }
         	 
         	 if(null==cu) {
         		 cu=this.userService.getUserByDB(code);
         	 }
         	 cu.setUserStatus("2");
         	 this.userService.updateUser(cu);
         }
         
    	 return StringUtil.returnSucess();
    }
    
    /**
 	  * 正常
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
   @RequestMapping(value="/db-upUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbUpUserAll(@RequestParam("ids") String codes) throws Exception {
 	  if(StringUtil.isNUll(codes)) {
 	    	return StringUtil.returnSucess();
 	    }
       String[]codeArray=codes.split(",",-1);
       
       for(String code:codeArray) {
       	ChartUser cu=userService.getChartOnUser(code);
       	if(null!=cu && !"0".equals(cu.getUserStatus())) {
       		userService.sendAlertMsgByCode(code, "系统消息此用户已上线!");
       		this.userService.addHashMap(RedisPre.DB_USER+code, "userStatus", "1");
       	 }
       	
        if(null==cu) {
    		 cu=this.userService.getUserByDB(code);
    	 }
        
       	 cu.setUserStatus("0");
       	 this.userService.updateUser(cu);
       }
   	    return StringUtil.returnSucess();
 	}
   
    /**
 	   *  注销
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-delUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDelUserAll(@RequestParam("ids") String code) throws Exception {
 	   if(StringUtil.isNUll(code)) {
 	    	return StringUtil.returnSucess();
 	    }
        String[]codeArray=code.split(",",-1);
        
        for(String str:codeArray) {
           //ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已注销!");
        	userService.removeChannelByCode(str);
        }
        
        Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.addAll(Arrays.asList(codeArray));
 		this.userService.dbDownUser(userCodeSet, "-1"); 
 		 
 	    return StringUtil.returnSucess();
 	}
  //----------------------DB用户数据结束----------------------   
   
}
