package com.pingpang.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.pingpang.load.impl.LoadPoll;
import com.pingpang.service.GetServerMsg;
import com.pingpang.service.UserMsgService;
import com.pingpang.service.UserService;
import com.pingpang.util.IPUtil;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChartUser;
import com.pingpang.websocketchat.ChatUserBind;

@Configuration
@RestController
@RequestMapping("/user")
public class Chat {
	
	@Value("${adminUserName}")
	private String adminUserName;
	
	@Value("${adminPassWord}")  
	private String adminPassWord;
	
	@DubboReference
	private UserService userService;
	
	@DubboReference
	private UserMsgService userMsgService;
	
	@DubboReference
	private GetServerMsg getServerMsg;
	/**
	  * 主页
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index() {
		return new ModelAndView("index");
	}

	/**
	 *  添加用户
	 * @return
	 */
	@RequestMapping(value="/regist")
	public ModelAndView userRegist(){
		return new ModelAndView("index");
	}
	
	/**
	 *  添加用户
	 * @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("userName", cu.getUserName());
			mav.addObject("userCode", cu.getUserCode());
			mav.addObject("userPassword", cu.getUserPassword());
			mav.addObject("isAdd", "1");
        	mav.addObject("errorMsg", addMap.get("MESSAGE"));
        	return mav;
		}
		
		ChatUserBind cub=new ChatUserBind(cu.getUserCode(),IPUtil.getIpAddr(request),"0");
		userMsgService.addUserBind(cub);
		
		mav.addObject("errorMsg","注册成功,请登录!");
		return new ModelAndView("index");
	}
	
	/**
	  * 用户登录
	 * @param userName
	 * @param userCode
	 * @return
	 */
	@RequestMapping("/chat")
	public ModelAndView chat(ChartUser cu,HttpServletRequest request) {
		if (null == cu.getUserPassword() ||"".equals(cu.getUserPassword()) ||null == cu.getUserCode() || "".equals(cu.getUserCode())) {
			return new ModelAndView("index");
		}

		request.setAttribute("userCode", cu.getUserCode());
		request.setAttribute("userPassword", cu.getUserPassword());
		
		//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
		//		.getRequest();
		
		//String scheme = request.getScheme();// http
		String serverName = request.getServerName();// localhost
		//int serverPort = request.getServerPort();// 8080
		//String contextPath = request.getContextPath();// 项目名
		//String url = scheme + "://" + serverName + ":" + serverPort + contextPath;// http://127.0.0.1:8080/test
		//String url = serverName;
		ModelAndView mav = new ModelAndView();
		/*
		 * if(null != ChannelManager.getChartUser(userCode)) { mav.setViewName("index");
		 * mav.addObject("errorMsg", "用户编码已存在，请换个编码!"); return mav; }
		 */	
		//管理员直接进入到管理账户页面
		if(cu.getUserCode().equals(this.adminUserName) && cu.getUserPassword().equals(this.adminPassWord)) {
			mav.setViewName("adminView");
			//这里是管理员页面
			request.getSession().setAttribute("isAdmin", true);
			request.getSession().setAttribute("user", cu);
			return mav;
		}
		
        cu=this.userService.getUser(cu);
        if(null==cu) {
        	request.setAttribute("errorMsg", "用户名或密码不正确!");
        	return new ModelAndView("index");
        }
        
        //用户状态-1:注销,0:离线,1:在线
        if("-1".equals(cu.getUserStatus())) {
        	request.setAttribute("errorMsg", "用户注销请联系管理员!");
        	return new ModelAndView("index");
        }
        
        String loginToken=UUID.randomUUID().toString().replace("-", "");
        boolean isLoginToken=userService.addUserLoginToken(cu, loginToken);
        if(!isLoginToken) {
        	request.setAttribute("errorMsg", "用户添加校验信息失败!");
        	return new ModelAndView("index");
        }
        
        request.getSession().setAttribute("user", cu);
        
        //把数据改为登录状态
        //userService.dbDownUser(cu.getUserCode(), cu.getUserStatus());
        
        ChatUserBind cub=new ChatUserBind(cu.getUserCode(),IPUtil.getIpAddr(request),"1");
		userMsgService.addUserBind(cub); 
        
        mav.setViewName("panl");
		mav.addObject("userName", cu.getUserName());
		mav.addObject("userCode", cu.getUserCode());
		mav.addObject("chatPath", serverName);
//		mav.addObject("nettyServer", new LoadPoll().getAddress());
		mav.addObject("nettyServer", getServerMsg.getServerIPMsg());
		mav.addObject("loginToken",loginToken);
		return mav;
	}
	
	
	/**
	 * 获取服务器地址
	 * 断线重连时使用
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/server-list")
	public Map<String,Object> getServer(HttpServletRequest request){
		ChartUser usr=(ChartUser)request.getSession().getAttribute("user");
		String loginToken=UUID.randomUUID().toString().replace("-", "");
        userService.addUserLoginToken(usr, loginToken);
        
		Map<String,Object>resultMap=new HashMap<String,Object>();
// 		resultMap.put("nettyServer", new LoadPoll().getAddress());
		resultMap.put("nettyServer", getServerMsg.getServerIPMsg());
 		resultMap.put("loginToken", loginToken);
 		return resultMap;
	}
	
	/**
	   * 用户退出
	 */
	@RequestMapping("/logOut")
	public ModelAndView index(HttpServletRequest request) {
		ChartUser cu=(ChartUser) request.getSession().getAttribute("user");
		
		//移除session
		request.getSession().removeAttribute("user");
		//移除聊天信息
		if(!StringUtil.isNUll(cu.getUserCode())) {
			//把数据改为离线状态
			ChartUser cuRedis=userService.getUser(cu);
			if(null!=cuRedis && "-1".equals(cuRedis.getUserStatus())) {
				userService.dbDownUser(cu.getUserCode(), "0");
			}
		}
		
		//return new ModelAndView("blog");
		return new ModelAndView("index");
	}
	
	
	/**
	   * 视频聊天
	 * @return
	 */
	@RequestMapping("/audio")
	public ModelAndView audio(HttpServletRequest request) {
		return new ModelAndView("videocall");
	}
	
	/**
	   *语音聊天
	 * @return
	 */
	@RequestMapping("/voice")
	public ModelAndView video(HttpServletRequest request) {
		return new ModelAndView("voicecall");
	}
	
	/**
	 * 直播发起
	 * @return
	 */
	@RequestMapping("/liveMe")
	public ModelAndView liveMe(HttpServletRequest request) {
		return new ModelAndView("videoLiveMe");
	}
	
	/**
	  * 直播人脸检测
	 * @return
	 */
	@RequestMapping("/videoLiveMeFace")
	public ModelAndView videoLiveMeFace(HttpServletRequest request) {
		return new ModelAndView("videoLiveMeFace");
	}
	
	/**
	 * 直播观看
	 * @return
	 */
	@RequestMapping("/liveCall")
	public ModelAndView liveCall(HttpServletRequest request) {
		return new ModelAndView("videoLiveCall");
	}
}
