package com.cim.idm.mwmsextend.userprofile.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Element;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.exception.IDMFrameDBErrorSignal;
import com.cim.idm.framework.exception.ext.DuplicateNameSignal;
import com.cim.idm.framework.exception.ext.FrameworkErrorSignal;
import com.cim.idm.framework.exception.ext.InvalidStateTransitionSignal;
import com.cim.idm.framework.exception.ext.NotFoundSignal;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.user.UserServiceProxy;
import com.cim.idm.wmspackage.user.management.data.AuthTokenResultModel;
import com.cim.idm.wmspackage.user.management.data.PortalResp;
import com.cim.idm.wmspackage.user.management.data.UserInfo;
import com.cim.idm.wmspackage.user.management.data.UserInfoKey;
import com.cim.idm.wmspackage.user.management.data.UserLoggedIn;
import com.cim.idm.wmspackage.user.management.data.UserLoggedInHistory;
import com.cim.idm.wmspackage.user.management.data.UserLoggedInHistoryKey;
import com.cim.idm.wmspackage.user.management.data.UserLoggedInKey;
import com.cim.idm.wmspackage.user.management.impl.EncryptUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
//import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
//import com.sun.org.apache.xml.internal.security.utils.Base64;

import cn.hutool.crypto.digest.DigestUtil;


public class UserProfileServiceImpl implements ApplicationContextAware{
	private ApplicationContext     	applicationContext;
	private static Log 				log = LogFactory.getLog(UserProfileServiceImpl.class);
			
	@Autowired
    private RestTemplate restTemplate;
	
	static String client_id = "";
    static String client_secret = "";
    static String url = "";
    static String redirect_uri = "";
    
    public UserProfileServiceImpl() {
    	String mode = "TST";
    	if ("TST".equals(mode)) {
    		client_id = "1e130d3af47544c29fd92fa01a3e61fd";
			client_secret = "ywHLpxzlR4XRxOP0AB5Z";
			url = "http://10.44.254.26/portal/auth/";
			redirect_uri = "http://10.44.254.172:8083/MWMS_TST.Shell.application";
    	} else if ("PRD".equals(mode)) {
    		client_id = "b82c48ddf7f646819b9db502f7c1f308";
			client_secret = "RUCL6Pi629Gin6QJmMSZ";
			url = "http://10.45.128.178/portal/auth/";
			redirect_uri = "http://10.44.254.170:8083/MWMS_PRD.Shell.application";
    	}
    }

	/*
	* Name : setApplicationContext
	* Desc : This function is setApplicationContext
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	@Override
	public void setApplicationContext(ApplicationContext arg0)throws BeansException 
	{
			applicationContext = arg0;
	}

	/*
	* Name : validateUserLoggedIn
	* Desc : This function is validateUserLoggedIn
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public String validateUserLoggedIn(String userId, String password,
			String uiName, String workStationName)
			throws CustomException {
		log.info("Execute validateUserLoggedIn");
		try {
			boolean verifyPassword = UserServiceProxy.getUserInfoService().verifyPassword(userId, password);
			boolean verifyPsd = UserServiceProxy.getUserInfoService().verifyPassword(userId, DigestUtil.md5Hex(password));
			if(verifyPassword || verifyPsd) {
				
				try {
					UserLoggedInKey keyInfo2 = new UserLoggedInKey(userId,uiName);
					UserLoggedIn selectByKey2 = UserServiceProxy.getUserLoggedInService().selectByKey(keyInfo2);
					return selectByKey2.getWorkStationName();
				} catch (Exception e) {
					return "";
				}
				
			}
			else {
				throw new CustomException("User-0002",userId,password);
			}
		} catch (CustomException e) {
			throw e;
		} catch (Exception e) {
			throw new CustomException("User-0001",userId);
		}

	}

	/*
	* Name : login
	* Desc : This function is login
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void login(String userId,
			String password,
			String uiName,
			String workStationName)
			throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal, Exception
		 {
		validateUserLoggedIn(userId, password, uiName, workStationName);
		login(userId, password, uiName, workStationName,"");
	}
	
	/*
	* Name : login
	* Desc : This function is login
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void login(String userId,
				  	  String password,
					  String uiName,
					  String workStationName,
					  String oldWorkStationName)
	throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal, Exception
	{
		log.info("Execute login");
		
		/*if(!oldWorkStationName.isEmpty() && !workStationName.equalsIgnoreCase(oldWorkStationName)) {
			logOut(userId, uiName, oldWorkStationName);
		}
		
		//UserServiceProxy.getUserProfileService().logIn(userId, password, uiName, workStationName);
		UserServiceProxy.getUserProfileService().logIn(userId, password, uiName, " ");*/
		UserLoggedInKey userLoggedInKey = new UserLoggedInKey(userId, uiName);
		UserLoggedIn userLoggedIn =  null;
		try{
			userLoggedIn = UserServiceProxy.getUserLoggedInService().selectByKey(userLoggedInKey);
		}catch(IDMFrameDBErrorSignal e){
			log.error(e,e);
//			throw e;
		}catch(NotFoundSignal e){
			log.error(e,e);
//			throw e;
		}
		
		Timestamp loggedInTime =new Timestamp(System.currentTimeMillis());


		if(userLoggedIn!=null){	
			
			userLoggedIn.setLoggedInTime(loggedInTime);
			userLoggedIn.setWorkStationName(workStationName);
			UserServiceProxy.getUserLoggedInService().update(userLoggedIn);
			
	    }
		else
		{
			userLoggedInKey = new UserLoggedInKey(userId, uiName);
			userLoggedIn  = new UserLoggedIn(userLoggedInKey, workStationName, loggedInTime);		
		    UserServiceProxy.getUserLoggedInService().insert(userLoggedIn);
		}
		
		 UserLoggedInHistoryKey userLoggedInHistoryKey = new UserLoggedInHistoryKey();
		 userLoggedInHistoryKey.setUserId(userId);
		 userLoggedInHistoryKey.setUIName(uiName);
		 userLoggedInHistoryKey.setLoggedInTime(loggedInTime);
		 
		 UserLoggedInHistory userLoggedInHistory = new UserLoggedInHistory();
		 userLoggedInHistory.setKey(userLoggedInHistoryKey);
		 userLoggedInHistory.setWorkStationName(workStationName);
		 userLoggedInHistory.setLoggedOutTime(null);
		 UserServiceProxy.getUserLoggedInHistoryService().insert(userLoggedInHistory);
		
		
	}
	
	/*
	* Name : logOut
	* Desc : This function is logOut
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void logOut(String userId,
					   String uiName, 
					   String workStationName)
	throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal
	{
		try{
			log.info("Execute logOut");
			
			/*//UserServiceProxy.getUserProfileService().logOut(userId, uiName, workStationName);
			UserServiceProxy.getUserProfileService().logOut(userId, uiName, " ");*/
			
			String sql1	= "SELECT * FROM USERLOGGEDIN "
				+ "WHERE USERID = :userId AND UINAME = :uiName AND WORKSTATIONNAME = :workStationName";
	
			Map<String, Object> bindMap1 = new HashMap<String, Object>();		
			bindMap1.put("userId", userId);
			bindMap1.put("uiName", uiName);
			bindMap1.put("workStationName", workStationName);
			
			List<Map<String, Object>> sqlResult1 
			= IDMFrameServiceProxy.getSqlTemplate().queryForList(sql1, bindMap1);
			
			if(sqlResult1.size()>0)
			{
				String sql2	= "DELETE FROM USERLOGGEDIN "
					+ "WHERE USERID = :userId AND UINAME = :uiName AND WORKSTATIONNAME = :workStationName";
				
				IDMFrameServiceProxy.getSqlTemplate().update(sql2, bindMap1);
				
				UserLoggedInHistoryKey userLoggedInHistoryKey = new UserLoggedInHistoryKey();
				userLoggedInHistoryKey.setUserId(userId);
				userLoggedInHistoryKey.setUIName(uiName);
				userLoggedInHistoryKey.setLoggedInTime((Timestamp)sqlResult1.get(0).get("LOGGEDINTIME"));
				
				UserLoggedInHistory userLoggedInHistory = new UserLoggedInHistory();
				userLoggedInHistory.setKey(userLoggedInHistoryKey);
				userLoggedInHistory.setWorkStationName(workStationName);
				userLoggedInHistory.setLoggedOutTime(new Timestamp(System.currentTimeMillis()));
				
				UserServiceProxy.getUserLoggedInHistoryService().update(userLoggedInHistory);			
			}
			
			
		}catch(Exception e){
			log.warn(e);
		}
	}
	
	/*
	* Name : changePassword
	* Desc : This function is changePassword
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void changePassword(String userId,
							   String oldPassword, 
							   String newPassword)
	throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal, Exception
	{
		try {
			log.info("Execute changePassword");
			
			UserInfoKey userInfoKey = new UserInfoKey();
			userInfoKey.setUserId(userId);
			UserInfo userInfo = UserServiceProxy.getUserInfoService().selectByKey(userInfoKey);
			
			UserServiceProxy.getUserInfoService().changePassword(userId, DigestUtil.md5Hex(oldPassword.getBytes()), DigestUtil.md5Hex(newPassword.getBytes()));

//			String userName = userInfo.getUserName();
//
//			AuthTokenResultModel authTokenResultModel = this.getAuthToken();
//
//			this.updateUserInfoToProtal(userInfo.getPortalId(), userName, newPassword, authTokenResultModel.getAccess_token());
		}
		catch  (Exception e){
			IDMFrameServiceProxy.getTxDataSourceManager().rollbackTransaction();
			throw e;
		}
	}
	
	/*
	* Name : verifyPassword
	* Desc : This function is verifyPassword
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void verifyPassword(String userId,
							   String password)
	throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal, CustomException
	
	{
		log.info("Execute verifyPassword");
        
        if ( !(UserServiceProxy.getUserInfoService().verifyPassword(userId, password)))
        {
        	throw new CustomException("User-0002", userId, password);
        }
	}
	
	/*
	* Name : verifyPasswordByEIS
	* Desc : This function is verifyPasswordByEIS
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public String verifyPasswordByEIS(String userId,
			String password)
	throws InvalidStateTransitionSignal, FrameworkErrorSignal, NotFoundSignal, DuplicateNameSignal
	
	{
		log.info("Execute verifyPassword");
		
		String authorityCode=null;
		
		if ( !(UserServiceProxy.getUserInfoService().verifyPassword(userId, password)))
		{
			authorityCode="N";
		}
		else {
            authorityCode="Y";
        }
		
		return authorityCode;
	}
	
	/*
	* Name : verifyUser
	* Desc : This function is verifyUser
	* Author : AIM Systems, Inc
	* Date : 2011.02.12
	*/
	public void verifyUser(String userId) throws Exception
	{
		log.info("Execute verify User");
		
		UserInfoKey userProfileKey = new UserInfoKey();
		
		userProfileKey.setUserId( userId );
		
		try
		{
			UserServiceProxy.getUserInfoService().selectByKey( userProfileKey );
		}
		catch ( Exception e )
		{
			throw new CustomException("User-0001", userId);
		}
	}
	public String PDAUserLoggedIn(String userId, String password)
			throws Exception {
		log.info("Execute PDAUserLoggedIn");
		String result = "";
		//password = Base64Decode(password);
		try {
			boolean verifyPassword = UserServiceProxy.getUserInfoService().verifyPassword(userId, password);
			if(verifyPassword) {				
				result=userId;
				return result;				
			}
			else {
				throw new CustomException("LoginError",userId,password);
			}
		} catch (CustomException e) {
			throw new CustomException("LoginError",userId,password);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("LoginError",userId,password);						
		}
	}
	public String PDAUserLoggedInOld(String userId, String password)
			throws Exception {
		log.info("Execute PDAUserLoggedIn");
		String result = "";
		//password = Base64Decode(password);
		try {
			boolean verifyPassword = UserServiceProxy.getUserInfoService().verifyPassword(userId, password);
			if(verifyPassword) {				
				result=userId;
				return result;				
			}
			else {
				throw new CustomException("LoginError",userId,password);
			}
		} catch (CustomException e) {
			throw new CustomException("LoginError",userId,password);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("LoginError",userId,password);						
		}
	}
	public List<UserInfo> getUserList(String jsStr) throws Exception
	{		
		List<UserInfo> informationList=new ArrayList<UserInfo>();
		if(jsStr!="")
		{
			try
			{ 
				ObjectMapper mapper=new ObjectMapper();
				mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY , true);
				//String s=jsStr.replaceAll("\n", "").replaceAll(" ", "");
				informationList=mapper.readValue(jsStr, new TypeReference<List<UserInfo>>() {});	
			}
			catch(Exception e)
			{
				e.getMessage();
				throw e;
			}
		}
		return informationList;
			
	}
	public String pdaLoginCheck(List<UserInfo> userInfo) throws CustomException
	{
		String result = "";
		try {
			boolean verifyPassword = UserServiceProxy.getUserInfoService().verifyPassword(userInfo.get(0).getKey().getUserId(), userInfo.get(0).getPassword());
			if(verifyPassword) {
				
				try {
					result=userInfo.get(0).getKey().getUserId();
					return result;
				} catch (Exception e) {
					return "";
				}
			}
			else {
				throw new CustomException("User-0002",userInfo.get(0).getKey().getUserId(), userInfo.get(0).getPassword());
			}
		} catch (CustomException e) {
			throw e;
		} catch (Exception e) {
			throw new CustomException("User-0001",userInfo.get(0).getKey().getUserId());
		}
	}
	
	public void createUserGroup(
			String userGroupName,
			String description,
			String siteName,
			String changeFlag
			) {
		String sql = "";
		if(changeFlag.equals("create")) {
			sql = "INSERT INTO USERGROUP "
					+ " (SITENAME,USERGROUPNAME,DESCRIPTION) "
					+ " VALUES "
					+ " (:SITENAME,:USERGROUPNAME,:DESCRIPTION) ";
			Map<String,Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("USERGROUPNAME", userGroupName);
			bindMap.put("DESCRIPTION", description);
			IDMFrameServiceProxy.getSqlTemplate().update(sql,bindMap);
		}
		else if(changeFlag.equals("delete")) {
			sql = "DELETE FROM USERGROUP "
					+ " WHERE "
					+ " SITENAME = :SITENAME "
					+ " AND USERGROUPNAME = :USERGROUPNAME ";
			Map<String,Object> bindMap = new HashMap<String, Object>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("USERGROUPNAME", userGroupName);
			bindMap.put("DESCRIPTION", description);
			IDMFrameServiceProxy.getSqlTemplate().update(sql,bindMap);
		}
		
	}
	
	public void updateUserGroupMenu(String siteName,
			String userGroupName,
			String uiName,
			String accessFlag,
			List<Element> menuList) throws Exception {
		try {

			
			String sqlDelete = "DELETE FROM usergroupmenu "
					+ " WHERE "
					+ " SITENAME=:SITENAME "
					+ " AND USERGROUPNAME=:USERGROUPNAME "
					+ " AND UINAME=:UINAME";
			Map<String,Object> bindMap = new HashMap<String,Object>();
			bindMap.put("SITENAME", siteName);
			bindMap.put("USERGROUPNAME", userGroupName);
			bindMap.put("UINAME", uiName);
			IDMFrameServiceProxy.getSqlTemplate().update(sqlDelete,bindMap);
			
			String sqlInsert = "INSERT INTO usergroupmenu "
					+ " (SITENAME,USERGROUPNAME,UINAME,MENUNAME,ACCESSFLAG ) "
					+ " VALUES "
					+ " (:SITENAME,:USERGROUPNAME,:UINAME,:MENUNAME,:ACCESSFLAG ) ";
			for (Element menu : menuList) {
				bindMap.put("MENUNAME", menu.getTextTrim());
				bindMap.put("ACCESSFLAG", accessFlag);
				IDMFrameServiceProxy.getSqlTemplate().update(sqlInsert,bindMap);
			}
		}
		catch  (Exception e){
			IDMFrameServiceProxy.getTxDataSourceManager().rollbackTransaction();
			throw e;
		}
	}
	
	
	public void updateUserGroupInfo (String siteName,
			String userGroupName,
			List<Element> userList) throws Exception {
		try {
			String updateUserInfoSql = " UPDATE USERINFO SET USERGROUPNAME=:USERGROUPNAME "
					+ " WHERE USERID=:USERID ";
			
			Map<String,Object> bindMap = new HashMap<String,Object>();
			bindMap.put("USERGROUPNAME", userGroupName);
			for (Element userId : userList) {
				bindMap.put("USERID", userId.getTextTrim());
				IDMFrameServiceProxy.getSqlTemplate().update(updateUserInfoSql,bindMap);
			}
		}
		catch  (Exception e){
			IDMFrameServiceProxy.getTxDataSourceManager().rollbackTransaction();
			throw e;
		}
	}
	
	
	public void createUserInfo(String siteName,
			String userId,
			String userName,
			String newPassword,
			String eventUser) throws Exception  {
		try {
			UserInfoKey userInfoKey = new UserInfoKey();
			userInfoKey.setUserId(userId);
			
			UserInfo userInfo = new UserInfo();
			userInfo.setSiteName(siteName);
			userInfo.setUserName(userName);
			userInfo.setPassword(EncryptUtil.encrypt(DigestUtil.md5Hex(newPassword)));
			userInfo.setKey(userInfoKey);
			
			UserServiceProxy.getUserInfoService().insert(userInfo);
			
			//UserServiceProxy.getUserInfoService().changePassword(userId, oldPassword, newPassword);
			
//			UserInfoKey eventKey = new UserInfoKey();
//			eventKey.setUserId(eventUser);
//			UserInfo eventUserInfo = UserServiceProxy.getUserInfoService().selectByKey(eventKey);
//			
//			AuthTokenResultModel authTokenResultModel = this.getAuthToken();
//			
//			this.createUserInfoToProtal(userId, userName, newPassword, authTokenResultModel.getAccess_token(), eventUserInfo.getUserName());
		}
		catch  (Exception e){
			IDMFrameServiceProxy.getTxDataSourceManager().rollbackTransaction();
			throw e;
		}
	}
	
	public void deletUserInfo (List<Element> userList, String eventUser) throws Exception {
		try {
			
			List<UserInfoKey> userInfoKeyList = new ArrayList<UserInfoKey>();
			for (Element userId : userList) {
				UserInfoKey userInfoKey = new UserInfoKey();
				userInfoKey.setUserId(userId.getTextTrim());
				userInfoKeyList.add(userInfoKey);
			}
			
			List<UserInfo> userInfoList = UserServiceProxy.getUserInfoService().selectByKey(userInfoKeyList);
			
			UserServiceProxy.getUserInfoService().delete(userInfoKeyList);
			
//			AuthTokenResultModel authTokenResultModel = this.getAuthToken();
//			String token = authTokenResultModel.getAccess_token();
//			
//			if (userInfoList.size() == 1 && userInfoList.get(0) != null) {
//				this.deleteUserInfoToProtal(userInfoList.get(0).getPortalId(), token);
//			} else {
//				List<Long> portalIdList = userInfoList.stream()
//						.map(userInfo -> Long.parseLong(userInfo.getPortalId()))
//						.collect(Collectors.toList());
//				this.deleteUserInfoBatchToProtal(portalIdList, token);
//			}
		}
		catch  (Exception e){
			IDMFrameServiceProxy.getTxDataSourceManager().rollbackTransaction();
			throw e;
		}
	}
	
	/*public String Base64Decode(String Message) {
		//解码
			try {
				return new String(Base64.decode(Message), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (Base64DecodingException e) {
				e.printStackTrace();
			}
			return "";
	}*/
	
	public void createUserInfoToProtal(
			String userId,
			String userName,
			String password,
			String token,
			String eventUser) throws Exception {
		HashMap<String,Object> paramMap = new HashMap<>();
		String encrypt = DigestUtil.md5Hex(password.getBytes());
		paramMap.put("account", userId);
		paramMap.put("name", userName);
		paramMap.put("password", encrypt);
		paramMap.put("phone", "");
		paramMap.put("email", "");
		paramMap.put("enabled", true);
		paramMap.put("createdBy", eventUser);
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + token);
        
        HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(paramMap), headers);
        ResponseEntity<PortalResp> response = null;
        
        try {
            response = restTemplate.postForEntity(url + "api/sync/user/create", request, PortalResp.class);
            log.info("输出"+JSON.toJSONString(response.getBody()));
            Long portalId = response.getBody().getData().getId();
            UserInfoKey userInfoKey = new UserInfoKey();
            userInfoKey.setUserId(userId);
            UserInfo userInfo = UserServiceProxy.getUserInfoService().selectByKey(userInfoKey);
            userInfo.setPortalId(String.valueOf(portalId));
            UserServiceProxy.getUserInfoService().update(userInfo);
        } catch (Exception e){
            log.error("portal login error",e);
            throw new CustomException("",new Object[]{e.getMessage()});
        }
	}
	
	public void updateUserInfoToProtal(
			String portalId,
			String userName,
			String newPassword, 
			String token) throws Exception {
		HashMap<String,Object> paramMap = new HashMap<>();
		String encrypt = DigestUtil.md5Hex(newPassword.getBytes());
		paramMap.put("id", Long.parseLong(portalId));
		paramMap.put("account", userName);
		paramMap.put("name", userName);
		paramMap.put("password", encrypt);
		paramMap.put("phone", "");
		paramMap.put("email", "");
		paramMap.put("enabled", true);
		paramMap.put("updatedBy", userName);
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + token);
        
        HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(paramMap), headers);
        ResponseEntity<PortalResp> response = null;
        
        try {
            response = restTemplate.postForEntity(url + "api/sync/user/update", request, PortalResp.class);
        } catch (Exception e){
            log.error("portal login error",e);
            throw new CustomException("",new Object[]{e.getMessage()});
        }
	}
	
	public void deleteUserInfoToProtal(String portalId, String token) throws Exception {
		HashMap<String,Object> paramMap = new HashMap<>();
		paramMap.put("id", Long.parseLong(portalId));
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + token);
        
        HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(paramMap), headers);
        ResponseEntity<PortalResp> response = null;
        
        try {
            response = restTemplate.postForEntity(url + "api/sync/user/delete", request, PortalResp.class);
        } catch (Exception e){
            log.error("portal login error",e);
            throw new CustomException("",new Object[]{e.getMessage()});
        }
	}
	
	public void deleteUserInfoBatchToProtal(List<Long> portalIdList, String token) throws Exception {
		HashMap<String,Object> paramMap = new HashMap<>();
		paramMap.put("ids", portalIdList);
		
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer " + token);
        
        HttpEntity<String> request = new HttpEntity<>(JSON.toJSONString(paramMap), headers);
        ResponseEntity<PortalResp> response = null;
        
        try {
            response = restTemplate.postForEntity(url + "api/sync/user/batch/delete", request, PortalResp.class);
        } catch (Exception e){
            log.error("portal login error",e);
            throw new CustomException("",new Object[]{e.getMessage()});
        }
	}
	
	private  AuthTokenResultModel getAuthToken() throws Exception{
		MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
		paramMap.add("grant_type", "client_credentials");
        paramMap.add("client_id", client_id);
        paramMap.add("client_secret", client_secret);
		
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(paramMap, headers);
        ResponseEntity<AuthTokenResultModel> response = null;
        try {
            response = restTemplate.postForEntity(url + "oauth2/token", request, AuthTokenResultModel.class);
        } catch (Exception e){
            log.error("portal login error",e);
            throw new CustomException("",new Object[]{e.getMessage()});
        }
        AuthTokenResultModel body = response.getBody();
        if(body == null){
            return null;
        }
        return body;
    }

	public Boolean orgPermission(String userId, String password, String orgNo)
	{
		String sql = "SELECT ORGNO FROM USERINFO WHERE USERID =:USERID ";
		Map<String, Object> bindMapOrg = new HashMap<String, Object>();
		bindMapOrg.put("USERID",userId);
		// 此物料的仓库是否是调拨单的出库仓库,如果无记录，则提示，系统无此条
		List<Map<String,Object>> orgList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMapOrg);
		if(orgList.get(0).get("ORGNO") == null || "".equals(orgList.get(0).get("ORGNO"))) {
//			throw new GlobalException("组织不存在");
		}else {
			String orgs = (String)orgList.get(0).get("ORGNO");
			if(orgs.contains(orgNo)) {
				return true;
			}

		}
		return false;
	}

	/**
	 * 加密密码字符串
	 * 使用MD5算法对密码进行散列处理，以确保密码的安全性
	 * MD5是一种广泛使用的散列函数，生成的散列值用于加密数据
	 * 注意：虽然MD5提供了一定程度的安全性，但现代密码学认为它已不足够安全
	 * 对于高安全要求的应用，建议使用更安全的加密算法，如SHA-256
	 *
	 * @param password 明文密码字符串，需要进行加密处理
	 * @return 返回加密后的密码字符串，用于存储或验证
	 */
	public String encryptPassword(String password) {
	    // 使用MD5算法对密码字符串进行散列处理
	    return EncryptUtil.encrypt(DigestUtil.md5Hex(password));
	}
}
