package com.rndchina.aisin.system.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rndchina.aisin.system.modle.SystemUser;
import com.rndchina.aisin.system.service.FriendsCircleService;
import com.rndchina.aisin.system.service.UserService;
import com.rndchina.aisin.system.vo.UserVo;
import com.rndchina.aisin.util.Constants;
import com.rndchina.aisin.util.JSONFactory;
import com.rndchina.aisin.util.Util;
import com.rndchina.aisin.util.sms.SendSmsUtil;

/**
 * <code>UserController.java<code/>
 * <p>
 * 功能：用户相关操作Controller类
 * <p>
 * Copyright 神州锐达 2014 All right reserved.
 * 
 * @Author: Brain.Hou,2014年5月5日上午10:23:22
 */
@Controller
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private FriendsCircleService friendsCircleService;

	/**
	 * 获取手机短信验证码
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/user/getVerifyCode")
	public void regVerify(HttpServletRequest request,
			HttpServletResponse response) {
		String phonenum = request.getParameter("phonenum");
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("username", phonenum);
		long existUser = userService.findPart(5, 1, null, null, parameters)
				.size();
		if (existUser == 0) {
			if (Util.isNull(phonenum)) {
				String randcode = SendSmsUtil.sendSms(phonenum);
				if (Util.isNull(randcode)) {
					Map<String, String> resultMap = new HashMap<String, String>();
					resultMap.put("verifycode", randcode);
					JSONFactory.printData(response, Constants.succeed,
							Constants.success, resultMap);
				} else {
					JSONFactory.printResult(response, Constants.fail,
							"后台生成验证码失败");
				}
			} else {
				JSONFactory.printResult(response, Constants.fail, "手机号不能为空");
			}
		} else {
			JSONFactory.printResult(response, Constants.fail, "该手机已注册");
		}
	}

	/**
	 * 用户注册
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/user/userRegister")
	public void reg(HttpServletRequest request, HttpServletResponse response) {

		String username = request.getParameter("username");
		String nickname = request.getParameter("nickname");
		String password = request.getParameter("password");

		System.err.println("username=" + username + "nickname=" + nickname
				+ "password=" + password);

		if (Util.isNull(username) && Util.isNull(password)) {
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("username", username);
			long existUser = userService.findPart(1, 5, null, null, parameters)
					.size();
			if (existUser == 0) {
				// 本地库添加用户
				SystemUser newUser = new SystemUser();
				newUser.setId(Util.getUUID());
				String asId = this.getAsId();
				newUser.setUserAisinNum(asId);
				newUser.setPassword(password);
				newUser.setUsername(username);
				newUser.setUserMobilephone(username);
				newUser.setUserNickName(nickname);
				newUser.setUserIcon("default.jpg");
				userService.save(newUser);
				this.userLogin(request, response);
			} else {
				JSONFactory.printResult(response, Constants.fail, "用户名已存在");
			}
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/user/login")
	public void userLogin(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");

			Map<String, Object> parameters = new HashMap<String, Object>();
			if (Util.isMobileNo(username)) {
				parameters.put("username", username);
			} else {
				parameters.put("userAisinNum", username);
			}
			parameters.put("enabled", "1");
			List<SystemUser> loginUserList = userService.findPart(1, 5, null,
					null, parameters);
			if (loginUserList.size() > 0 && loginUserList.size() == 1) {
				SystemUser loginUser = loginUserList.get(0);
				if (Util.isNull(password)) {
					if (password.equals(loginUser.getPassword())) {
						// 将用户信息存入Session
						Util.getSession(request).setAttribute("loginUser",
								loginUser);
						request.setAttribute("userAisinNum",
								loginUser.getUserAisinNum());
						this.getUserMsgByAisinNum(request, response);
					} else {
						JSONFactory.printResult(response, Constants.fail,
								"密码错误");
					}
				} else {
					JSONFactory.printResult(response, Constants.fail, "密码为空");
				}
			} else {
				JSONFactory.printResult(response, Constants.fail, "用户名错误");
			}
		} catch (Exception e) {
			JSONFactory.printResult(response, Constants.fail, "服务器异常");
			e.printStackTrace();
		}
	}

	/**
	 * 获取用户信息
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/user/getUserMsgByAisinNum")
	public void getUserMsgByAisinNum(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String asId = request.getParameter("userAisinNum");
			if (!Util.isNull(asId)) {
				asId = request.getAttribute("userAisinNum").toString();
			}
			if (Util.isNull(asId)) {
				Map<String, Object> parameters = new HashMap<String, Object>();
				parameters.put("userAisinNum", asId);
				List<SystemUser> userList = userService.findPart(1, 5, null,
						null, parameters);
				if (null != userList && userList.size() == 1) {
					SystemUser user = userList.get(0);
					// 拼接用户视图对象
					UserVo userVo = new UserVo();
					userVo.setUserid(user.getId());
					userVo.setRealName(user.getRealName());
					userVo.setUserActivation(user.getUserActivation());
					userVo.setUserAddress(user.getUserAddress());
					userVo.setUserAisinNum(user.getUserAisinNum());
					userVo.setUserArea(user.getUserArea());
					userVo.setUserAuthentication(user.getUserAuthentication());
					userVo.setUserCountry(user.getUserCountry());
					userVo.setUserDuty(user.getUserDuty());
					userVo.setUserEducation(user.getUserEducation());
					userVo.setUserIcon(user.getUserIcon());
					userVo.setUserIdentitycard(user.getUserIdentitycard());
					userVo.setUserLandline(user.getUserLandline());
					userVo.setUserMail(user.getUserMail());
					userVo.setUserMobilephone(user.getUserMobilephone());
					userVo.setUsername(user.getUsername());
					userVo.setUserNickName(user.getUserNickName());
					userVo.setUserPolitical(user.getUserPolitical());
					userVo.setUserSex(user.getUserSex());
					userVo.setUserSignature(user.getUserSignature());
					userVo.setUserTDcode(user.getUserTDcode());
					JSONFactory.printData(response, Constants.succeed,
							Constants.success, userVo);
				} else {
					JSONFactory.printResult(response, 1, "该用户不存在");
				}
			} else {
				JSONFactory.printResult(response, 1, "爱信号为空");
			}
		} catch (Exception e) {
			JSONFactory
					.printResult(response, Constants.fail, Constants.failstr);
			e.printStackTrace();
		}
	}

	// /**
	// * 用户认证
	// *
	// * @param request
	// * @param response
	// */
	// @RequestMapping(value = "/user/identification")
	// public void identification(HttpServletRequest request,
	// HttpServletResponse response) {
	//
	// }

	//
	// /**
	// * 用户登出
	// *
	// * @param request
	// * @param response
	// */
	// @RequestMapping(value = "user/logout")
	// public void userLogout(HttpServletRequest request,
	// HttpServletResponse response) {
	// // Map<String, Object> xmppConnMap = (Map<String, Object>) Utils
	// // .getSession(request).getAttribute("xmppConnMap");
	// // if (Utils.isNull(xmppConnMap)) {
	// // XMPPConnection conn = (XMPPConnection) xmppConnMap.get(Utils
	// // .getLoginUser(request).getUserId());
	// // conn.disconnect();
	// // }
	// // String path = request.getContextPath();
	// // String path1 = request.getRequestURI();
	// // System.out.println(path + "-----" + path1 + "---" + path2);
	// }
	//
	// /**
	// * 获取用户信息By用户登录名
	// *
	// * @param request
	// * @param response
	// */
	// @RequestMapping(value = "user/getUserMsg")
	// public void getUserMsgByUserName(HttpServletRequest request,
	// HttpServletResponse response) {
	// String username = request.getParameter("username");
	//
	// UserBaseInfo loginUser = userService.findUserList(username);
	// try {
	// if (loginUser != null) {
	// // 查询用户认证信息
	// long pb = userService.findUserPBByUserId(loginUser.getUserId());
	//
	// UserVo uv = new UserVo();
	// uv.setUserid(loginUser.getUserId());
	// uv.setHeadAddress(loginUser.getHeadAddress());
	// uv.setLanguage(loginUser.getLanguage());
	// uv.setMobilePhone(loginUser.getMobilePhone());
	// uv.setNickName(loginUser.getNickName());
	// uv.setPraiseNum(loginUser.getPraiseNum());
	// uv.setCountryRegion(loginUser.getCountryRegion());
	// uv.setState(loginUser.getState());
	// uv.setCity(loginUser.getCity());
	// uv.setRegion(loginUser.getRegion());
	// uv.setSex(loginUser.getSex());
	// uv.setSignature(loginUser.getSignature());
	// uv.setStatus(loginUser.getStatus());
	// uv.setUserName(loginUser.getUserName());
	// uv.setStarLevel(loginUser.getStarLevel());
	// uv.setApprove(pb > 0 ? true : false);
	//
	// JSONFactory.printData(response, Constants.succeed,
	// Constants.success, uv);
	// } else {
	// JSONFactory.printResult(response, Constants.fail, "用户不存在");
	// }
	// } catch (Exception e) {
	// JSONFactory
	// .printResult(response, Constants.fail, Constants.failstr);
	// e.printStackTrace();
	// }
	// }

	/**
	 * 验证用户是否是应用的用户
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/user/verifyAppUser")
	public void verifyAppUser(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String userid = request.getParameter("userid");
			if (Util.isNull(userid)) {
				String contactsList = request.getParameter("contactsList");
				if (Util.isNull(contactsList)) {
					JSONObject jo = JSONObject.fromObject(contactsList);
					Map<String, Integer> resultMap = new HashMap<String, Integer>();
					List<String> list = JSONArray.fromObject(jo.get("list"));
					for (String str : list) {
						// String str = String.valueOf(lstr);
						str = str.replaceAll(" ", "");
						// 验证通讯录用户是否是爱信用户
						Map<String, Object> parameters = new HashMap<String, Object>();
						parameters.put("username", str);
						long userNum = userService.findPart(1, 5, null, null,
								parameters).size();
						if (userNum > 0) {
							// 验证通讯录用户是否已经是用户的好友
							String countHql = "From FriendsCircle fc,SystemUser user where fc.userid = '"
									+ userid
									+ "' and user.username = '"
									+ str
									+ "'";
							long friendNum = friendsCircleService
									.findCountWithHql(countHql);
							if (friendNum > 0) {
								// 是爱信用户并且也是用户的好友
								resultMap.put(str, Constants.zero);
							} else {
								// 是爱信用户但还不是用户的好友
								resultMap.put(str, Constants.one);
							}
						} else {
							// 不是爱信用户
							resultMap.put(str, Constants.two);
						}
					}

					JSONFactory.printData(response, Constants.succeed,
							Constants.success, resultMap);
				}
			}
		} catch (Exception e) {
			JSONFactory.printResult(response, Constants.fail, "出现了异常");
			e.printStackTrace();
		}
	}

	/**
	 * 生成不重复的爱信号
	 * 
	 * @return
	 */
	private String getAsId() {
		String asId = Util.getAsId();
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("userAisinNum", asId);
		long existUser = userService.findPart(1, 5, null, null, parameters)
				.size();
		if (existUser != 0) {
			asId = this.getAsId();
		}
		return asId;
	}
}