package com.goafanti.user.controller;

import java.util.Calendar;
import java.util.UUID;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goafanti.admin.service.AdminService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.BaseController;
import com.goafanti.common.enums.UserFields;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.common.utils.TimeUtils;
import com.goafanti.common.utils.VerifyCodeUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.easemob.EasemobUtils;
import com.goafanti.message.service.MessageService;
import com.goafanti.user.bo.InputUser;
import com.goafanti.user.service.UserService;

@Controller
public class UserRegisterController extends BaseController {
	@Resource
	private UserService		userService;
	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;
	@Resource
	private AdminService	adminService;
	@Resource
	private MessageService messageService;
	@Resource
	private EasemobUtils   easemobUtils;
	Logger					logger	= Logger.getLogger(UserRegisterController.class);
	
	/**
	 * 网站用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public Result register(@Valid InputUser user, String mobileCode,BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					UserFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		// 验证码15分钟有效
		if (TimeUtils.checkOverTime("register")) {
			res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "手机验证码超时失效"));
			return res;
		}
		if (!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode.toLowerCase())) {
			res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "手机验证码错误"));
			return res;
		}
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					bindingResult.getFieldError().getField()));
			return res;
		}
		if(StringUtils.isBlank(user.getUsername())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "用户名"));
		}else if(null == user.getType()){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "用户类型"));
		}else if (StringUtils.isBlank(user.getMobile())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "手机号码"));
		} else if (StringUtils.isBlank(user.getPassword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "密码"));
		} else {
			User u = userService.selectByMobieAndType(user.getMobile().trim(), user.getType());
			if (null != u) {
					res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "用户已存在"));
			}
		}
		if (res.getError().isEmpty()) {
			User us = new User();
			us.setId(UUID.randomUUID().toString());
			us.setMobile(user.getMobile().trim());
			us.setType(user.getType());
			us.setPassword(user.getPassword());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			us.setCreateTime(now.getTime());
			us.setUpdateTime(now.getTime());
			us.setPassword(passwordUtil.getEncryptPwd(us));
			us.setLvl(0);
			us.setNickname(user.getUsername());
			us.setSource(AFTConstants.USER_SOURCE_REGISTER);
			us.setStatus(AFTConstants.USER_STATUS_NORMAL);
			us.setShareType(AFTConstants.USER_SHARE_PUBLIC);
			us.setIdentifyName(StringUtils.isBlank(user.getUnitName())?"":user.getUnitName());
			us.setLvl(UserLevel.GENERAL.getCode());
			//us.setAid("0");
			userService.insertRegister(us,user.getUnitName(),user.getUsername());
		}
		return res;
	}
	
	
	/**
	 * APP用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/mregister", method = RequestMethod.POST)
	@ResponseBody
	public Result mRegister(@Valid InputUser user, String mobileCode,String uuid,BindingResult bindingResult) {
		Result res = new Result();
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					UserFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}
		// 验证码15分钟有效
		if (TimeUtils.checkOverTime("register")) {
			res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "手机验证码超时失效"));
			return res;
		}
		if (!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode.toLowerCase())) {
			res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "手机验证码错误"));
			return res;
		}
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					bindingResult.getFieldError().getField()));
			return res;
		}
		if(StringUtils.isBlank(user.getUsername())){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "用户名"));
		}else if(null == user.getType()){
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "用户类型"));
		}else if (StringUtils.isBlank(user.getMobile())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "手机号码"));
		} else if (StringUtils.isBlank(user.getPassword())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "密码"));
		} else {
			User u = userService.selectByMobieAndType(user.getMobile().trim(), user.getType());
			if (null != u) {
					res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "用户已存在"));
			}
		}
		if (res.getError().isEmpty()) {
			User us = new User();
			us.setId(UUID.randomUUID().toString());
			us.setMobile(user.getMobile().trim());
			us.setType(user.getType());
			us.setPassword(user.getPassword());
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			us.setCreateTime(now.getTime());
			us.setUpdateTime(now.getTime());
			us.setPassword(passwordUtil.getEncryptPwd(us));
			us.setLvl(0);
			us.setNickname(user.getUsername());
			us.setSource(AFTConstants.USER_SOURCE_REGISTER);
			us.setStatus(AFTConstants.USER_STATUS_NORMAL);
			us.setShareType(AFTConstants.USER_SHARE_PUBLIC);
			us.setIdentifyName(StringUtils.isBlank(user.getUnitName())?"":user.getUnitName());
			us.setLvl(UserLevel.GENERAL.getCode());
			userService.insertRegister(us,user.getUnitName(),user.getUsername());
			/*User currentUser =*/
					userService.selectByPrimaryKey(us.getId()); 			
			//registerEasemobAfterRegister(uuid,currentUser);//开通环信账号
		}
		return res;
	}
	
	/*private void registerEasemobAfterRegister(String uuid,User u){
			JSONObject resultObj = new JSONObject();
			String easemobName =  String.valueOf(u.getNumber());
			String easemobPass = new SimpleHash("md5", u.getId(), null, 1).toHex();
			resultObj.put("password", easemobPass);
			resultObj.put("username", easemobName);
			resultObj.put("nickname", StringUtils.isBlank(u.getNickname()) ? "技淘用户" + u.getNumber() : u.getNickname());
			easemobUtils.send(
					new EasemobInfo().uri("/users/").data(resultObj.toJSONString()).method(HttpMethod.POST));
			//绑定账号
			messageService.addJpushEasemobAccount(uuid,u.getId(),easemobName,easemobPass);		
	}*/
}
