package com.jeeplus.modules.sys.web;


import com.easemob.server.example.api.impl.EasemobIMUsers;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.EncrypeUtil;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.SystemConfig;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemConfigService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import redis.clients.jedis.Jedis;

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

/**
 * 用户Controller
 * @author jeeplus
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/register")
public class RegisterController extends BaseController {


	@Autowired
	private SystemConfigService systemConfigService;
	
	@Autowired
	private SystemService systemService;

	@Autowired
	private OfficeService officeService;

	@Autowired
	private UserDao userDao;

	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getUser(id);
		}else{
			return new User();
		}
	}

	@RequestMapping(value = {"index",""})
	public String register(User user, Model model) {
		return "modules/sys/register";
	}


	@RequestMapping(value = "registerUser")
	public String registerUser( HttpServletRequest request,HttpServletResponse response, boolean mobileLogin, String randomCode, User user, Model model, RedirectAttributes redirectAttributes) {
		Jedis jedis = null;
		try {
			jedis = JedisUtils.getResource();
			String mobile = user.getMobile();
			String name = user.getName();
			String password = EncrypeUtil.encrypeString(user.getPassword(),"UTF-8");
			AjaxJson j = new AjaxJson();
			//验证手机号是否已经注册
			if (userDao.findUniqueByProperty("mobile", user.getMobile()) != null) {
				// 如果是手机登录，则返回JSON字符串
				if (mobileLogin) {
					j.setSuccess(false);
					j.setErrorCode("1");
					j.setMsg("手机号已经被使用！");
					return renderString(response, j.getJsonStr());
				} else {
					addMessage(model, "手机号已经被使用!");
					return register(user, model);
				}
			}
			/*if (!randomCode.equals(jedis.get(mobile)) || !"1".equals(jedis.get("1"))) {
				String message= "验证码验证失败!";
				j.setSuccess(false);
				j.setMsg(message);
				j.setErrorCode(ErrorCode.code_1011);
			}*/
			// 清除验证码
			//request.getSession().getServletContext().removeAttribute(mobile);
			jedis.del(mobile);
			String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
			String contextPath = request.getContextPath();
			j = systemService.registerUser(mobile,randomCode,name,password,contextPath,url);
			addMessage(redirectAttributes, j.getMsg());
		} catch (Exception e) {
			//logger.error("getActiveSessions", e);
			AjaxJson j = new AjaxJson();
			String message= "验证码验证失败，注册失败！";
			j.setSuccess(false);
			j.setMsg(message);
			j.setErrorCode(ErrorCode.code_1011);
		} finally {
			JedisUtils.returnResource(jedis);
		}
		/*AjaxJson j = new AjaxJson();
		long time = System.currentTimeMillis();
		String name = user.getName();
		try {
			//验证手机号是否已经注册
			if (userDao.findUniqueByProperty("mobile", user.getMobile()) != null) {
				// 如果是手机登录，则返回JSON字符串
				if (mobileLogin) {
					j.setSuccess(false);
					j.setErrorCode("1");
					j.setMsg("手机号已经被使用！");
					return renderString(response, j.getJsonStr());
				} else {
					addMessage(model, "手机号已经被使用!");
					return register(user, model);
				}
			}
		//验证用户是否已经注册
		if(userDao.findUniqueByProperty("login_name", user.getLoginName()) != null){
			// 如果是手机登录，则返回JSON字符串
			if (mobileLogin){
				AjaxJson j = new AjaxJson();
				j.setSuccess(false);
				j.setErrorCode("2");
				j.setMsg("用户名已经被注册！");
		        return renderString(response, j.getJsonStr());
			}else{
				addMessage(model, "用户名已经被注册!");
				return register(user, model);
			}
		}

			//验证短信内容
			if (!randomCode.equals(request.getSession().getServletContext().getAttribute(user.getMobile()))) {
				// 如果是手机登录，则返回JSON字符串
				if (mobileLogin) {
					j.setSuccess(false);
					j.setErrorCode("3");
					j.setMsg("手机验证码不正确!");
					return renderString(response, j.getJsonStr());
				} else {
					addMessage(model, "手机验证码不正确!");
					return register(user, model);
				}
			}
			*//*

			/// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
			List<Dict> dictList = DictUtils.getDictList("defalut_role");
			Dict dict = dictList.get(0);
			Role role = systemService.getRole(dict.getValue());
	*//*		String officeCode = "1000";
			if(roleName.equals("patient")){
				officeCode = "1001";
			}
			Office office = officeService.getByCode(officeCode);*//*
			// 密码MD5加密
			String password = EncrypeUtil.encrypeString(user.getPassword(), "UTF-8");
			user.setPasswordRemake(password);
			user.setPassword(SystemService.entryptPassword(password));
			user.setLoginName(user.getMobile());

			// 岗位数据有效性验证，过滤不在授权内的岗位
			List<Role> roleList = Lists.newArrayList();
			roleList.add(role);
			user.setRoleList(roleList);

			*//*
			//保存机构
			user.setCompany(office);
			user.setOffice(office);
			*//*
			// 生成用户二维码，使用登录名
			String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL +time+ "/qrcode/";
			FileUtils.createDirectory(realPath);
			String picName = time + ".png"; // encoderImgId此处二维码的图片名
			String filePath = realPath + picName; // 存放路径
			TwoDimensionCode.encoderQRCode(user.getLoginName(), filePath, "png");// 执行生成二维码
			user.setQrCode(request.getContextPath() + Global.USERFILES_BASE_URL +time+  "/qrcode/" + picName);
			if (user.getQrCode()!=null && !user.getQrCode().equals("")){
				InputStream inputStream = null;
				HttpURLConnection httpURLConnection;
				try {
					URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ user.getQrCode());
					httpURLConnection = (HttpURLConnection) url.openConnection();
					// 设置网络连接超时时间
					httpURLConnection.setConnectTimeout(3000);
					// 设置应用程序要从网络连接读取数据
					httpURLConnection.setDoInput(true);

					httpURLConnection.setRequestMethod("GET");
					int responseCode = httpURLConnection.getResponseCode();
					if (responseCode == 200) {
						// 从服务器返回一个输入流
						inputStream = httpURLConnection.getInputStream();
					}
					OSSClientUtil ossUtil =new OSSClientUtil();
					String[] arr = user.getQrCode().split("/");
					String qrCodeName = System.currentTimeMillis()+arr[arr.length-1];
					ossUtil.uploadFile2OSS(inputStream, Global.getRqcode(),qrCodeName);
					user.setQrCode(Global.getAliyunUrl()+"/"+ Global.getRqcode() + qrCodeName);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					inputStream.close();
				}
			}
			String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL  +time+ "/img/";
			FileUtils.createDirectory(realPathPhoto);
			String picNamePhoto =time + ".png"; // encoderImgId此处二维码的图片名
			String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
			//FontImageUtil.createImage(name.substring(0, 1), new Font("宋体", Font.BOLD, 100), new File(filePathPhoto), 200, 200);
			WordToPic.TextToPic(name.substring(name.length()-2>0?name.length()-2:0,name.length()),200, 200, 55, filePathPhoto);
			user.setPhoto(request.getContextPath() + Global.USERFILES_BASE_URL + time + "/img/"+picNamePhoto);
			if (user.getPhoto()!=null && !user.getPhoto().equals("")){
				InputStream inputStream = null;
				HttpURLConnection httpURLConnection;
				try {
					URL url = new URL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ user.getPhoto());
					httpURLConnection = (HttpURLConnection) url.openConnection();
					// 设置网络连接超时时间
					httpURLConnection.setConnectTimeout(3000);
					// 设置应用程序要从网络连接读取数据
					httpURLConnection.setDoInput(true);

					httpURLConnection.setRequestMethod("GET");
					int responseCode = httpURLConnection.getResponseCode();
					if (responseCode == 200) {
						// 从服务器返回一个输入流
						inputStream = httpURLConnection.getInputStream();

					}
					OSSClientUtil ossUtil =new OSSClientUtil();
					String[] arr = user.getPhoto().split("/");
					String photoName = time+arr[arr.length-1];
					ossUtil.uploadFile2OSS(inputStream, Global.getPhoto(),photoName);
					user.setPhoto(Global.getAliyunUrl() + "/" + Global.getPhoto() + photoName);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					inputStream.close();
				}
			}
			// 保存用户信息

			// 清除当前用户缓存
			if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
				UserUtils.clearCache();
				//UserUtils.getCacheMap().clear();
			}
			request.getSession().getServletContext().removeAttribute(user.getMobile());//清除验证码

			//环信注册
			RegisterUsers users = new RegisterUsers();
			io.swagger.client.model.User user1 = new io.swagger.client.model.User().username(user.getId()).password(password);
			users.add(user1);
			Object result = easemobIMUsers.createNewIMUserSingle(users);
			Nickname nickname = new Nickname();
			nickname.setNickname(user.getName());
			easemobIMUsers.modifyIMUserNickNameWithAdminToken(user.getId(), nickname);
			logger.info(result.toString());
			addMessage(redirectAttributes, "注册用户'" + user.getLoginName() + "'成功");
		}catch (Exception e){
			e.printStackTrace();
			userDao.delete(user);
		}*/
		return "redirect:" + adminPath + "/login";
	}
	
	
	/**
	 * 获取验证码
	 * @param request
	 * @param response
	 * @param mobile
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "getRegisterCode")
	@ResponseBody
	public AjaxJson getRegisterCode(HttpServletRequest request,HttpServletResponse response, String mobile,String type,
			Model model, RedirectAttributes redirectAttributes) {
		SystemConfig config = systemConfigService.get("1");
		AjaxJson j = new AjaxJson();
		//验证手机号是否已经注册
		if(userDao.findUniqueByProperty("mobile", mobile) == null||("resetPassword").equals(type)){
		String randomCode = String.valueOf((int) (Math.random() * 9000 + 1000));
		System.out.println(randomCode);
		// String result = UserUtils.sendRandomCode(config.getSmsName(),config.getSmsPassword(), mobile, randomCode);
		String result = null;
		Jedis jedis = null;
		try{
			if(("2").equals(Global.getCodeType())){
				//调用工具类返回结果
				result = UserUtils.sendRandomCodes(mobile, randomCode);
				JSONObject jsonObj = JSONObject.fromObject(result);
				String statusCode = jsonObj.getString("statusCode");
				//if (result.contains("Success") && result.contains("ok")) {
				if (("000000").equals(statusCode)) {
					j.setSuccess(true);
					j.setErrorCode("-1");
					j.setMsg("短信发送成功!");
					//存放验证码
					jedis = JedisUtils.getResource();
					jedis.set(mobile, randomCode);

					jedis.setex(mobile, 300, randomCode);
					//request.getSession().getServletContext().setAttribute(mobile, randomCode);
				}else{
					j.setSuccess(false);
					j.setErrorCode("2");
					//j.setMsg("短信发送失败，错误代码："+result+"，请联系管理员。");
					j.setMsg("短信发送失败，错误代码：101，请联系管理员。");
					j.put("ErrorXml",result);
				}
			}else{
				//调用工具类返回结果
				result = UserUtils.sendRandomCode(mobile, randomCode);
				if (result.contains("Success") && result.contains("ok")) {
					j.setSuccess(true);
					j.setErrorCode("-1");
					j.setMsg("短信发送成功!");
					//存放验证码
					jedis = JedisUtils.getResource();
					jedis.set(mobile, randomCode);

					jedis.setex(mobile, 300, randomCode);
					//request.getSession().getServletContext().setAttribute(mobile, randomCode);
				}else{
					j.setSuccess(false);
					j.setErrorCode("2");
					//j.setMsg("短信发送失败，错误代码："+result+"，请联系管理员。");
					j.setMsg("短信发送失败，错误代码：101，请联系管理员。");
					j.put("ErrorXml",result);
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			logger.info("5");
			j.setSuccess(false);
			j.setErrorCode("101");
			j.setMsg("短信发送失败!");
		}
		finally {
			JedisUtils.returnResource(jedis);
		}
		return j;
		}else{
			return null ;
		}
		/*		} catch (IOException e) {
			j.setSuccess(false);
			j.setErrorCode("3");
			j.setMsg("因未知原因导致短信发送失败，请联系管理员。");
		}
		//验证手机号是否已经注册
		if(userDao.findUniqueByProperty("mobile", mobile) != null){

				j.setSuccess(false);
				j.setErrorCode("1");
				j.setMsg("手机号已经被使用！");
		        return j;
		}*/
	}


	/**
	 * web端ajax验证手机验证码是否正确
	 */
	@ResponseBody
	@RequestMapping(value = "validateMobileCode")
	public boolean validateMobileCode(HttpServletRequest request,
			String mobile, String randomCode) {
		Jedis jedis = null;
		try {
			jedis = JedisUtils.getResource();
			String randomCode1 = jedis.get(mobile);
			logger.info("-----"+randomCode1);
			if (randomCode.equals(randomCode1)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			logger.error("getActiveSessions", e);
			return false;
		} finally {
			JedisUtils.returnResource(jedis);
		}
		/*if (randomCode.equals(request.getSession().getServletContext().getAttribute(mobile))) {
			return true;
		} else {
			return false;
		}*/
	}
	/**
	 * web端ajax验证密码是否正确
	 */
	@ResponseBody
	@RequestMapping(value = "validatePassword")
	public String validatePassword(HttpServletRequest request,
									  String password, String loginName) {
		User user = UserUtils.getByLoginName(loginName);
		if (user ==null || org.apache.commons.lang3.StringUtils.isBlank(user.getId())){
			return "false";
		}
		//password = SystemService.encrypeString(password);
		if (SystemService.validatePassword(password, user.getPassword())) {
			return "true";
		} else {
			return "false";
		}
	}



}
