package kr.co.kihyun.beans.batch;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.cert.X509Certificate;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.db.FixMeJDOException;
import kr.co.kihyun.lang.MString;

public class GroupConinfoUp extends DBManager {

	private static final Logger LOG = LoggerFactory.getLogger(GroupConinfoUp.class);

	private ResultSet rs = null;
	private int count = 0;
	PreparedStatement pstmt = null;
	Statement stmt = null;
	PrintWriter out = null;

	public void updateMoumiDept() {

		Calendar oCalendar = Calendar.getInstance(); // 현재 날짜/시간 등의 각종 정보 얻기
		Integer yyCompare = oCalendar.get(Calendar.YEAR);
		Integer monCompare = (oCalendar.get(Calendar.MONTH) + 1);
		Integer dayCompare = oCalendar.get(Calendar.DAY_OF_MONTH);
		Integer hourCompare = oCalendar.get(Calendar.HOUR_OF_DAY);
		String dateCompare = Integer.toString(yyCompare) + "-" + Integer.toString(monCompare) + "-"
				+ Integer.toString(dayCompare) + " " + "01:00:00";// 2012-07-01 01:00:00
		StringBuilder sql = null;

		try {
			GroupInfoConnector gic = new GroupInfoConnector();
			int start = 1;
			String id;
			String rootCode;
			String name;
			String parentCode;
			int iSuccessCount = 0;
			sql = getDeptSql();

			String[] deptArr = null;
			while (start == 1 || deptArr.length == 1000) {
				deptArr = gic.getDeptFullTextData(start);

				for (int i = 0; i < deptArr.length; i++) {
					String[] deptColInfo = deptArr[i].split("§");
					id = deptColInfo[6];
					rootCode = deptColInfo[5];
					name = deptColInfo[7];
					parentCode = deptColInfo[9];
					if ("ROOT".equals(parentCode)) {
						parentCode = null;
					}
					addBatch(sql.toString(), id, name, id, id, rootCode, parentCode);
				}
				iSuccessCount += execBatch();
				start += 1000;
			}

			//LOG.info(":::: 부서 : " + iSuccessCount);
			LOG.info("부서 동기화 작업 성공");
			return;

		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public void updateMoumiMuser() {
		Calendar oCalendar = Calendar.getInstance(); // 현재 날짜/시간 등의 각종 정보 얻기
		Integer yyCompare = oCalendar.get(Calendar.YEAR);
		Integer monCompare = (oCalendar.get(Calendar.MONTH) + 1);
		Integer dayCompare = oCalendar.get(Calendar.DAY_OF_MONTH);
		Integer hourCompare = oCalendar.get(Calendar.HOUR_OF_DAY);
		String dateCompare = Integer.toString(yyCompare) + "-" + Integer.toString(monCompare) + "-"
				+ Integer.toString(dayCompare) + " " + "01:00:00";// 2012-07-01 01:00:00
		String delYn;
		StringBuilder sql = null;
		
		try {
			GroupInfoConnector gic = new GroupInfoConnector();
			int start = 1;
			String id;
			String name;
			String deptId;
			String dutyName;
			int iSuccessCount = 0;
			sql = getUserSql();

			String[] userArr = null;
			while (start == 1 || userArr.length == 1000) {
				userArr = gic.getUserFullTextData(start);

				for (int i = 0; i < userArr.length; i++) {
					String[] userColInfo = userArr[i].split("§");
					id = userColInfo[7];
					name = userColInfo[8];
					deptId = userColInfo[5];
					dutyName = userColInfo[17];
					delYn = "N";
					if (!"1".equals(userColInfo[2])) {
						delYn = "Y";
					}
					addBatch(sql.toString(), id, name, deptId, delYn, dutyName);
				}
				iSuccessCount += execBatch();
				start += 1000;
			}

			//LOG.info(":::: 사용자 : " + iSuccessCount);
			LOG.info("사용자 동기화 작업 성공");
			return;

		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/*
	 * 기존 부서 전체의 삭제타입을 수정
	 */
	public void updateDelMoumiDept() {
		StringBuilder sql = new StringBuilder(250);

		try {
			sql.append(" UPDATE DPMOUOWN.MOUMI_DEPT SET IS_OUT='Y' ");

			int iSuccessCount = execUpdate(sql.toString());

			LOG.info("부서 사용유무 N으로 변경");
			return;

		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/*
	 * 기존 사용자 전체의 삭제타입을 수정
	 */
	public void updateDelMoumiMuser() {
		StringBuilder sql = new StringBuilder(250);

		try {
			sql.append(" UPDATE DPMOUOWN.MOUMI_MUSER SET DEL_TYPE='Y' WHERE ID != 'admin' \n");

			System.out.print("\n::::DelMoumiMuser::::\n" + sql.toString());

			int iSuccessCount = execUpdate(sql.toString());

			//LOG.info(":::: 사용자 사용유무 N으로 변경 : " + iSuccessCount);
			LOG.info("사용자 사용유무 N으로 변경");
			return;

		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public StringBuilder getDeptSql() throws FileNotFoundException, SQLException, FixMeJDOException, IOException {
		StringBuilder sql = new StringBuilder(250);
		sql.append(				"MERGE INTO MOUMI.MOUMI_DEPT A                                                                                                       \n");
		sql.append(				"USING (                                                                                                                       \n");
		sql.append(				"	SELECT ? AS ID                                                                                           \n");
		sql.append(				"		, ? AS NAME                                                                                    \n");
		sql.append(				"		, ? AS ORGAN                                                                                    \n");
		sql.append(				"		, ? AS PASSCODE                                                                                  \n");
		sql.append(				"		, ? AS ROOT_DEPT                                                                      \n");
		sql.append(				"		, ? AS UPPER_DEPT                                                                    \n");
		sql.append(				"		, ? AS SEL_TYPE   FROM DUAL                                                                   \n");
		sql.append(				") B                                                                                                                             \n");
		sql.append(				"ON (A.ID = B.ID)                                                                                                                \n");
		sql.append(				"WHEN NOT MATCHED THEN                                                                                                           \n");
		sql.append(				"	INSERT (                                                                                                                \n");
		sql.append(				"		A.ID,                                                                                                         \n");
		sql.append(				"		A.NAME,                                                                                                       \n");
		sql.append(				"		A.ORGAN,                                                                                                      \n");
		sql.append(				"		A.PASSCODE,                                                                                                   \n");
		sql.append(				"		A.ROOT_DEPT,                                                                                                  \n");
		sql.append(				"		A.UPPER_DEPT,                                                                                                 \n");
		sql.append(				"		A.SEL_TYPE,                                                                                                   \n");
		sql.append(				"		A.IS_OUT,                                                                                                     \n");
		sql.append(				"		A.PRIORITY,                                                                                                   \n");
		sql.append(				"		A.SYS_AUTH                                                                                                   \n");
		sql.append(				"	)                                                                                                                     \n");
		sql.append(				"	VALUES (                                                                                                              \n");
		sql.append(				"		B.ID,                                                                                                         \n");
		sql.append(				"		B.NAME,                                                                                                       \n");
		sql.append(				"		B.ORGAN,                                                                                                      \n");
		sql.append(				"		B.PASSCODE,                                                                                                   \n");
		sql.append(				"		B.ROOT_DEPT,                                                                                                  \n");
		sql.append(				"		B.UPPER_DEPT,                                                                                                 \n");
		sql.append(				"		B.SEL_TYPE,                                                                                                   \n");
		sql.append(				"		'N',                                                                                                   \n");
		sql.append(				"		0,                                                                                                     \n");
		sql.append(				"		2                                                                                                     \n");
		sql.append(				")                                                                                                                     \n");
		sql.append(				"WHEN MATCHED THEN UPDATE SET                                                                                          \n");
		sql.append(				"A.ROOT_DEPT   = B.ROOT_DEPT,                                                                                          \n");
		sql.append(				"A.NAME        = B.NAME,                                                                                               \n");
		sql.append(				"A.IS_OUT      = 'N',                                                                                               \n");
		sql.append(				"A.PASSCODE    = B.PASSCODE,                                                                                           \n");
		sql.append(				"A.ORGAN    = B.ORGAN,                                                                                           \n");
		sql.append(				"A.UPPER_DEPT  = B.UPPER_DEPT                                                                                         \n");
		//setSql(sql);
		return sql;
	}

	public StringBuilder getUserSql() throws FileNotFoundException, SQLException, FixMeJDOException, IOException {
		StringBuilder sql = new StringBuilder(250);
		sql.append(				"MERGE INTO MOUMI.MOUMI_MUSER A                                                                                                       \n");
		sql.append(				"USING (                                                                                                                       \n");
		sql.append(				"	SELECT ? AS ID                                                                                           \n");
		sql.append(				"		, ? AS NAME                                                                                    \n");
		sql.append(				"		, ? AS DEPT_ID                                                                                    \n");
		sql.append(				"		, ? AS DEL_TYPE                                                                                    \n");
		sql.append(				"		, ? AS DUTY_NAME   FROM DUAL                                                                   \n");
		sql.append(				") B                                                                                                                             \n");
		sql.append(				"ON (A.ID = B.ID)                                                                                                                \n");
		sql.append(				"WHEN NOT MATCHED THEN                                                                                                           \n");
		sql.append(				"	INSERT (                                                                                                                \n");
		sql.append(				"		A.ID,                                                                                                         \n");
		sql.append(				"		A.NAME,                                                                                                       \n");
		sql.append(				"		A.DEPT_ID,                                                                                                      \n");
		sql.append(				"		A.DUTY_NAME,                                                                                                   \n");
		sql.append(				"		A.SYS_AUTH,                                                                                                  \n");
		sql.append(				"		A.PASSWD,                                                                                                 \n");
		sql.append(				"		A.MOD_YN,                                                                                                   \n");
		sql.append(				"		A.DEL_TYPE,                                                                                                     \n");
		sql.append(				"		A.DUAL_POST_YN                                                                                                   \n");
		sql.append(				"	)                                                                                                                     \n");
		sql.append(				"	VALUES (                                                                                                              \n");
		sql.append(				"		B.ID,                                                                                                         \n");
		sql.append(				"		B.NAME,                                                                                                       \n");
		sql.append(				"		B.DEPT_ID,                                                                                                      \n");
		sql.append(				"		B.DUTY_NAME,                                                                                                   \n");
		sql.append(				"		2,                                                                                                  \n");
		sql.append(				"		'1',                                                                                                 \n");
		sql.append(				"		'N',                                                                                                   \n");
		sql.append(				"		B.DEL_TYPE,                                                                                                   \n");
		sql.append(				"		'N'                                                                                                     \n");
		sql.append(				")                                                                                                                     \n");
		sql.append(				"WHEN MATCHED THEN UPDATE SET                                                                                          \n");
		sql.append(				"A.NAME   = B.NAME,                                                                                          \n");
		sql.append(				"A.DEPT_ID        = B.DEPT_ID,                                                                                               \n");
		sql.append(				"A.DEL_TYPE        = B.DEL_TYPE,                                                                                               \n");
		sql.append(				"A.DUTY_NAME  = B.DUTY_NAME                                                                                         \n");
		System.out.println("sql append ====   " + sql );
		setSql(sql);
		System.out.println("sql append set sql ====   " + sql );
		return sql;
	}
	
	
	public void getUserSync() throws JSONException {
		
		StringBuilder sql = null;
		String scheme = "https";

		HttpComponentsClientHttpRequestFactory factory = null;
		
		try {
			
			
			

			//ssl 일 경우

			if (scheme.contains("https")) {

			  TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

			  SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
			  SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
			  CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
			  factory = new HttpComponentsClientHttpRequestFactory(httpClient);
			  System.out.println("factory user===  \n" + factory);

			} else {

			  factory = new HttpComponentsClientHttpRequestFactory();

			}
			//factory = new HttpComponentsClientHttpRequestFactory();
			System.out.println("factory 222 ====   " + factory );
	
			RestTemplate restTemplate = new RestTemplate(factory);		
			System.out.println("restTemplate ====   " + restTemplate );
			
			String jSon = "";//"{\"pageSize\" : \"5\", \"pageNum\" : \"1\", \"sttsCd\":\"GNFL000300001\"}";
			 
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add("X-KNU-API-KEY", "lJwJUyM9tqxdIISEUndJVmNIydwSAKn1");
			httpHeaders.add("X-KNU-USER-ID", "moumi.web");
			httpHeaders.add("Content-Type","application/json");
			
			System.out.println("httpHeaders ====   " + httpHeaders );
	
			int pageSize =300;
			int totalPages=1;
			int iSuccessCount = 0;
			String tempJsonString1[];
			String tempJsonString2[];
			System.out.println("sql 0000000   ====   " + sql );
			//sql = getUserSql();
			System.out.println("sql 1111111   ====   " + sql );
			for(int page=1; page <= totalPages; page ++) {
				
				//jSon = "{\"pageSize\" : \""+pageSize+"\", \"pageNum\" : \""+page+"\", \"sttsCd\":\"GNFL000300001\"}";
				//jSon = "{\"pageSize\" : \""+pageSize+"\", \"pageNum\" : \""+page+"\", \"userSection\":\"EMP\"}";
				jSon = "{\"pageSize\" : \""+pageSize+"\", \"pageNum\" : \""+page+"\"}";
				System.out.println("jSon ====   " + jSon );				
				HttpEntity<String> httpEntity = new HttpEntity<String>(jSon,httpHeaders);
				System.out.println("httpEntity ====   " + httpEntity );
				MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
				System.out.println("mappingJackson2HttpMessageConverter ====   " + mappingJackson2HttpMessageConverter );
				mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
				restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
				
				System.out.println("restTemplate ====   " + restTemplate );
				//운영: https://cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/user/selectlistidntcno
				//dev: http://dev-cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/user/selectlistidntcno
				Map<String, Object> result1 = restTemplate.exchange("http://dev-cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/user/selectlistidntcno"
				          , HttpMethod.POST
				          , httpEntity	
				          , new ParameterizedTypeReference<Map<String, Object>>() {}
		
				).getBody();

				result1.forEach((key, value)
						    -> System.out.println(">>>>>result1 key: " + key + ", value: " + value));
				
				if ((int)result1.get("statusCode")==200) {
					String dutyName = null;//교수 교원
					String id = null;
					String deptId = null;//DEPT_ID K10
					String name = null;//NAME
					String passwd = null;//PASSWD 1
					String sysAuth = null;//SYS_AUTH 2
					String email = null;//EMAIL
					String userSection = null;//
					String sttsCdNm = null; //
					String sttsCd=null;//GNFL000300001
					String delType=null;

					String  jsonString1 = result1.get("data").toString();
					
					//데이터를 json형식으로 치환
					jsonString1 = jsonString1.replace("=", "\":\"");
					jsonString1 = jsonString1.replace("{", "{\"");
					jsonString1 = jsonString1.replace(", ", "\", \"");

					jsonString1 = jsonString1.replace("\"yhchoi@knu.ac.kr\", \"228choi@hanmail.net\"","\"yhchoi@knu.ac.kr\"");
					jsonString1 = jsonString1.replace("\"shlee232@knu.ac.kr\", \"shlee232@hotmail.com\"","\"shlee232@knu.ac.kr\"");
										
					jsonString1 = jsonString1.replace("\"{\"", "{\"");
					jsonString1 = jsonString1.replace("}\",", "\"},");
					jsonString1 = jsonString1.replace("\"[","[");
					jsonString1 = jsonString1.replace("]\"","]");
					jsonString1 = jsonString1.replace("}]","\"}]");
					jsonString1 = jsonString1.replace("}}","\"}}");

			    	//System.out.println(">>>>>jsonString1: " + jsonString1);	
					//외국인들 한글 이름에 포함된 ',' 삭제
					tempJsonString1 = jsonString1.split(", \"itttnCd\"");
			    	//System.out.println(">>>>>tempJsonString1 length: " + tempJsonString1.length);	

			    		
			    	for(int j=0; j<tempJsonString1.length-1; j++ ) {
				    	//System.out.println(">>>>>tempJsonString1:["+j+"]"+ tempJsonString1[j]);	
				    	tempJsonString2 = tempJsonString1[j].split("\"korNm\":");
				    	System.out.println(">>>>>대상"+ tempJsonString2[1]);	
				    	System.out.println(">>>>>치환"+ tempJsonString2[1].replace("\", \"", " "));	
				    	jsonString1 = jsonString1.replace(tempJsonString2[1], tempJsonString2[1].replace("\", \"", " "));
			    	}

			    	//System.out.println(">>>>>jsonString1: " + jsonString1);	
			        JSONObject jsonObject = new JSONObject();
	
					JSONParser parser = new JSONParser();
					jsonObject = (JSONObject)parser.parse(jsonString1);
					JSONArray jsonArray1 = (JSONArray)jsonObject.get("data");
					Map paging = (Map)jsonObject.get("paging");				

				    System.out.println("paging : " +paging);
				    if(page==1) {
				    	totalPages = Integer.parseInt(paging.get("totalPages").toString());
				    }			
					for (Object value : jsonArray1) {
					    JSONObject v = (JSONObject) value;
	
						id = MString.checkNull(v.get("userId").toString());
						dutyName = MString.checkNull(v.get("clspsNm").toString());
						deptId = MString.checkNull(v.get("itttnCd").toString());
						name = MString.checkNull(v.get("korNm").toString());
						email = MString.checkNull(v.get("email").toString());
						userSection = MString.checkNull(v.get("userSection").toString());
						sttsCdNm = MString.checkNull(v.get("sttsCdNm").toString());
						//System.out.println("sttsCd userYN =====  \n" +MString.checkNull(v.get("sttsCd").toString()));
						sql = getUserSql();
						//System.out.println("sql>>>>>"+sql); 
						sttsCd=MString.checkNull(v.get("sttsCd").toString());//GNFL000300001
						if("GNFL000300001".equals(sttsCd)) {
							delType="Y";
						}
						else delType="N";
							
						    System.out.println("userId : [" + id+
						    		"], dutyName : [" + dutyName+
						    		"], deptId : [" + deptId+
						    		"], name : [" + name+
						    		"], email : [" + email+
						    		"], userSection : [" + userSection+
						    		"], sttsCdNm : [" + sttsCdNm+"]");
						    
						addBatch(sql.toString(), id, name, deptId, delType, dutyName);
						iSuccessCount += execBatch();
						System.out.println("iSuccessCount>>>>>"+iSuccessCount); 
					}
				}
			}	
		}
		catch(Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}
		finally {
			return;			
		}
	}
	
public void getDeptSync() throws JSONException {
		
		StringBuilder sql = null;
		String scheme = "https";

		HttpComponentsClientHttpRequestFactory factory = null;
		
		try {
			

			//ssl 일 경우

			if (scheme.contains("https")) {

			  TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
			  System.out.println("acceptingTrustStrategy dept===  \n" + acceptingTrustStrategy);		
			  SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
			  System.out.println("sslContext dept===  \n" + sslContext);
			  SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
			  System.out.println("csf dept===  \n" + csf);
			  CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
			  System.out.println("httpClient dept===  \n" + httpClient);
			  factory = new HttpComponentsClientHttpRequestFactory(httpClient);
			  System.out.println("factory dept===  \n" + factory);

			} else {

			  factory = new HttpComponentsClientHttpRequestFactory();

			}
	
			RestTemplate restTemplate = new RestTemplate(factory);		 
			
			String jSon = "";
			
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add("X-KNU-API-KEY", "lJwJUyM9tqxdIISEUndJVmNIydwSAKn1");
			httpHeaders.add("X-KNU-USER-ID", "moumi.web");
			httpHeaders.add("Content-Type","application/json");
	
			int pageSize =1;
			int totalPages=1;
			int iSuccessCount = 0;
			String tempJsonString1[];
			String tempJsonString2[];
			String rightKorNm = null;
			String wrongKorNm = null;
			sql = getDeptSql();
//			for(int page=1; page <= totalPages; page ++) {
				jSon = "{\"pageSize\" : \""+pageSize+"\", \"pageNum\" : \"1\"}";
				
				HttpEntity<String> httpEntity = new HttpEntity<String>(jSon,httpHeaders);
				MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
				mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM));
				restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
				
				System.out.println("httpEntity ====   " + httpEntity );
				//운영: https://cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/itttn/selectlistitttn
				//dev: http://dev-cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/itttn/selectlistitttn
				Map<String, Object> result1 = restTemplate.exchange("https://cmmnn-api.knu.ac.kr:9080/openapi/cmmnn/support/itttn/selectlistitttn"
				          , HttpMethod.POST
				          , httpEntity	
				          , new ParameterizedTypeReference<Map<String, Object>>() {}
		
				).getBody();


				result1.forEach((key, value)
							    -> System.out.println(">>>>>result1 key: " + key + ", value: " + value));
				
				if ((int)result1.get("statusCode")==200) {
					String id 		= null;	//itttnCd
					String name 	= null;	//itttnNm
					String priority = null;	//lvl
					String organ 	= null;	//cmpsClscd
					String passCode	= null;	//
					String rootDept = null;	//0
					String upperDept= null;	//upperItttnCd
					String selType 	= null;	//dprtmUseSttcd: CMST001100001(사용) Y, N
					String isOut 	= null;	//N 
					String seqNum 	= null;	//0
					String sysAuth 	= null;	//2					
					
					String  jsonString1 = result1.get("data").toString();
					
					//데이터를 json형식으로 치환
					jsonString1 = jsonString1.replace("=", "\":\"");
					jsonString1 = jsonString1.replace("{", "{\"");
					jsonString1 = jsonString1.replace(", ", "\", \"");
						
					jsonString1 = jsonString1.replace("\"{\"", "{\"");
					jsonString1 = jsonString1.replace("}\",", "\"},");
					jsonString1 = jsonString1.replace("\"[","[");
					jsonString1 = jsonString1.replace("]\"","]");
					jsonString1 = jsonString1.replace("}]","\"}]");
					jsonString1 = jsonString1.replace("}}","\"}}");

//					//외국인들 한글 이름에 포함된 ',' 삭제
//					tempJsonString1 = jsonString1.split(", \"itttnCd\"");
//			    	System.out.println(">>>>>tempJsonString1 length: " + tempJsonString1.length);	
//
//			    		
//			    	for(int j=0; j<tempJsonString1.length-1; j++ ) {
//				    	System.out.println(">>>>>tempJsonString1:["+j+"]"+ tempJsonString1[j]);	
//				    	tempJsonString2 = tempJsonString1[j].split("\"korNm\":");
//				    	System.out.println(">>>>>대상"+ tempJsonString2[1]);	
//				    	System.out.println(">>>>>치환"+ tempJsonString2[1].replace("\", \"", " "));	
//				    	jsonString1 = jsonString1.replace(tempJsonString2[1], tempJsonString2[1].replace("\", \"", " "));
//			    	}
//jsonString1="{\"data\":[{\"rowIndex\":\"0\", \"success\":\"false\", \"message\":\"null\", \"pageSize\":\"100\", \"pageNum\":\"1\", \"lvl\":\"1\", \"itttnCd\":\"0\", \"itttnNm\":\"경북대학교(총괄)\", \"hdqrtEdcncSctcd\":\"null\", \"hdqrtEdcncSctcdNm\":\"null\", \"upperItttnNm\":\"null\", \"dprtmLvlRank\":\"1\", \"dprtmSn\":\"1\", \"itttnGrpCd\":\"null\", \"itttnGrpCdNm\":\"null\", \"lwstDprtmYn\":\"null\", \"offclDprtmYn\":\"null\", \"dprtmBeginDt\":\"18991231\", \"dprtmEndDt\":\"99991231\", \"itttnAbbnm\":\"null\", \"otpuItttnNm\":\"null\", \"dprtmUseSttcd\":\"CMST001100001\", \"dprtmUseSttcdNm\":\"사용\", \"cmpsClscd\":\"null\", \"cmpsClscdNm\":\"null\", \"orgnnSctcd\":\"null\", \"orgnnSctcdNm\":\"null\", \"dngtSctcd\":\"null\", \"dngtSctcdNm\":\"null\", \"rmrk\":\"null\", \"upperItttnCd\":\"null\", \"admnsStnrdDtalCdVal\":\"null\", \"dprtnChrceSctcd\":\"null\", \"dprtnChrceSctcdNm\":\"null\", \"rprsnFaxNo\":\"null\", \"rprsnTelno\":\"null\", \"mgmntItttnCd\":\"null\", \"paging\":\"false\", \"rowStatus\":\"R\", \"pageSort\":\"null\"},  {\"rowIndex\":\"0\", \"success\":\"false\", \"message\":\"null\", \"pageSize\":\"100\", \"pageNum\":\"1\", \"lvl\":\"2\", \"itttnCd\":\"01\", \"itttnNm\":\"총장(영문)\", \"hdqrtEdcncSctcd\":\"CMST000900001\", \"hdqrtEdcncSctcdNm\":\"본부\", \"upperItttnNm\":\"경북대학교(총괄)\", \"dprtmLvlRank\":\"2\", \"dprtmSn\":\"1\", \"itttnGrpCd\":\"null\", \"itttnGrpCdNm\":\"null\", \"lwstDprtmYn\":\"null\", \"offclDprtmYn\":\"null\", \"dprtmBeginDt\":\"18991231\", \"dprtmEndDt\":\"99991231\", \"itttnAbbnm\":\"null\", \"otpuItttnNm\":\"null\", \"dprtmUseSttcd\":\"CMST001100001\", \"dprtmUseSttcdNm\":\"사용\", \"cmpsClscd\":\"null\", \"cmpsClscdNm\":\"null\", \"orgnnSctcd\":\"null\", \"orgnnSctcdNm\":\"null\", \"dngtSctcd\":\"null\", \"dngtSctcdNm\":\"null\", \"rmrk\":\"null\", \"upperItttnCd\":\"null\", \"admnsStnrdDtalCdVal\":\"null\", \"dprtnChrceSctcd\":\"null\", \"dprtnChrceSctcdNm\":\"null\", \"rprsnFaxNo\":\"null\", \"rprsnTelno\":\"null\", \"mgmntItttnCd\":\"null\", \"paging\":\"false\", \"rowStatus\":\"R\", \"pageSort\":\"null\"}]}";
jsonString1="{\"data\":"+jsonString1+"}";

System.out.println(">>>>>jsonString11: "+ jsonString1);						
					
			        JSONObject jsonObject = new JSONObject();
	
					JSONParser parser = new JSONParser();
					jsonObject = (JSONObject)parser.parse(jsonString1);
					JSONArray jsonArray1 = (JSONArray)jsonObject.get("data");
//					Map paging = (Map)jsonObject.get("paging");					

				   // System.out.println("paging : " +paging);
//				    if(page==1) {
//				    	totalPages = Integer.parseInt(paging.get("totalPages").toString());
//				    }			
					for (Object value : jsonArray1) {
					    JSONObject v = (JSONObject) value;

//						String id 		= null;	//itttnCd
//						String name 	= null;	//itttnNm
//						String organ 	= null;	//cmpsClscd
//						String passCode = null;	//id
//						String rootDept = null;	//0
//						String upperDept= null;	//upperItttnCd
//						String priority = null;	//lvl
//						String selType 	= null;	//if(dprtmUseSttcd==CMST001100001(사용)) Y, else N
//						String isOut 	= null;	//N
//						String seqNum 	= null;	//0
//						String sysAuth 	= null;	//2		
					    id 			= MString.checkNull(v.get("itttnCd").toString());
					    name 		= MString.checkNull(v.get("itttnNm").toString());
						organ 		= MString.checkNull(v.get("itttnGrpCd").toString());
					    passCode	= MString.checkNull(v.get("itttnCd").toString());
					    rootDept	= "0";
					    upperDept 	= MString.checkNull(v.get("upperItttnCd").toString());
					    selType		= MString.checkNull(v.get("dprtmUseSttcd").toString());
					  
					    if("CMST001100001".equals(selType)) {
					    	selType = "Y";					    	
					    }
					    else selType = "N";
					    
					    System.out.println("dprtmUseSttcd useYN =====  \n" +MString.checkNull(v.get("dprtmUseSttcd").toString()));
					    System.out.println("offclDprtmYn regYN =====  \n" +MString.checkNull(v.get("offclDprtmYn").toString()));
						if(id.equals("0")) {
							organ="0";
						}else if(id.length() > 1){
							organ=id.substring(0,1);
						}else {
							organ =id;
						}
						
						
						System.out.println("id : ["+ id+"]"
										+ ", name : [" + name+"]"
										+ ", organ : [" + organ+"]"
										+ ", passCode : [" + passCode+"]"
										+ ", rootDept : [" + rootDept+"]"
										+ ", upperDept : [" + upperDept+"]"
										+ ", selType : [" + selType+"]");
						    
						addBatch(sql.toString(), id, name, organ, passCode, rootDept, upperDept,selType);
						iSuccessCount += execBatch();
						System.out.println("iSuccessCount>>>>>"+iSuccessCount); ;
					}
				}
		}
		catch(Exception e) {
			System.out.println(e);
		}
		finally {
			return;			
		}
	}
}
