package com.wechat.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wechat.common.CommonHelper;
import com.wechat.common.Constants;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeCooperationMsg;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.requestDto.LoginByPasswordReq;
import com.wechat.model.requestDto.PositionSearchReq;
import com.wechat.model.requestDto.UserInfoDto;
import com.wechat.model.requestDto.UserInfoWithOpenidDto;
import com.wechat.model.responseDto.ResultEntity;
import com.wechat.service.CommonService;
import com.wechat.service.LoginService;

@Controller
@RequestMapping(value = "login")
public class LoginController  extends BaseController{

	@Autowired
	private LoginService loginService;
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private CommonHelper commonHelper;

	@Value("#{configProperties['enterprise.mail.activation.redirectUrl']}")
	private String redirectUrl;

	/**
	 * 用户登录
	 * @param loginReq
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<UserInfoDto> login(@RequestBody LoginByPasswordReq loginReq, HttpServletRequest req, HttpServletResponse resp) throws Exception {
		ResultEntity<UserInfoDto> rest = new ResultEntity<UserInfoDto>();
		
		// 验证身份
		if (loginReq != null && StringsUtils.isNotEmpty(commonHelper.getIRealIPAddr(req))) {

			//登陆信息验证
			ResultEntity<MdeUser> checkRest = loginService.checkPassword(loginReq);
			MdeUser mdeUser = checkRest.getResult();
			if(Constants.STR_OK.equals(checkRest.getCode()))
			{
				rest = loginService.login(mdeUser,loginReq,resp);
				//记录登陆历史
				commonService.addLoginHis(req,mdeUser.getUserCode());
			} else {
				rest.setCode(checkRest.getCode());
				rest.setMsg(checkRest.getMsg());
			}
		} else {
			rest.setMsg(InfoMsg.ERROR_LOGIN_MISS);
		}
		
		return rest;
	}

	/**
	 * 第三方登录
	 * 
	 * @param <T>
	 * 
	 * @param request
	 * @param response
	 *            return
	 */
	@RequestMapping(value = "loginByCode", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<UserInfoWithOpenidDto> loginByCode(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResultEntity<UserInfoWithOpenidDto> result = new ResultEntity<UserInfoWithOpenidDto>();
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String line;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		JSONObject jo = JSONObject.parseObject(sb.toString());

		// 获取授权code
		String code = jo.getString("code");
		if (StringsUtils.isEmpty(code)) {
			return new ResultEntity<>(InfoMsg.ERROR_AUZ_FAILED);
		}

		// 根据类型判断是微信登录还是领英 0.微信 1.领英
		String type = jo.getString("type");
		if (StringsUtils.isEmpty(type)) {
			return new ResultEntity<>(InfoMsg.ERROR_Type_MISS);
		}

		// 判断是pc端登录还是微信端登录
		String loginModel = jo.getString("loginModel");
		if (StringsUtils.isEmpty(loginModel)) {
			return new ResultEntity<>(InfoMsg.ERROR_LOGINMODEL_ERROR);
		}
		// 0.微信登录
		if ("0".equals(type)) {
			result = loginService.loginByWechatCode(request, response, code, loginModel);
			return result;
			// 领英登录
		} else {
			result = loginService.loginByLinkedInCode(request, response, code);
			return result;
		}
	}
	
	
	 /**
     * 解除绑定
     * 
     * @param <T>
     * 
     * @param request
     * @param response
     *            return
     */
    @RequestMapping(value = "unBinding", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity<UserInfoDto> unBinding(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ResultEntity<UserInfoDto> result = new ResultEntity<UserInfoDto>();
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        JSONObject jo = JSONObject.parseObject(sb.toString());

        // 获取授权code
        String code = jo.getString("code");
        if (StringsUtils.isEmpty(code)) {
            return new ResultEntity<>(InfoMsg.ERROR_AUZ_FAILED);
        }
        // 判断是pc端登录还是微信端登录
        String loginModel = jo.getString("loginModel");
        if (StringsUtils.isEmpty(loginModel)) {
            return new ResultEntity<>(InfoMsg.ERROR_LOGINMODEL_ERROR);
        }

        // 解除微信绑定
        result = loginService.unBindingWechatCode(code, loginModel);
        return result;

    }
	

	/**
	 * 第三方登录绑定账号
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "binding", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<UserInfoDto> binDingAccount(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		ServletInputStream inputStream = req.getInputStream();
		BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
		String line;
		StringBuilder builder = new StringBuilder();
		while ((line = buffer.readLine()) != null) {
			builder.append(line);
		}
		JSONObject jo = JSONObject.parseObject(builder.toString());
		ResultEntity<UserInfoDto> result = loginService.binDingAccount(req, resp, jo);
		return result;
	}

	/**
	 * 职位关键词搜索
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "searchJob", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String,Object>> searchJob(HttpServletRequest req, HttpServletResponse resp,
			@RequestBody PositionSearchReq searchReq) {
		return loginService.searchJob(searchReq);

	}

	/**
	 * 合作伙伴
	 * 
	 * @param resp
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = "cooperate", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> cooperate(HttpServletRequest req, HttpServletResponse resp,
			@RequestBody @Validated(value = MdeCooperationMsg.SaveGroup.class) MdeCooperationMsg mdeCooperationMsg) {
		String lang = commonService.getLanguage(req);
		InfoMsg infoMsg = loginService.cooperate(mdeCooperationMsg,lang);
		return new ResultEntity<>(infoMsg);
	}

	/**
	 * 企业用户 邮箱激活
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value = "activation")
	public void activationEnterprise(
			HttpServletRequest req, 
			HttpServletResponse resp,
			@RequestParam("userCode") String userCode, 
			@RequestParam("activationToken") String activationToken)
			throws IOException {
		loginService.activationEnterprise(activationToken, userCode, resp);
		resp.sendRedirect(redirectUrl);
	}

	/**
	 * 登录页初始化图片地址
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "getLoginInitImage", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<Map<String, Object>> getLoginInitImage(@RequestBody Map<String, String> param) {
		String type = param.get("type");
		return loginService.getLoginInitImage(type);
	}

}
