package com.goafanti.user.controller;

import java.util.Calendar;
import java.util.Date;
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.UserAuthentication;
import com.goafanti.common.enums.UserFields;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.InvitationCodeUtils;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.common.utils.TimeUtils;
import com.goafanti.common.utils.VerifyCodeUtils;
import com.goafanti.core.mybatis.JDBCIdGenerator;
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;
import com.goafanti.voucher.service.VoucherDetailService;
import com.goafanti.voucher.service.VoucherService;

@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;
	@Resource
	private JDBCIdGenerator	jDBCIdGenerator;
	@Resource
	private	VoucherDetailService	voucherDetailService;
	@Resource
	private VoucherService		voucherService;
	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;
		}
		if (StringUtils.isBlank(user.getUnitName())) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "用户名不能为空"));
			return res;
		}
		if (StringUtils.isBlank(user.getMobile())) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "手机号码不能为空"));
			return res;
		}
		User u = userService.selectByMobieAndType(user.getMobile().trim(),null);
		if (null != u) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "用户已存在"));
			return res;
		}
		if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) ==null||!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode.toLowerCase())) {
			res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "手机验证码错误"));
			return res;
		}
		// 验证码15分钟有效
		if (TimeUtils.checkOverTime("register")) {
			res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "手机验证码超时失效"));
			return res;
		}
		if (user.getBeInviteCode()!=null&&!user.getBeInviteCode().equals("")&&userService.checkeToInviteCode(user.getBeInviteCode())) {
				res.getError().add(buildError("邀请码不存在", "邀请码不存在"));
				return res;
		}
		if (res.getError().isEmpty()) {
			User us = new User();
			us.setId(UUID.randomUUID().toString());
			us.setMobile(user.getMobile().trim());
			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.setNickname(user.getUnitName());
			us.setSource(AFTConstants.USER_SOURCE_REGISTER);
			us.setBeInviteCode(user.getBeInviteCode());
			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.setAuthentication(UserAuthentication.UN_AUTHENTICATION.getCode());
			us.setTransferTime(now.getTime());
			userService.insertRegister(us,user.getUnitName(),user.getUsername());
			//获得抵用券
			userService.saveVoucher(us);
		}
		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;
		}
		if (StringUtils.isBlank(user.getUnitName())) {
			user.setUnitName("jt_"+InvitationCodeUtils.randomCode(new Date().getTime(),6));
		}
		if (StringUtils.isBlank(user.getMobile())) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "手机号码不能为空"));
			return res;
		}
		User u = userService.selectByMobieAndType(user.getMobile().trim(),null);
		if (null != u) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "用户已存在"));
		}
		if (TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE_TIME) ==null||!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode.toLowerCase())) {
			res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "手机验证码错误"));
			return res;
		}
		// 验证码15分钟有效
		if (TimeUtils.checkOverTime("register")) {
			res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "手机验证码超时失效"));
			return res;
		}
		if (user.getBeInviteCode()!=null&&!user.getBeInviteCode().equals("")&&userService.checkeToInviteCode(user.getBeInviteCode())) {
			res.getError().add(buildError("邀请码不存在", "邀请码不存在"));
			return res;
		}
		if (res.getError().isEmpty()) {
			User us = new User();
			us.setId(UUID.randomUUID().toString());
			us.setMobile(user.getMobile().trim());
			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.setNickname(user.getUnitName());
			if(user.getType() !=null)us.setType(user.getType());
			us.setBeInviteCode(user.getBeInviteCode());
			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.setAuthentication(UserAuthentication.UN_AUTHENTICATION.getCode());
			us.setTransferTime(now.getTime());
			userService.insertRegister(us,user.getUnitName(),user.getUsername());
			//获得抵用券
			userService.saveVoucher(us);
		}
		return res;
	}
	
	/*public void getVoucher(User u){
		if (StringUtils.isNotBlank(u.getBackgroundUrl())) {
			
			List<String> ids=voucherService.getSourceVoucher(VoucherSourceType.BYQFWS.getCode());
			for (String s : ids) {
				JtVoucherDetail j=new JtVoucherDetail();
				j.setId(jDBCIdGenerator.generateId().toString());
				j.setReceiveTime(new Date());
				j.setVoucherId(s);
				j.setUseUid(u.getId());
				j.setStatus(0);
				voucherDetailService.saveVoucherDetail(j);
			}
			
		}
	}
	
	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);		
	}*/
}
