package com.bcxin.ins.service.user.impl;

import com.bcxin.ins.dao.user.ClientUserDao;
import com.bcxin.ins.dto.oauth.AccessToken;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.oauth.OAuthService;
import com.bcxin.ins.service.order.InsCommonReportAPIService;
import com.bcxin.ins.service.user.ClientCompanyService;
import com.bcxin.ins.service.user.ClientUserService;
import com.bcxin.ins.core.service.ComDeployConfigService;
import com.bcxin.ins.entity.user.SysClientCompany;
import com.bcxin.ins.entity.user.SysClientUser;
import com.bcxin.ins.spring.cache.CacheUtils;
import com.bcxin.ins.spring.listener.SessionContext;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.email.EmailModel;
import com.bcxin.ins.util.email.EmailMsgType;
import com.bcxin.ins.util.email.MessageModel;
import com.bcxin.ins.util.email.SendEmailAndMsgUtil;
import com.bcxin.ins.util.idcard.IdNumberValidator;
import com.bcxin.ins.util.toolbox.DateUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.mapper.EntityWrapper;
import com.bcxin.mybatisplus.service.impl.ServiceImpl;
import com.bcxin.mybatisplus.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.bcxin.ins.rest.UserSupportUtil.getUserSynchronization;
import static com.bcxin.ins.util.Constant.USER_TYPE_MOBILE;


@Service
@Transactional
public class ClientUserServiceImpl extends ServiceImpl<ClientUserDao, SysClientUser> implements ClientUserService {

	private static Logger logger = LoggerFactory.getLogger(ClientUserServiceImpl.class);
	@Autowired
	private ClientUserDao clientUserDao;

	@Autowired
	private OAuthService oAuthService;
	@Autowired
	private ClientCompanyService clientCompanyService;
	@Autowired
	private ComDeployConfigService comDeployConfigService;
	@Autowired
	private InsCommonReportAPIService insCommonReportAPIService;
//	@Autowired
//	private ModelSendService mss;

	@Override
	public boolean saveClientUserVo(ClientUserVo vo) {

		try{
			SysClientUser user=null;
			SysClientCompany company  =null;
			if(vo.getLogin_name()!=null){
				if(StringUtils.isNotEmpty(vo.getOid())){
					user=this.selectById(vo.getOid());
				}else{
					//业务支撑系统已经有的登录数据 ,用户名不用生成
					user= new SysClientUser();
					user.setSys_client_user_id(IdWorker.getId());
					user.setLogin_name(vo.getLogin_name());
				}
			}else {
				user = setUserNameData(vo);
				user.setSys_client_user_id(IdWorker.getId());
			}
			//（1：个人，2：企业）
			if(Constant.TERMINAL_TYPE_COMPANY.equals(vo.getTerminal_type())){//企业类型

				if(vo.getCid()!=null){
					company=clientCompanyService.selectById(vo.getCid());
				}else{
					company=new SysClientCompany();
					company.setSys_client_company_id(IdWorker.getId());
					company.setCompany_name(Constant.COMPANYNAME);
				}
				Map<String,Object> map= UserSupportUtil.getCompany(company);
				boolean flag= (boolean) map.get("status");
				if(flag){
					company.setWeb_id(map.get("webID").toString());//保存支撑的id
					clientCompanyService.insertOrUpdate(company);
					user.setCompany_id(company.getSys_client_company_id());
				}else{
					return  false;
				}

			}
			user.setPassword(vo.getPassword());
			user.setTerminal_type(vo.getTerminal_type());
			user.setPassword(vo.getPassword());
			user.setEmail(vo.getEmail());
			user.setTelephone(vo.getTelephone());
			user.setUser_name(vo.getUser_name());
			user.setRole_name(vo.getRole_name());
			user.setRole_id(Long.parseLong(vo.getRole_id()));
			user.setBusiness_support_id(vo.getBusiness_support_id());
			user.setWeb_user_name(vo.getWeb_user_name());
			if(StringUtils.isNotEmpty(vo.getWeb_type())){
				user.setWeb_type(vo.getWeb_type());
				user.setWeb_id(vo.getWeb_id());
			}else{
				user.setWeb_type(Constant.WEB_TYPE_COINS);
				user.setWeb_id(user.getSys_client_user_id()+"");
			}
			if(Constant.IS_USER_NEW.equals(vo.getIs_new_data())){
				this.insertOrUpdate(user);
				return true;
			}
			if(company!=null&&StringUtils.isNotEmpty(company.getWeb_id())){
				Map<String,Object> map= getUserSynchronization(user,company.getWeb_id());
				boolean flag= (boolean) map.get("status");
				if(flag){
					user.setBusiness_support_id(map.get("webID").toString());//保存支撑的id
					this.insertOrUpdate(user);
					return true;
				}
			}else{
				Map<String,Object> map= getUserSynchronization(user,null);
				boolean flag= (boolean) map.get("status");
				if(flag){
					user.setBusiness_support_id(map.get("webID").toString());//保存支撑的id
					this.insertOrUpdate(user);
					return true;
				}
			}
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return  false;


	}

	private SysClientUser setUserNameData(ClientUserVo vo) {
		SysClientUser user= new SysClientUser();
		boolean  flag= false;
		do{
			StringBuffer userName=new StringBuffer("");
			if(Constant.TERMINAL_TYPE_COMPANY.equals(vo.getTerminal_type())){
				userName.append(Constant.USER_NAME_COMPANY+ MathUtil.getUserNum(9));
				user.setLogin_name(userName.toString());
			}else{
				userName.append(Constant.USER_NAME_COMMON+ MathUtil.getUserNum(9));
				user.setLogin_name(userName.toString());
			}
			int userNameNum=clientUserDao.getUserNameByExist(userName.toString());//判断用户名是否存在
			if(userNameNum>0){
				flag=true;
			}

		}while (flag);
		return user;
	}

	@Override
	public boolean getUserMobileForRegister(String mobile, String webType) {
//		if(UserSupportUtil.getUserPhoneExist(mobile)){
//			return false;
//		}
		int   num=clientUserDao.getUserMobileForRegister(mobile,webType);
		if(num>0){
			//存在该条记录
			return  false;
		}
		return true;
	}

	@Override
	public boolean getUserEmailForRegister(String email, String webType) {
//		if(UserSupportUtil.getUserEmailExist(email)){
//			return false;
//		}
		int num=clientUserDao.getUserEmailForRegister(email,webType);
		if(num>0){
			//存在该条记录
			return  false;
		}
		return true;
	}

	@Override
	public boolean sendEmailToUser(String email, String emailTitle, String emailContent) {

		try {

			if(StringUtils.isBlank(emailTitle)||StringUtils.isBlank(emailContent)|| StringUtils.isBlank(email)){

			}else{
				//"<h3>尊敬的"+"yq1012"+"，您好！</h3> <p>您正在进行邮箱验证，本次请求的验证码为：</p> <p> <a>"+code+"</a> </p><p>(为了保障您账户的安全性，请在半小时内完成验证。)</p>";

				EmailModel emailModel = new EmailModel(emailTitle, emailContent);
				List<String> list = new ArrayList<String>();
				list.add(email); // 发送地址
				emailModel.setTo(list);
				SendEmailAndMsgUtil.sendEmail(emailModel);
				return   true;
			}

		} catch (Exception e) {
			logger.error("发送邮件错误",e);
		}
		return   false;
	}

	/**
	 * <b> 邮件发送给客服人员 </b>
	 * @author ZXF
	 * @create 2018/02/08 0008 9:35
	 * @version
	 * @注意事项 </b>
	 */
	@Override
	public boolean sendEmailToService(String emailTitle, String emailContent) {
		try {
			if(StringUtils.isBlank(emailTitle)||StringUtils.isBlank(emailContent)){
				return false;
			}
			//"<h3>尊敬的"+"yq1012"+"，您好！</h3> <p>您正在进行邮箱验证，本次请求的验证码为：</p> <p> <a>"+code+"</a> </p><p>(为了保障您账户的安全性，请在半小时内完成验证。)</p>";
			String[] arrs = comDeployConfigService.getValueByKey("exmail").split(com.bcxin.ins.vo.ConstProp.SEMICOLON);
			EmailModel emailModel = new EmailModel(emailTitle, emailContent);
			logger.info("邮件发送（sendEmailToService 内容htmlContent）:"+emailModel.getContent());
			List<String> list = new ArrayList<String>();
			for(int i=0;i<arrs.length;i++){
				if(StringUtils.isNotBlank(arrs[i]) && !arrs[i].contains(ConstProp.COLON)){
					// 发送地址
					list.add(arrs[i].trim());
					logger.info("邮件发送（sendEmailToService 收件人Email-"+(i+1)+"）:"+arrs[i]);
				}
			}
			if(list.size()>0){
				emailModel.setTo(list);
				SendEmailAndMsgUtil.sendEmail(emailModel);
				logger.info("邮件发送（sendEmailToService）:SUCCESS!");
				return true;
			}
			logger.info("邮件发送（sendEmailToService）:FAIL!");
			return false;
		} catch (Exception e) {
			logger.error("邮件发送（sendEmailToService 发生异常）",e);
		}
		return false;
	}

	@Override
	public boolean checkUserExist(String email,boolean isUserName) {
		if(StringUtils.isBlank(email)){
			return false;
		}
		if(MathUtil.checkEmail(email)){
			//如果是邮箱就去判断 邮箱是否存在
			int num=clientUserDao.getUserEmailForRegister(email, Constant.WEB_TYPE_COINS);
			if(num>0){
				return true;
			}
//			if(UserSupportUtil.getUserEmailExist(email)){
//				return true;
//			}
		}else if(MathUtil.isMobileNO(email)){
			//如果是手机就去判断 手机是否存在
			int num=clientUserDao.getUserMobileForRegister(email, Constant.WEB_TYPE_COINS);
			if(num>0){
				return true;
			}
//			if(UserSupportUtil.getUserPhoneExist(email)){
//				return true;
//			}
		}else{
			if(!isUserName){
				return false;
			}
			//判断用户名 是否存在
			int num= clientUserDao.getUserNameByExist(email);
			if(num>0){
				return  true;
			}
//				if(UserSupportUtil.getUserLoginNameExist(email)){
//					return true;
//				}
		}
		return false;
	}

	@Override
	public String sendUserCode(String email, EmailMsgType type) {
		if(USER_TYPE_MOBILE.equals(MathUtil.getType(email))){
			//是手机号码
			if(EmailMsgType.AUTHCODE==type){
				//发送验证码
				String code = MathUtil.getRandomCode();
				//如果是测试环境验证码固定123456
				code = GlobalResources.IS_TEST_ENVI?"123456":code;
				logger.info("实名认证-验证码："+code);
				MessageModel mm = new MessageModel(code, EmailMsgType.AUTHCODE);
				logger.info("实名认证-手机验证码内容："+mm.getContent());
				//华为短信发送
//				mss.sendHuaWeiSMS(new HuaWeiSmsContent(
//						ConstProp.SMSPLATFORM_BCXIN,
//						ConstProp.SMSCODE_P01,
//						email,
//						JSON.toJSONString(new String[]{code})));
				logger.info("实名认证-手机号码"+email);
				return code;
			}
		}else if(Constant.USER_TYPE_EMAIL.equals(MathUtil.getType(email))){
			// 是邮箱
			if(EmailMsgType.AUTHCODE==type){
				//发送验证码
				String code= MathUtil.getRandomCode();
				//如果是测试环境验证码固定123456
				code = GlobalResources.IS_TEST_ENVI?"123456":code;
				EmailModel em = new EmailModel(code,EmailMsgType.TYYZM);
				em.addTo(email);
				try {
					SendEmailAndMsgUtil.sendEmail(em);
					return  code;
				}catch (Exception e){}
			}
		}

		return null;
	}

	@Override
	public ClientUserVo getClientUserVo(String email, String type) {
		ClientUserVo vo= null;
		if(Constant.USER_TYPE_EMAIL.equals(type)){
			vo= new ClientUserVo();
			vo.setEmail(email);
			vo= clientUserDao.getClientUserVo(vo);
		}
		else if(USER_TYPE_MOBILE.equals(type)){
			vo= new ClientUserVo();
			vo.setTelephone(email);
			vo= clientUserDao.getClientUserVo(vo);
		}
		else if(Constant.USER_TYPE_NAME.equals(type)){
			vo= new ClientUserVo();
			vo.setLogin_name(email);
			vo= clientUserDao.getClientUserVo(vo);
		}
		if(vo!=null&&StringUtils.isNotEmpty(vo.getOid())){
			if("1".equals(vo.getTerminal_type())){//个人
				vo.setCompany_name(null);
			}else if("2".equals(vo.getTerminal_type())){//企业
				vo.setReal_name(null);
			}
			return vo;
		}
		return null;
	}

	@Override
	public ClientUserVo getClientUserVoForThir(String webId, String webType) {
		ClientUserVo vo = new ClientUserVo();
		vo.setWeb_id(webId);
		vo.setWeb_type(webType);
		return clientUserDao.getClientUserVoForThir(vo);
	}

	@Override
	public boolean updClientUserVoPwd(ClientUserVo vo, String password) {
		//仅仅保存密码   需要调用修改密码接口
		if(StringUtils.isNotEmpty(password)&&vo.getOid()!=null){
			if(this.getUserPassword(vo.getLogin_name(),password)){
				return  true;
			}
		}
		return false;
	}

	@Override
	public boolean getUserPassword(String login_name, String password) {

		SysClientUser user= new SysClientUser();
		user.setUser_name(login_name);
		user=this.selectOne(new EntityWrapper<SysClientUser>().addFilter("login_name={0}",login_name));
		if(user==null){
			return false;
		}
		user.setPassword(Sha1Util.entryptPassword(password));
		clientUserDao.updateById(user);
		return true;

	}

	@Override
	public ClientUserVo initNewUser(Map<String,Object> map) {
		ClientUserVo vo = new ClientUserVo();
		//个人用户里面  个人账户/企业账户
		//密码
		vo.setTerminal_type(Constant.TERMINAL_TYPE_COMMON);
		vo.setRole_id("3");//设置角色权限
		vo.setRole_name("COMMON-ZERO-HEAD");//设置角色权限

		SysClientUser user= (SysClientUser) map.get("clientUser");
		if(user.getLogin_name()!=null){
			vo.setLogin_name(user.getLogin_name());
		}
		if(user.getEmail()!=null){
			vo.setEmail(user.getEmail());
		}
		if(user.getTelephone()!=null){
			vo.setTelephone(user.getTelephone());
		}

		if(user.getBusiness_support_id()!=null){
			vo.setBusiness_support_id(user.getBusiness_support_id());
		}
		vo.setIs_new_data(Constant.IS_USER_NEW);
		boolean  flag=this.saveClientUserVo(vo);
		if(flag){
			return  vo;
		}
		return null;

	}


	/**
	 * <b> 百联保用户信息绑定第三方平台标识 </b>
	 * @author ZXF
	 * @create 2024/01/29 0029 10:05
	 * @version
	 * @注意事项 </b>
	 */
	@Override
	public boolean bindThrUser(String webId, String webUsername, String phone, String userId, String webType) {
		SysClientUser user = selectById(Long.parseLong(userId));
		if(user != null){
			user.setWeb_type(webType);
			user.setWeb_id(webId);
			user.setWeb_user_name(webUsername);
//			user.setTelephone(phone);
			user.setUpdate_time(new Date());
			return updateById(user);
		}
		return false;
	}

//	@Override
//	public Map<String,Object> loginStatus(String userName, String password) {
//		//用户实体类
//		ClientUserVo vo = new ClientUserVo();
//		//获得用户登录类型
//		String type=MathUtil.getType(userName);
//		//手机类
//        if(Constant.USER_TYPE_MOBILE.equals(type)){
//			vo.setTelephone(userName);
//		}
//		//邮箱类
//		if(Constant.USER_TYPE_EMAIL.equals(type)){
//			vo.setEmail(userName);
//		}
//		//用户类
//		if(Constant.USER_TYPE_NAME.equals(type)){
//			vo.setLogin_name(userName);
//		}
//		vo.setPassword(password);
//		return UserSupportUtil.getUserLogin(vo);
//	}

	@Override
	public boolean updClientUserVoInfo(ClientUserVo vo, String realName, String realCard) {
		SysClientUser sysClientUser =clientUserDao.selectById(vo.getOid());
		sysClientUser.setReal_name(realName);
		sysClientUser.setBirthday(DateUtil.format(IdNumberValidator.idNumber2BirthDate(realCard),"yyyy-MM-dd"));
		String value = IdNumberValidator.getSexFromCard(realCard).code();
		sysClientUser.setSex(Integer.parseInt(value));
		sysClientUser.setId_card(realCard);
		sysClientUser.setId_type(Constant.IDCARD_TYPE);//
		sysClientUser.setIs_certification(Constant.IS_CERTIFICATION);
		sysClientUser.setPassword(vo.getPassword());
		clientUserDao.updateById(sysClientUser);
		//同步信息
		getUserSynchronization(sysClientUser,null);
		//设置vo
		vo.setBirthday(sysClientUser.getBirthday());
		vo.setSex(value);
		vo.setReal_name(sysClientUser.getReal_name());
		vo.setIs_certification(Constant.IS_CERTIFICATION);
		HttpServletRequest request = null;
		if (RequestContextHolder.getRequestAttributes() != null) {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			HttpSession session = request.getSession();
			session.setAttribute("userdetail", vo);
		}
		return true;
	}

	@Override
	public boolean updClientUserVoEmail(ClientUserVo vo, String email) {

		SysClientUser sysClientUser =clientUserDao.selectById(vo.getOid());
		sysClientUser.setEmail(email);
		sysClientUser.setPassword(vo.getPassword());

		Map<String,Object> map=getUserSynchronization(sysClientUser, null);
		boolean flag= (boolean) map.get("status");
		if(flag){
			vo.setEmail(email);
			clientUserDao.updateById(sysClientUser);
			//修改业务完成后重置用户登录状态
			HttpServletRequest request = null;
			if (RequestContextHolder.getRequestAttributes() != null) {
				request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
				HttpSession session = request.getSession();
				session.setAttribute("userdetail", vo);
			}
			return true;
		}else{
			return false;
		}


		//通知 支撑修改邮箱


	}

	@Override
	public boolean updClientUserVoPhone(ClientUserVo vo, String phone) {

		SysClientUser sysClientUser =clientUserDao.selectById(vo.getOid());
		sysClientUser.setTelephone(phone);
		//通知 支撑修改手机
		sysClientUser.setPassword(vo.getPassword());
		Map<String,Object> map=getUserSynchronization(sysClientUser, null);
		if(map.size()==0){
			return false;
		}
		boolean flag= (boolean) map.get("status");
		if(flag){
			vo.setTelephone(phone);
			clientUserDao.updateById(sysClientUser);
			//修改业务完成后重置用户登录状态
			HttpServletRequest request = null;
			if (RequestContextHolder.getRequestAttributes() != null) {
				request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
				HttpSession session = request.getSession();
				session.setAttribute("userdetail", vo);
			}
			return true;
		}else{
			return false;
		}

	}

	/**
	 *
	 * @param webType   外部来源类型
	 * @param webUserName    外部登录名字
	 * @param userWebId   外部用户id
	 * @return
	 */
	@Override
	public boolean saveClientUserVo(String webType, String webUserName,String  userWebId) {

		int  num= clientUserDao.getUserWebIdByExist(userWebId,webType);
		if(num>0){
			ClientUserVo vo=new ClientUserVo();
			vo.setWeb_id(userWebId);
			vo.setWeb_type(webType);
			ClientUserVo userVo=clientUserDao.getClientUserVo(vo);
			if(userVo==null){
				return false;
			}
			//直接登录
			setUserVoSession(userVo,webType);
			//同步登录账户的平安雇主线下报案信息
			insCommonReportAPIService.findXXReportDetails();
			return true;
		}else{
			//创建本地用户
			ClientUserVo userVo =setUserVoData(webType,webUserName,userWebId);
			if(userVo==null){
				return false;
			}
			//登录
			setUserVoSession(userVo,webType);
			return true;
		}

	}

	/**
	 * <b> 第三方请求过来触发的注册用户状态 </b>
	 * @author ZXF
	 * @create 2020/08/14 0014 14:20
	 * @version
	 * @注意事项 </b>
	 */
	@Override
	public boolean saveClientUserVoForTHR(String webType, String webUserName,String userWebId, String token) {
		int  num= clientUserDao.getUserWebIdByExist(userWebId,webType);
		ClientUserVo userVo = null;
		if(num>0){
			ClientUserVo vo=new ClientUserVo();
			vo.setWeb_id(userWebId);
			vo.setWeb_type(webType);
			userVo=clientUserDao.getClientUserVo(vo);
			if(userVo==null){
				return false;
			}
			//每次触发都将已存在的记录清除
			JedisUtils.del(ConstProp.REDIS_HEAD_UID+userVo.getOid());
			//直接登录
			setUserVoSessionForTHR(userVo,webType,token);
			//同步登录账户的平安雇主线下报案信息
			insCommonReportAPIService.findXXReportDetails();
		}else{
			//创建本地用户
			userVo =setUserVoData(webType,webUserName,userWebId);
			if(userVo==null){
				return false;
			}
			//登录
			setUserVoSessionForTHR(userVo,webType,token);
		}
		return true;
	}

	/**
	 * <b> 第三方绑定已有账号 </b>
	 * @author ZXF
	 * @create 2024/04/07 0007 14:55
	 * @version
	 * @注意事项 </b>
	 */
	@Override
	public boolean bindClientUser(String webType, String mobile, String webUserName,String userWebId) {
		SysClientUser user = getClientUser(mobile, USER_TYPE_MOBILE);
		if(user == null){
			return false;
		}
		if(StringUtils.isNotEmpty(user.getWeb_type())&&!ConstProp.BLB.equals(user.getWeb_type())){
			return false;
		}
		user.setWeb_type(webType);
		user.setWeb_user_name(webUserName);
		user.setWeb_id(userWebId);
		if(clientUserDao.updateById(user)>0){
			//直接登录
//			setUserVoSession(userVo,webType);
			return true;
		}
		return false;
	}

	@Override
	public void setLastTime(ClientUserVo userVo) {
		SysClientUser sysClientUser  =selectById(userVo.getOid());
		sysClientUser.setLast_login_time(new Date());
		sysClientUser.setBusiness_support_id(userVo.getBusiness_support_id());
		updateById(sysClientUser);

	}

	@Override
	public SysClientUser getClientUser(String userName, String type) {

		if(Constant.USER_TYPE_MOBILE.equals(type)){
			return selectOne(new EntityWrapper<SysClientUser>().addFilter("telephone={0}",userName));
		}
		if(Constant.USER_TYPE_EMAIL.equals(type)){
			return selectOne(new EntityWrapper<SysClientUser>().addFilter("email={0}",userName));

		}
		if(Constant.USER_TYPE_NAME.equals(type)){
			return selectOne(new EntityWrapper<SysClientUser>().addFilter("login_name={0}",userName));

		}
		return null;
	}




	private ClientUserVo setUserVoData(String webType, String webUserName, String  userWebId) {
		ClientUserVo userVo= new ClientUserVo();
		SysClientUser sysClientUser  =setUserNameData(userVo);
//		sysClientUser.setLogin_name();//map.get("longin_name").toString()
//        TODO 获取信息进行填充 待完善	//这里需要保存用户 还有公司企业
//		SysClientCompany company=new SysClientCompany();
//		company.setSys_client_company_id(IdWorker.getId());
//		company.setCompany_name(Constant.COMPANYNAME);
////		company.setWeb_id(map.get("web_id").toString());
//		company.setWeb_id(userWebId);
		sysClientUser.setWeb_type(webType);
		sysClientUser.setWeb_user_name(webUserName);
		if(StringUtils.isNotEmpty(userWebId)){
			sysClientUser.setWeb_id(userWebId);
		}
		sysClientUser.setSys_client_user_id(IdWorker.getId());
		Map<String,Object> map= getUserSynchronization(sysClientUser,null);
		boolean flag= (boolean) map.get("status");
		if(flag){
			//保存支撑的id
			sysClientUser.setBusiness_support_id(map.get("webID").toString());
			this.insert(sysClientUser);
			userVo.setWeb_id(userWebId);
			userVo.setWeb_user_name(webUserName);
			userVo.setWeb_type(webType);
			userVo.setBusiness_support_id(sysClientUser.getBusiness_support_id());
			userVo.setOid(sysClientUser.getSys_client_user_id()+"");
			setUserVoSession(userVo,webType);
		}else{
			return null;
		}

		return  userVo;

	}

	/**
	 * 第三方平台虚拟登录
	 * @param userVo
	 * @param webType 平台标识
	 */
	private void setUserVoSession(ClientUserVo userVo,String webType) {
		HttpServletRequest request = null;
		if (RequestContextHolder.getRequestAttributes() != null) {
			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(60*60);
			session.setAttribute("userdetail",userVo);
			//记录第三方请求来源标识
			CacheUtils.put(CacheUtils.THIRD_PLATFORM_FLAG,session.getId(),webType);
		}else{
			logger.info("session创建不成功");
		}
	}

	private void setUserVoSessionForTHR(ClientUserVo userVo,String webType,String token) {
		try {
			oAuthService.getAccessToken("web", userVo, token);
		} catch (OAuthSystemException e) {
			e.printStackTrace();
		}
//		HttpServletRequest request = null;
//		if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//			session.setMaxInactiveInterval(60*60);
//            session.setAttribute("userdetail",userVo);
		//记录第三方请求来源标识
		JedisUtils.set(CacheUtils.THIRD_PLATFORM_FLAG+token,webType, AccessToken.ACCESS_TOKEN_WEB_VALIDITY_SECONDS);
//			//添加session
//			SessionContext.getInstance().addSession(session);
//			//请求Ip跟session绑定
//			JedisUtils.set(ConstProp.REDIS_HEAD_THR_TOKEN+token,session.getId(),ConstProp.ONE_HOURS_TIMEOUT_SECONDS);
//        }else{
//            logger.info("session创建不成功");
//        }
	}
}
