package com.goafanti.user.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goafanti.app.bo.UserBasicInfo;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.BaseController;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.MessageConsumer;
import com.goafanti.common.model.MessageProducer;
import com.goafanti.common.model.User;
import com.goafanti.common.utils.TimeUtils;
import com.goafanti.common.utils.VerifyCodeUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.message.bo.MessageBo;
import com.goafanti.message.service.MessageService;
import com.goafanti.user.service.UserService;

@Controller
public class UserLoginController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private AdminMapper	adminMapper;
	@Resource
	private MessageService messageService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	@ResponseBody
	public Result login(HttpServletRequest request, Model model) {
		Result res = new Result();
		TokenManager.logout();
		return res;
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @param remember
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/signin", method = RequestMethod.POST)
	@ResponseBody
	public Result signin(User user, Boolean remember, HttpServletRequest request) {
		Result res = new Result();
		JSONObject jo = (JSONObject) JSON.toJSON(TokenManager.login(user, remember));
		SavedRequest sr = WebUtils.getAndClearSavedRequest(request);
		if (sr != null) {
			jo.put("requestURI", sr.getRequestURI());
			jo.put("queryString", sr.getQueryString());
		}
		res.setToken(SecurityUtils.getSubject().getSession().getId());
		return res;
	}


	/**
	 * 用户登录
	 * 
	 * @param user
	 * @param remember
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/mlogin", method = RequestMethod.POST)
	@ResponseBody
	public Result mLogin(User user, Boolean remember, HttpServletRequest request) {
		Result res = new Result();
		JSONObject jo = (JSONObject) JSON.toJSON(TokenManager.login(user, remember));
		
		UserBasicInfo ubi=userService.selectBaseInfo();
		jo.put("easemobName",ubi.getEasemobName());
		jo.put("easemobPass",ubi.getEasemobPass());
		res.setToken(SecurityUtils.getSubject().getSession().getId());
		res.setData(jo);
		// 发送推送消息
		sendMessageAfterLogin(); 
		return res;
	}

	/**
	 * 管理端登录
	 * 
	 * @param user
	 * @param remember
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/managesignin", method = RequestMethod.POST)
	@ResponseBody
	public Result managesignin(Admin admin, Boolean remember, HttpServletRequest request) {
		Result res = new Result();
		String mobile=adminMapper.selectStatusByMobile(admin.getMobile());
		if("锁定".equals(mobile)){
			res.getError().add(buildError("","用户已被锁定不能登录"));
			return res;
		}
		if("注销".equals(mobile)){
			res.getError().add(buildError("","用户已被注销"));
			return res;
		}
		res.setData(TokenManager.manageLogin(admin, remember));
		return res;
	}

	/**
	 * 忘记密码 使用手机号+手机验证码登录
	 * 
	 * @param mobile
	 * @param mobileCode
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/mobileSigin", method = RequestMethod.POST)
	@ResponseBody
	public Result mobileSignIn(User user, String mobileCode) {
		Result res = new Result();
		if (StringUtils.isBlank(user.getMobile())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "必须指定", "手机号"));
			return res;
		}
		if (TimeUtils.checkOverTime("register")) {
			res.getError().add(buildError(ErrorConstants.MCODE_OVERTIME_ERROR, "手机验证码超时失效"));
			return res;
		}
		if (!TokenManager.getSession().getAttribute(VerifyCodeUtils.M_CODE).equals(mobileCode)) {
			res.getError().add(buildError(ErrorConstants.MCODE_ERROR, "手机验证码错误"));
			return res;
		}
		return res;
	}
	
	/**
	 * 登陆时查询未发送消息指定发送 
	 */
	private void sendMessageAfterLogin(){
		//更新 message_producer
		User u = TokenManager.getUserToken();
		if(u != null){
			List<MessageBo> boList = messageService.selectSyncMessage(u.getId()); 
			if(boList != null && boList.size()>0){
				List<MessageProducer> producers = new ArrayList<MessageProducer>();
				List<MessageConsumer> consumers = new ArrayList<MessageConsumer>();
				MessageProducer mp = null;
				MessageConsumer mc = null;
				Date date = new Date();
				for(MessageBo bo : boList){
					mp = new MessageProducer();
					mp.setId(bo.getId());
					mp.setSendTime(date);
					producers.add(mp);
					mc = new MessageConsumer();
					mc.setId(UUID.randomUUID().toString());
					mc.setConsumerId(TokenManager.getUserId());
					mc.setMessageId(bo.getMessageId());
					consumers.add(mc);
				}
				if(producers.size()>0)messageService.updateMessageProducer(producers);
				//新增 message_consumer
				if(consumers.size()>0)messageService.insertBatchConsumer(consumers);
			}
			messageService.updateJpushEasemobAccount(null, null, null,null);
		}
	}
}
