package com.zjrs.ggfw.dzsbk.bpo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yinhai.bcpcs.BcpRequest;
import com.yinhai.bcpcs.BcpResponse;
import com.yinhai.bcpcs.DefaultBcpClient;
import com.yinhai.bcpcs.IBcpClient;
import com.yinhai.bcpcs.profile.DefaultProfile;
import com.yinhai.bcpcs.profile.IClientProfile;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.bpo.impl.BPOImpl;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.util.SecurityUtils;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import com.zjrs.ggfw.dzsbk.blo.SignBLO;
import com.zjrs.ggfw.dzsbk.bpo.SignBPO;
import com.zjrs.ggfw.dzsbk.dto.*;
import com.zjrs.ggfw.dzsbk.entity.RsInterfaceLogMapper;
import com.zjrs.ggfw.dzsbk.po.RsInterfaceLog;
import com.zjrs.ggfw.dzsbk.po.VRsDzsbkQf;
import com.zjrs.ggfw.dzsbk.util.*;
import com.zjrs.ggfw.portal.blo.CommBLO;
import com.zjrs.ggfw.portal.blo.UserBLO;
import com.zjrs.ggfw.portal.po.VRsGgfwUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

@Service
public class SignBPOImpl extends BPOImpl implements SignBPO {
	
	private static final Logger LOG = LoggerFactory.getLogger(SignBPOImpl.class);
	
	@Value("${wxgzh.access_token_url:https://api.weixin.qq.com/sns/oauth2/access_token}")
	private String wxgzhAccessTokenUrl;//微信网页授权url
	
	@Value("${wxgzh.access_token_check_url:https://api.weixin.qq.com/sns/auth}")
	private String wxgzhAccessTokenCheckUrl;//微信检验授权凭证url
	
	@Value("${wxgzh.appid:wx3f88bb50c9e0ac64}")
	private String wxgzhAppid;//微信公众号ID
	
	@Value("${wxgzh.secret:6af9a1c4cf1a50824b34165102b25710}")
	private String wxgzhSecret;//微信公众号密码
	
	@Value("${wxgzh.publicKey:xxxxxxxxxxxxxxxxx}")
	private String wxgzhPublicKey;//公钥
	
	@Value("${wxgzh.privateKey:xxxxxxxxxxxxxxxx}")
	private String wxgzhPrivateKey;//私钥
	
	@Value("${dzsbk.signInfoUrl:https://test-ssc.mohrss.gov.cn/CSB/ecard}")
	private String signInfoUrl;//领卡查询

	@Value("${dzsbk.checkMaxNum:10}")
	private String checkMaxNum;//每天认证最大次数

	@Value("${sggfw.url:http://www.gdhrss.nwmh/bcp}")
	private String url;
	
	@Autowired
    private SelfServicePropertyDTO selfServicePropertyDTO;
	
	@Autowired
	MiniProgramPropertyDTO miniProgramPropertyDTO;

	@Autowired
	RealNameAuthPropertyDTO realNameAuthPropertyDTO;

	@Resource
    private UserBLO userBLO;
	
	@Resource
    private SignBLO signBLO;

	@Resource
	RsInterfaceLogMapper rsInterfaceLogMapper;

	@Resource
	CommBLO commBLO;
	
	@Override
	public AjaxResponse getZzzdSignature(SignDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		//获取自助终端属性
		PropertyDTO propertyDTO = new PropertyDTO();
		BeanUtils.copyProperties(selfServicePropertyDTO,propertyDTO);
		//获取签名
		try {
			String sign = SignUtils.sign(propertyDTO, dto);
			ajaxResponse.setData("sign", sign);
		} catch (Exception e) {
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getZzzdDzsbkUser(SecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		String security = AESUtils.decrypt(dto.getSecurity(), selfServicePropertyDTO.getDk());
		JSONObject jsonObject = JSONObject.parseObject(security);
		ajaxResponse.setData("data", jsonObject);
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getMiniRsDzsbkQf() {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		//获取当前用户
    	CurrentUser cUser = SecurityUtils.getCurrentUser();
		VRsDzsbkQf vRsDzsbkQf = signBLO.getRsDzsbkQf(cUser.getUsername(), miniProgramPropertyDTO.getChannelNo());
		if(vRsDzsbkQf == null) {
			//从用户表默认信息
			VRsGgfwUser vRsGgfwUser = userBLO.getVRsGgfwUser(cUser.getUsername());
			vRsDzsbkQf = new VRsDzsbkQf();
			vRsDzsbkQf.setAac003(vRsGgfwUser.getMc());
			//若为身份证，则默认社会保障号为身份证号
			if("01".equals(vRsGgfwUser.getZjlx())) {
				vRsDzsbkQf.setAac002(vRsGgfwUser.getZjhm());
			}
		}
		ajaxResponse.setData("data", vRsDzsbkQf);
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getMiniSignature(SignDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		//参数校验
		if(StringUtils.isBlank(dto.getIsWeb()) && StringUtils.isBlank(dto.getIsWebView())) {
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("isWeb与isWebView两者必传一项！");
            return ajaxResponse;
		}
		
		//获取小程序属性
		PropertyDTO propertyDTO = new PropertyDTO();
		BeanUtils.copyProperties(miniProgramPropertyDTO,propertyDTO);
		//获取签名
		try {
			String sign = SignUtils.sign(propertyDTO, dto);
			ajaxResponse.setData("sign", sign);
		} catch (Exception e) {
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse saveMiniDzsbkUser(MiniProgramQfUserDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		//获取当前用户
    	CurrentUser cUser = SecurityUtils.getCurrentUser();
		VRsDzsbkQf vRsDzsbkQf = signBLO.getRsDzsbkQf(cUser.getUsername(), miniProgramPropertyDTO.getChannelNo());
		if(vRsDzsbkQf == null) {
			vRsDzsbkQf = new VRsDzsbkQf();
			vRsDzsbkQf.setUserid(cUser.getUsername());
			vRsDzsbkQf.setChannelNo(miniProgramPropertyDTO.getChannelNo());
		}
		vRsDzsbkQf.setAac002(dto.getAac002());
		vRsDzsbkQf.setAac003(dto.getAac003());
		signBLO.saveRsDzsbkQf(vRsDzsbkQf);
		
		ajaxResponse.setData("data", vRsDzsbkQf);
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse saveMiniSignNo(SecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		
		String security = AESUtils.decrypt(dto.getSecurity(), miniProgramPropertyDTO.getDk());
		JSONObject jsonObject = JSONObject.parseObject(security);
		//获取result用户信息
		JSONObject resultObject = JSONObject.parseObject((String) jsonObject.get("result"));
		//获取当前用户
    	CurrentUser cUser = SecurityUtils.getCurrentUser();
		VRsDzsbkQf vRsDzsbkQf = signBLO.getRsDzsbkQf(cUser.getUsername(), miniProgramPropertyDTO.getChannelNo());
		
		vRsDzsbkQf.setAab301(resultObject.getString("aab301"));
		vRsDzsbkQf.setSignNo(resultObject.getString("signNo"));
		vRsDzsbkQf.setSignDate(resultObject.getString("signDate"));
		signBLO.saveRsDzsbkQf(vRsDzsbkQf);		
		ajaxResponse.setData("data", vRsDzsbkQf);
		
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getWeChatDzsbkQf(WeChatQueryQfDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("getWeChatDzsbkQf");
		rsInterfaceLog.setParamIn(dto.getCode());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//获取微信openid、access_token
			Map<String, Object> params = new HashMap<String, Object>(); 
			params.put("appid", wxgzhAppid);
			params.put("secret", wxgzhSecret);
			params.put("grant_type", "authorization_code");
			String result = HttpUtils.doGet(wxgzhAccessTokenUrl, params);
			if(StringUtils.isNotBlank(result)) {
				JSONObject resultObject = JSON.parseObject(result);
				if(resultObject.containsKey("openid")) {
					//返回用户签发信息
					JSONObject jsonUser = new JSONObject();
					jsonUser.put("openid", resultObject.getString("openid"));
					jsonUser.put("accessToken", resultObject.getString("access_token"));
					//查询用户签发信息
					VRsDzsbkQf vRsDzsbkQf = signBLO.getWeChatRsDzsbkQf(resultObject.getString("openid"), miniProgramPropertyDTO.getChannelNo());
					if(vRsDzsbkQf != null) {
						jsonUser.put("realTime", vRsDzsbkQf.getRealTime());
						//查询证件类型、证件号码
						VRsGgfwUser vRsGgfwUser = userBLO.getVRsGgfwUser(vRsDzsbkQf.getUserid());
						//本地已签发数据，实时查询是否一致
						if(StringUtils.isNotBlank(vRsDzsbkQf.getSignNo())) {
							JSONObject jsonData = new JSONObject();
							jsonData.put("aab301", vRsDzsbkQf.getAab301());
							jsonData.put("aac002", vRsDzsbkQf.getAac002());
							jsonData.put("aac003", vRsDzsbkQf.getAac003());

						}
					}
					//加密出参
					String user = RSAUtils.encrypt(jsonUser.toJSONString(), wxgzhPublicKey);
					ajaxResponse.setData("data", user);
					rsInterfaceLog.setStatus("1");//成功
				}else {
					rsInterfaceLog.setMsg("授权code无效！");
					ajaxResponse.setAppcode("1");
		            ajaxResponse.setErrorMsg("授权code无效！");
				}
			}else {
				rsInterfaceLog.setMsg("微信接口异常");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("微信接口异常");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse saveWeChatDzsbkUser(SecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		String dqsj = this.commBLO.getCurrenttime();//当前时间
		dqsj = dqsj.substring(0,10);
		LOG.info("---now time="+dqsj);

		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("saveWeChatDzsbkUser");
		rsInterfaceLog.setParamIn(dto.getSecurity());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//解密入参
			String userStr = RSAUtils.decrypt(dto.getSecurity(), wxgzhPrivateKey);
			rsInterfaceLog.setParamIn(userStr);
			JSONObject userObject = JSON.parseObject(userStr);
			String zjhm=userObject.getString("aac147");
			rsInterfaceLog.setUserid(zjhm);
			LOG.info("证件号码："+zjhm);

			//认证次数是否超过每天上限
			QueryWrapper<RsInterfaceLog> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("userid", zjhm);//用户ID
			queryWrapper.eq("interface_Name", "saveWeChatDzsbkUser");//接口名称
			queryWrapper.likeRight("create_Time",dqsj);
			int cnt = rsInterfaceLogMapper.selectCount(queryWrapper);
			LOG.info("zjhm:"+zjhm+",今天已认证次数："+cnt);
			LOG.info("每人每天认证次数："+checkMaxNum);
			if(cnt>Integer.parseInt(checkMaxNum)){
				LOG.info("---above max num---");
				ajaxResponse.setAppcode("1");
				ajaxResponse.setErrorMsg("很抱歉，认证次数已超出限制，请明天再试！");
				return ajaxResponse;
			}

			//校验微信授权token是否有效
			if(checkWeChatToken(userObject.getString("openid"),userObject.getString("accessToken"))) {
				//获取微信实名认证授权信息
				RealNameAuthDTO realNameAuthDTO = getRealNameAuthToken(userObject.getString("aac003"), userObject.getString("aac147"));
				
				//保存用户表信息(切换身份证信息)
				VRsGgfwUser vRsGgfwUser = new VRsGgfwUser();
				vRsGgfwUser.setFwdx("1");//个人
				DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		    	String czsj = LocalDateTime.now().format(formatters);//获取当前时间
		    	vRsGgfwUser.setCjsj(czsj);
				vRsGgfwUser = signBLO.saveRsGgfwUser(vRsGgfwUser);
				//保存签发表信息
				VRsDzsbkQf vRsDzsbkQf = signBLO.getWeChatRsDzsbkQf(userObject.getString("openid"), miniProgramPropertyDTO.getChannelNo());
				if(vRsDzsbkQf == null) {
					vRsDzsbkQf = new VRsDzsbkQf();
				}
				vRsDzsbkQf.setUserid(vRsGgfwUser.getUserid());
				vRsDzsbkQf.setAac003(userObject.getString("aac003"));
				vRsDzsbkQf.setAac002(userObject.getString("aac002"));
				vRsDzsbkQf.setAab301("440800");
				vRsDzsbkQf.setAuthToken(realNameAuthDTO.getAuthToken());
				vRsDzsbkQf.setRealTime("");//清空实名时间，防止切换证件信息
				signBLO.saveRsDzsbkQf(vRsDzsbkQf);
				
				ajaxResponse.setData("data", realNameAuthDTO);
				rsInterfaceLog.setStatus("1");//成功
			}else {
				rsInterfaceLog.setMsg("微信授权超时！");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("微信授权超时！");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getWeChatSignature(SecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse(); 
		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("getWeChatSignature");
		rsInterfaceLog.setParamIn(dto.getSecurity());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//解密入参
			String userStr = RSAUtils.decrypt(dto.getSecurity(), wxgzhPrivateKey);
			rsInterfaceLog.setParamIn(userStr);
			JSONObject userObject = JSON.parseObject(userStr);
			//校验微信授权token是否有效
			if(checkWeChatToken(userObject.getString("openid"),userObject.getString("accessToken"))) {
				//获取签名，组装入参
				SignDTO signDTO = new SignDTO();
				if(userObject.containsKey("aab301")) {
					signDTO.setAab301(userObject.getString("aab301"));
				}
				if(userObject.containsKey("aac067")) {
					signDTO.setAac067(userObject.getString("aac067"));
				}
				if(userObject.containsKey("isWeb")) {
					signDTO.setIsWeb(userObject.getString("isWeb"));
				}else if(userObject.containsKey("isWebView")) {
					signDTO.setIsWebView(userObject.getString("isWebView"));
				}
				if(userObject.containsKey("isIndep")) {
					signDTO.setIsIndep(userObject.getString("isIndep"));
				}
				if(userObject.containsKey("isAuthFace")) {
					signDTO.setIsAuthFace(userObject.getString("isAuthFace"));
				}
				if(userObject.containsKey("systemName")) {
					signDTO.setSystemName(userObject.getString("systemName"));
				}
				//获取签名
				ajaxResponse = getMiniSignature(signDTO);
				rsInterfaceLog.setStatus("1");//成功
			}else {
				rsInterfaceLog.setMsg("微信授权超时！");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("微信授权超时！");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse saveWeChatSignNo(WeChatSecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("saveWeChatSignNo");
		rsInterfaceLog.setParamIn(dto.getSfxx());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//解密入参
			String userStr = RSAUtils.decrypt(dto.getSfxx(), wxgzhPrivateKey);
			JSONObject userObject = JSON.parseObject(userStr);
			//校验微信授权token是否有效
			if(checkWeChatToken(userObject.getString("openid"),userObject.getString("accessToken"))) {
				//解析电子社保卡签发用户信息串
				String security = AESUtils.decrypt(dto.getSecurity(), miniProgramPropertyDTO.getDk());
				rsInterfaceLog.setParamIn(userStr+";"+security);
				JSONObject jsonObject = JSONObject.parseObject(security);
				//获取result用户信息
				JSONObject resultObject = JSONObject.parseObject((String) jsonObject.get("result"));
				
				//查询是否已保存用户信息
				VRsDzsbkQf vRsDzsbkQf = signBLO.getWeChatRsDzsbkQf(userObject.getString("openid"), miniProgramPropertyDTO.getChannelNo());
				if(vRsDzsbkQf == null) {
					//保存用户表信息
					VRsGgfwUser vRsGgfwUser = new VRsGgfwUser();
					vRsGgfwUser.setFwdx("1");//个人
					DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			    	String czsj = LocalDateTime.now().format(formatters);//获取当前时间
			    	vRsGgfwUser.setCjsj(czsj);
					vRsGgfwUser = signBLO.saveRsGgfwUser(vRsGgfwUser);
					//保存签发表信息
					vRsDzsbkQf = new VRsDzsbkQf();
					vRsDzsbkQf.setUserid(vRsGgfwUser.getUserid());
					vRsDzsbkQf.setAac003(userObject.getString("aac003"));
					vRsDzsbkQf.setAac002(userObject.getString("aac002"));
					vRsDzsbkQf.setOpenid(userObject.getString("openid"));
				}
				vRsDzsbkQf.setAab301(resultObject.getString("aab301"));
				//保存用户信息
				signBLO.saveRsDzsbkQf(vRsDzsbkQf);
				
				//加密信息返回
				userObject.put("signNo", resultObject.getString("signNo"));
				String user = RSAUtils.encrypt(userObject.toJSONString(), wxgzhPublicKey);
				ajaxResponse.setData("data", user);
				rsInterfaceLog.setStatus("1");//成功
			}else {
				rsInterfaceLog.setMsg("微信授权超时！");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("微信授权超时！");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse removeWeChatSignNo(WeChatSecurityDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("saveWeChatSignNo");
		rsInterfaceLog.setParamIn(dto.getSfxx());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//解密入参
			String userStr = RSAUtils.decrypt(dto.getSfxx(), wxgzhPrivateKey);
			JSONObject userObject = JSON.parseObject(userStr);
			//校验微信授权token是否有效
			if(checkWeChatToken(userObject.getString("openid"),userObject.getString("accessToken"))) {
				//解析电子社保卡签发用户信息串
				String security = AESUtils.decrypt(dto.getSecurity(), miniProgramPropertyDTO.getDk());
				rsInterfaceLog.setParamIn(userStr+";"+security);
				JSONObject jsonObject = JSONObject.parseObject(security);
				//获取result用户信息
				JSONObject resultObject = JSONObject.parseObject((String) jsonObject.get("result"));
				//解绑
				if("002".equals(resultObject.getString("actionType")) 
						|| StringUtils.isBlank(resultObject.getString("signNo"))) {
					//查询电子社保卡签发信息
					VRsDzsbkQf vRsDzsbkQf = signBLO.getWeChatRsDzsbkQf(userObject.getString("openid"), miniProgramPropertyDTO.getChannelNo());
					if(vRsDzsbkQf != null) {
						vRsDzsbkQf.setSignNo("");
						vRsDzsbkQf.setSignDate("");
					}
					//加密信息返回
					userObject.put("signNo", "");
					String user = RSAUtils.encrypt(userObject.toJSONString(), wxgzhPublicKey);
					ajaxResponse.setData("data", user);
					rsInterfaceLog.setStatus("1");//成功
				}else {
					rsInterfaceLog.setMsg("电子社保卡解除绑定失败！");
					ajaxResponse.setAppcode("1");
		            ajaxResponse.setErrorMsg("电子社保卡解除绑定失败！");
				}
			}else {
				rsInterfaceLog.setMsg("微信授权超时！");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("微信授权超时！");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	@Override
	public AjaxResponse getWeChatRealName(RealNameAuthDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();
		//记录调用日志
		RsInterfaceLog rsInterfaceLog = new RsInterfaceLog();
		rsInterfaceLog.setInterfaceName("getWeChatRealName");
		rsInterfaceLog.setParamIn(dto.getAuthToken());
		rsInterfaceLog.setStatus("0");//默认失败
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		try {
			//获取身份信息
			VRsDzsbkQf vRsDzsbkQf = signBLO.getWeChatRsDzsbkQfByAuth(dto.getAuthToken());
			if(vRsDzsbkQf != null) {
				//返回用户签发信息
				JSONObject jsonUser = new JSONObject();
				jsonUser.put("openid", vRsDzsbkQf.getOpenid());
				jsonUser.put("accessToken", vRsDzsbkQf.getAccessToken());
				jsonUser.put("realTime", vRsDzsbkQf.getRealTime());
				//查询证件类型、证件号码
				VRsGgfwUser vRsGgfwUser = userBLO.getVRsGgfwUser(vRsDzsbkQf.getUserid());
				jsonUser.put("aac058", vRsGgfwUser.getZjlx());
				
				//本地已签发数据，实时查询是否一致
				JSONObject jsonData = new JSONObject();
				jsonData.put("channelNo", miniProgramPropertyDTO.getChannelNo());//渠道号
				jsonData.put("aab301", vRsDzsbkQf.getAab301());
				//领卡查询验证是否已在电子社保卡解绑
				String signInfo = signInfoUtils.getSignInfo(signInfoUrl, miniProgramPropertyDTO.getAk(), miniProgramPropertyDTO.getSk(), jsonData.toJSONString());
				LOG.info("========getWeChatRealName,signInfo:"+signInfo);
				//解析参数，防止签发成功，但是本地未保存成功
				String signNo = "";
				if(StringUtils.isNotBlank(signInfo)) {
					JSONObject retJson=JSON.parseObject(signInfo);//返回的json对象
					if("000001".equals(retJson.getString("msgCode"))){//返回成功
						JSONObject resultJson = retJson.getJSONObject("result");
						signNo = (String)resultJson.get("signNo");//签发号
						jsonUser.put("signNo", signNo);
					}
				}
				vRsDzsbkQf.setAab301("440800");
				vRsDzsbkQf.setSignNo(signNo);
				
				//获取微信实名认证结果
				Map<String, String> result = getRealNameAuthResult(dto.getAuthToken());
				//保存认证时间
				if(result != null && result.containsKey("ResultType") && "0".equals(result.get("ResultType"))) {
					DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			    	String czsj = LocalDateTime.now().format(formatters);//获取当前时间
			    	vRsDzsbkQf.setRealTime(czsj);
				}
				//保存签发表信息
				signBLO.saveRsDzsbkQf(vRsDzsbkQf);
				
				//加密出参
				rsInterfaceLog.setStatus("1");//成功
			}else {
				rsInterfaceLog.setMsg("未查询到对应用户信息！");
				ajaxResponse.setAppcode("1");
	            ajaxResponse.setErrorMsg("未查询到对应用户信息！");
			}
		} catch (Exception e) {
			rsInterfaceLog.setMsg("系统异常");
			ajaxResponse.setAppcode("1");
            ajaxResponse.setErrorMsg("系统异常");
			LOG.error("系统异常：", e);
		}
		signBLO.saveRsInterfaceLog(rsInterfaceLog);
		return ajaxResponse;
	}
	
	private boolean checkWeChatToken(String openid,String accessToken) {
		boolean isValid = false;
		try {
			//校验微信授权token是否有效
			Map<String, Object> params = new HashMap<String, Object>(); 
			params.put("openid", openid);
			String result = HttpUtils.doGet(wxgzhAccessTokenCheckUrl, params);
			if(StringUtils.isNotBlank(result)) {
				JSONObject resultObject = JSON.parseObject(result);
				if("0".equals(resultObject.getString("errcode"))) {
					isValid = true;
				}
			}
		} catch (Exception e) {
			LOG.error("系统异常：", e);
		}
		return isValid;
	}

	/**
	 * 获取微信实名认证授权信息
	 * @param name 姓名
	 * @param idCard 身份证
	 * @return RealNameAuthDTO
	 * @throws Exception
	 */
	public RealNameAuthDTO getRealNameAuthToken(String name, String idCard) throws Exception {
		RealNameAuthDTO result = new RealNameAuthDTO();
		// TreeMap可以自动排序
		TreeMap<String, Object> params = new TreeMap<>();
		params.put("Action", "GetRealNameAuthToken");
		params.put("Version", "2018-03-01");
		params.put("Name", name);
		params.put("IDCard", idCard);

		String url = "faceid.tencentcloudapi.com/";
		String method = "GET";

		String reqUrl = getRealNameReqUrl(params, url, method);

		String resp = HttpUtils.doGet(reqUrl, null);
		if(StringUtils.isNotBlank(resp)) {
			JSONObject resultObject = JSON.parseObject(resp);
			result = JSON.parseObject(resultObject.getString("Response"), RealNameAuthDTO.class);
		}
		return result;
	}

	/**
	 * 获取微信实名认证结果
	 * @param authToken 实名认证凭证
	 * @return {
	 *     "RequestId": 唯一请求 ID,
	 *     "ResultType": 认证结果码 0: 姓名和身份证号一致
	 * 							-1: 姓名和身份证号不一致
	 * 							-2: 姓名和微信实名姓名不一致
	 * 							-3: 微信号未实名
	 *   }
	 * @throws Exception
	 */
	public Map<String, String> getRealNameAuthResult(String authToken) throws Exception {
		Map<String, String> result = new HashMap<>();

		TreeMap<String, Object> params = new TreeMap<>();
		params.put("Action", "GetRealNameAuthResult");
		params.put("Version", "2018-03-01");
		params.put("AuthToken", authToken);

		String url = "faceid.tencentcloudapi.com/";
		String method = "GET";

		String reqUrl = getRealNameReqUrl(params, url, method);

		String resp = HttpUtils.doGet(reqUrl, null);
		if(StringUtils.isNotBlank(resp)) {
			JSONObject resultObject = JSON.parseObject(resp);
			result = JSON.parseObject(resultObject.getString("Response"), Map.class);
		}
		return result;
	}

	/**
	 * 设置公共参数，并获取实名认证请求地址
	 * @param params 接口业务入参
	 * @param url 请求域名地址
	 * @param method 请求方法
	 * @return 实际请求接口
	 * @throws Exception
	 */
	private String getRealNameReqUrl(TreeMap<String, Object> params, String url, String method) throws Exception {
		// 设置公共参数
		params.put("Timestamp", System.currentTimeMillis() / 1000);
		params.put("Nonce", new Random().nextInt(Integer.MAX_VALUE));
		params.put("SecretId", realNameAuthPropertyDTO.getSecretId());
		String signString = SignRealNameAuthUtils.getStringToSign(params, method, url);
		params.put("Signature", SignRealNameAuthUtils.sign(signString, realNameAuthPropertyDTO.getSecretKey(), "HmacSHA1"));

		return SignRealNameAuthUtils.getUrl(params, url);
	}
	@Override
	public AjaxResponse getUserByEsscNo(EsscnoDTO dto) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		Map<String, String> data = new HashMap<>();
		try {
			data = this.digitalCard(dto);
			ajaxResponse.setMsg(data.get("msg"));
			ajaxResponse.setAppcode(data.get("flag"));
		} catch (Exception e) {
			LOG.info("解析电子社保卡二维码，接口异常");
			e.printStackTrace();
		}
		return ajaxResponse;
	}

	private Map<String, String> digitalCard(EsscnoDTO dto) throws Exception {
		Map<String, String> map = new HashMap<>();
		map.put("businessType", "2601");
		map.put("businessTypeDesc", "解析电子社保卡二维码");
		Map<String, String> param = new HashMap<>();
		param.put("qrCode", dto.getEsscno());
		param.put("systemName", "湛江智慧人社综合服务平台");
		param.put("busiType", "01");
		map.put("businessParam", JSONObject.toJSONString(param));
		LOG.info(JSONObject.toJSONString(param));
		return callHttp(url, "zj_zhrsfw", "esscQrcodeValid", true, "certification_zj_zhrsfw.keystore", new Object[]{map});
	}

	/**
	 * getProfile方法参数顺序
	 *
	 * @param url         协同平台对外IP或域名（只暴露80端口）
	 * @param projectCode 接入系统标识key
	 * @param serviceCode 对外服务标识key
	 * @param isHttp      是否调用http接口，false为调用交易平台接口
	 * @param keyName     证书
	 * @param obj         请求数据
	 * @throws Exception
	 */
	private Map<String, String> callHttp(String url, String projectCode, String serviceCode, boolean isHttp, String keyName, Object obj) throws Exception {
		Map<String, String> resultMap = new HashMap<>();
		resultMap.put("flag","0");
		BcpRequest request = new BcpRequest();
		request.setInput(obj);
		IClientProfile profile = DefaultProfile.getProfile(url, projectCode, serviceCode, isHttp, keyName);
		//创建client
		IBcpClient client = new DefaultBcpClient(profile, request);
		//获取返回对象，通过泛型指定结果类型
		BcpResponse<String> response = client.getResponse(String.class);
		// 获取调用成功标识
		boolean isInvokeSuccess = response.isInvokeSuccess();

		String data = "";
		if (isInvokeSuccess) {
			// 获取服务返回的业务数据
			// 具体类型取决于服务的返回类型
			data = response.getInvokeData();
			LOG.info("接口返回成功："+data);
			JSONObject dataJson = JSONObject.parseObject(data);
			if(dataJson.getBoolean("bizSuccess")){
				JSONObject rJson = JSONObject.parseObject(dataJson.getString("data"));
				String aac002 = rJson.getString("aac002");
				resultMap.put("flag","0");
				resultMap.put("msg",aac002);
			}else{
				String message = dataJson.getString("message");
				resultMap.put("flag","1");
				resultMap.put("msg",message);
			}

		} else {
			//获取调用错误信息
			String errorMsg = response.getErrorMessage();
			LOG.info("接口返回失败："+errorMsg);
			resultMap.put("flag","1");
			resultMap.put("msg",errorMsg);
		}

		return resultMap;
	}

}