package com.goafanti.app.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.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 org.springframework.web.bind.annotation.RestController;

import com.goafanti.achievement.service.AchievementInterestService;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.app.bo.ExpertsListBo;
import com.goafanti.banners.service.BannersService;
import com.goafanti.comment.bo.CommentResult;
import com.goafanti.comment.service.CommentService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.BaseApiController;
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.PasswordUtil;
import com.goafanti.common.utils.TimeUtils;
import com.goafanti.common.utils.VerifyCodeUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.demand.service.DemandService;
import com.goafanti.easemob.EasemobUtils;
import com.goafanti.message.service.MessageService;
import com.goafanti.news.service.NewsService;
import com.goafanti.user.bo.InputUser;
import com.goafanti.user.service.UserCareerService;
import com.goafanti.user.service.UserIdentityService;
import com.goafanti.user.service.UserInterestService;
import com.goafanti.user.service.UserService;

@RestController
@RequestMapping(value = "/open/app/user")
public class OpenAppUserController extends BaseApiController {
	@Resource
	private UserService userServiceImpl;
	@Resource
	private MessageService messageService;
	@Resource
	private CommentService 	commentService;
	@Resource
	private EasemobUtils   easemobUtils;
	@Resource
	private BannersService		bannersService;
	@Resource
	private NewsService			newsService;
	@Resource
	private AchievementService	achievementService;
	@Resource
	private DemandService		demandService;
	@Resource
	private UserCareerService	userCareerService;
	@Resource
	private UserInterestService userInterestService; 
	@Resource
	private UserIdentityService	userIdentityService;
	@Resource
	private AchievementInterestService achievementInterestService;
	@Resource
	private UserService	userService;
	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;
	
	/**
	 * 成果详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/achievementDetail", method = RequestMethod.GET)
	private Result userDetail(String id ) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"成果必须指定","成果"));
			return res;
		}
		res.setData(achievementService.selectAppUserOwnerDetail(id));
		return res;
	}
	/**
	 * 需求详情
	 */
	@RequestMapping(value = "/demandDetail", method = RequestMethod.GET)
	public Result DemandDetail(String id ) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"需求必须指定","需求"));
			return res;
		}
		res.setData(demandService.selectAppDemandDetail( id));
		return res;
	}
	
	/**
	 * 专家、顾问详情
	 */
	@RequestMapping(value = "/expertsDetail", method = RequestMethod.GET)
	public Result expertsDetail(String id ) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"id必须指定","id"));
			return res;
		}
		res.setData(userIdentityService.selectExpertsDetail( id));
		return res;
	}
	
	/**
	 * 专家、顾问评价
	 */
	@RequestMapping(value = "/expertsComment", method = RequestMethod.GET)
	public Result expertsComment(String id ,Integer pageNo,Integer pageSize) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR,"id必须指定","id"));
			return res;
		}
		CommentResult commentResult=new CommentResult();
		ExpertsListBo e=userIdentityService.selectExpertsDetail( id);
		commentResult.setNegativeCommentCount(e.getInferior());
		commentResult.setOrdinaryCommentCount(e.getGeneral());
		commentResult.setPositiveCommentCount(e.getFavorable());
		commentResult.setTotalCommentCount(e.getCommentCount());
		commentResult.setComments(commentService.selectExpertsComment(id, pageNo, pageSize));
		res.setData(commentResult);
		return res;
	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public Result index(){
		Result res = new Result();
		res.setData(messageService.selectMessageWithGroup());
		return res;
	}
	
	/**
	 * APP用户注册检查
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/registerCheck", method = RequestMethod.GET)
	@ResponseBody
	public Result registerCheck(@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.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;
		}
		
		return res.data(1);
	}
	/**
	 * APP用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/appRegister", method = RequestMethod.POST)
	@ResponseBody
	public Result AppRegister(@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())) {
			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;
		}
		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.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;
	}
}
