package com.wechat.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
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.wechat.common.CommonHelper;
import com.wechat.common.Constants;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeInterview;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.dto.WxBaseUserInfoDto;
import com.wechat.model.requestDto.LoginByPasswordReq;
import com.wechat.model.requestDto.LoginByPhoneReq;
import com.wechat.model.requestDto.UserInfoWithOpenidDto;
import com.wechat.model.responseDto.ResultEntity;
import com.wechat.model.responseDto.WxMiniCode2SessionResp;
import com.wechat.service.CommonService;
import com.wechat.service.InterviewService;
import com.wechat.service.LoginService;
import com.wechat.service.MdeUserService;
import com.wechat.service.WeiXinProgService;

import net.sf.json.JSONObject;

/**
* @author jadyn
* @version 创建时间：2020年7月17日 下午3:32:51
* 微信小程序
*/

@Controller
@RequestMapping(value = "wxMiniprog")
public class WxMiniprogController {
	
	protected static final Log log = LogFactory.getLog(WxMiniprogController.class);
	
	@Autowired
	private WeiXinProgService wxProgService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private LoginService loginService;

	@Autowired
	private MdeUserService mdeUserService;
	
	@Autowired
	private InterviewService intvService;
	
	@Autowired
	private CommonHelper commonHelper;

	
	/**
	 * 小程序登陆
     * 
     * @param 
     * @return
     */
    @RequestMapping(value = "wxMiniLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity<UserInfoWithOpenidDto> wxMiniLogin(@RequestParam String jscode, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ResultEntity<UserInfoWithOpenidDto> restEnty = new ResultEntity<UserInfoWithOpenidDto>();
    	UserInfoWithOpenidDto userDto = new UserInfoWithOpenidDto();
    	//获取当前用户信息
    	WxMiniCode2SessionResp wxResp = wxProgService.getJscodeToSession(jscode);
    	if(StringsUtils.isEmpty(wxResp.getOpenid()))
    	{
    		//调用小程序登陆出错
    		log.error("**************调用小程序登陆出错【jscode2session】【"+wxResp.getErrmsg()+"】*********************"); 
    		restEnty.setMsg(InfoMsg.ERROR_AUZ_FAILED);
    	} else if(StringsUtils.isEmpty(wxResp.getUnionid())){
    		//unionid为空说明没有关注
    		restEnty.setMsg(InfoMsg.ERROR_UN_SUBSCRIBE);
    	} else {
    		// 根据UnionId查询用户
    		MdeUser mdeUser = mdeUserService.findByUnionId(wxResp.getUnionid());
    		
    		//session存储
    		WxBaseUserInfoDto rdsBUInfo = new WxBaseUserInfoDto();
    		rdsBUInfo.setOpenId(wxResp.getOpenid());
    		rdsBUInfo.setSessionKey(wxResp.getSession_key());
    		rdsBUInfo.setUnionId(wxResp.getUnionid());
    		if(mdeUser != null)
    		{
        		rdsBUInfo.setUserCode(mdeUser.getUserCode());
        		rdsBUInfo.setIdentityFlag(mdeUser.getIdentityFlag());
    		}
    		wxProgService.setSessionKey(rdsBUInfo);
    		
    		//调用微信登陆
    		restEnty = loginService.loginByWechatBase(response,wxResp.getUnionid(), "", wxResp.getOpenid(),"1",mdeUser);
    		if (InfoMsg.SUCCESS_REQUEST.getCode().equals(restEnty.getCode())) {
				//正常处理的场合
				userDto = restEnty.getResult();
				userDto.setOpenIdMini(wxResp.getOpenid());// 手机端登录存储 （微信模板信息推送需要）
				//记录登陆历史
				commonService.addLoginHis(request,userDto.getUserCode());
			} else if(InfoMsg.ERROR_BINDING_ERROR.getCode().equals(restEnty.getCode())){
				//未绑定的情况下
				userDto.setOpenIdMini(wxResp.getOpenid());// 手机端登录存储 （微信模板信息推送需要）
				restEnty.setResult(userDto);
			}
    	}

    	return restEnty;
    }
    
    
    /**
	 * 通过微信小程序 手机号登陆
     * 
     * @param 
     * @return
     */
    @RequestMapping(value = "loginByPhone", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity<UserInfoWithOpenidDto> loginByPhone(@RequestBody @Valid LoginByPhoneReq req, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ResultEntity<UserInfoWithOpenidDto> restEnty = new ResultEntity<UserInfoWithOpenidDto>();
    	UserInfoWithOpenidDto userDto = new UserInfoWithOpenidDto();
    	
    	//缓存中获取openid等信息
    	WxBaseUserInfoDto sessionInfo = wxProgService.getSessionKey(req.getOpenId());
    	if(sessionInfo != null)
    	{
    		//通过微信小程序解码获得手机号
    		JSONObject phoneJson = wxProgService.getDecodeInfo(sessionInfo.getSessionKey(), req.getEncryptedData(), req.getIv());
    		if(phoneJson != null) {
    			// 根据手机号查询用户
        		MdeUser mdeUser = mdeUserService.findByUserName(phoneJson.get("phoneNumber").toString());
        		if(mdeUser == null) {
        			restEnty.setMsg(InfoMsg.ERROR_PERSON_USER_NOTEXIST);
        		} else {
        			mdeUser.setOpenIdMini(sessionInfo.getOpenId());
            		mdeUser.setUnionId(sessionInfo.getUnionId());
            		//调用微信登陆
            		restEnty = loginService.loginByWechatBase(response,sessionInfo.getUnionId(), "", sessionInfo.getOpenId(),"1",mdeUser);
            		if (InfoMsg.SUCCESS_REQUEST.getCode().equals(restEnty.getCode())) {
        				//正常处理的场合
        				userDto = restEnty.getResult();
        				//记录登陆历史
        				commonService.addLoginHis(request,userDto.getUserCode());
        			}
            		//session存储
            		sessionInfo.setUserCode(mdeUser.getUserCode());
            		sessionInfo.setIdentityFlag(mdeUser.getIdentityFlag());
            		wxProgService.setSessionKey(sessionInfo);
        		}
    		} else {
    			restEnty.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
    		}
    	} else {
       		//调用小程序登陆出错
    		log.error("**************小程序未登录*********************"); 
    		restEnty.setMsg(InfoMsg.ERROR_AUZ_FAILED);
    	}

    	return restEnty;
    }
    

    /**
	 * 通过账号密码登录（小程序）
     * 
     * @param 
     * @return
     */
    @RequestMapping(value = "loginByPassword", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity<UserInfoWithOpenidDto> loginByPassword(@RequestBody @Valid LoginByPasswordReq loginReq, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ResultEntity<UserInfoWithOpenidDto> restEnty = new ResultEntity<UserInfoWithOpenidDto>();
    	UserInfoWithOpenidDto userDto = new UserInfoWithOpenidDto();

		// 验证身份
		if (loginReq != null && StringsUtils.isNotEmpty(commonHelper.getIRealIPAddr(request))) {
	    	//缓存中获取openid等信息
	    	WxBaseUserInfoDto sessionInfo = wxProgService.getSessionKey(loginReq.getOpenId());
	    	if(sessionInfo != null)
	    	{
	    		//登陆信息验证
				ResultEntity<MdeUser> checkRest = loginService.checkPassword(loginReq);
				MdeUser mdeUser = checkRest.getResult();
				if(Constants.STR_OK.equals(checkRest.getCode()))
				{
					mdeUser.setOpenIdMini(sessionInfo.getOpenId());
	        		mdeUser.setUnionId(sessionInfo.getUnionId());
	        		//调用微信登陆
	        		restEnty = loginService.loginByWechatBase(response,sessionInfo.getUnionId(), "", sessionInfo.getOpenId(),"1",mdeUser);
	        		if (InfoMsg.SUCCESS_REQUEST.getCode().equals(restEnty.getCode())) {
	    				//正常处理的场合
	    				userDto = restEnty.getResult();
	    				//记录登陆历史
	    				commonService.addLoginHis(request,userDto.getUserCode());
	    				
	    				//session存储
	            		sessionInfo.setUserCode(mdeUser.getUserCode());
	            		sessionInfo.setIdentityFlag(mdeUser.getIdentityFlag());
	            		wxProgService.setSessionKey(sessionInfo);
	    			}
				} else {
					restEnty.setCode(checkRest.getCode());
					restEnty.setMsg(checkRest.getMsg());
				}
	    	} else {
	    		//调用小程序登陆出错
	    		log.error("**************小程序未登录*********************"); 
	    		restEnty.setMsg(InfoMsg.ERROR_AUZ_FAILED);
	    	}
		} else {
			restEnty.setMsg(InfoMsg.ERROR_LOGIN_MISS);
		}
		
		return restEnty;
    }


    /**
	 * 验证视频用户权限
     * 
     * @param 
     * @return
     */
    @RequestMapping(value = "checkVUserRight", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity<String> checkVUserRight(@RequestParam String roomId, HttpServletRequest request) {
    	ResultEntity<String> restEnty = new ResultEntity<String>(InfoMsg.ERROR_JOIN_VIDEO_ROOM);
    	String userSin = "";
    	//获取当前登录用户
    	String userCode = commonService.getUserCode(request);
    	String identityFlg = commonService.getIdentityFlag(request);
    	
    	if(!StringsUtils.anyIsEmpty(roomId,userCode,identityFlg))
    	{
    		//检查用户是否和房间号相匹配
    		MdeInterview intv = intvService.getIntvInfoByKey(roomId,userCode,identityFlg);
    		if(intv != null && intv.getIntvId() != null) {
    			restEnty.setMsg(InfoMsg.SUCCESS_REQUEST);
    			//获取用户签名
    			userSin = wxProgService.getVideoUserSig(userCode);
    			if(StringsUtils.isEmpty(userSin))
    			{
    				restEnty.setMsg(InfoMsg.ERROR_SYSTEM_ERROR);
    				log.error("**********************视频用户签名出错：roomid【"+roomId+"】usercode【"+userCode+"】*******************************");
    			}
    		}
    	} 
		restEnty.setResult(userSin);
		return restEnty;
    }
    
}
