package com.kingdee.eas.custom.erp.util;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.qing.util.StringUtils;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;

public class SynPositionToErpUtils {

	private static Logger log = LoggerFactory.getLogger(SynPositionToErpUtils.class);
	
	
	private static String ierp = "https://sites.gtiit.edu.cn/kderpdev/ierp";  
	
	private  static  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	 // 创建SimpleDateFormat实例来格式化日期  
	private  static   SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	
	
	/**
	 * 新增：获取gt15_adminorg_add的请求地址
	 * @param request
	 * @param code
	 * @return
	 */
	 public static String getGt15BosPositionAddUrl() {
		 Properties config = SynPublicUtils.getConfig();
		  ierp = (String)config.get("ierp");
	     return new StringBuffer().append(ierp).append("/kapi/v2/gt15/base/bos_position/gt15_bos_position_add").toString();
	       
	 }
	
	
	 /**
		 * 封存：获取gt15_adminorg_beta的请求地址: https://sites.gtiit.edu.cn/kderpdev/ierp/kapi/v2/gt15/base/bos_adminorg/gt15_adminorg_beta
		 * @param request
		 * @param code
		 * @return  https://sites.gtiit.edu.cn/kderpdev/ierp/kapi/v2/gt15/base/bos_position/gt15_bos_position_disable
		 */
		 public static String getBosPositionDisableUrl() {
			 Properties config = SynPublicUtils.getConfig();
			  ierp = (String)config.get("ierp");
		     return new StringBuffer().append(ierp).append("/kapi/v2/gt15/base/bos_position/gt15_bos_position_disable").toString();
		       
		 }
	
		 
		 
		 /**
			 * 主体:新增：推送数据到ERP功能:主体
			 * @return
			 * @throws Exception 
			 */
			 public static void synPostionToErp(Context ctx ,String startDate, String endDate) throws Exception{
				 
				 //获取appToken
				 String appToken = SynSalaryFromErpUtils.getAppToken(ctx);
				 log.info("synPostionToErp.appToken："+appToken);
				 //获取accessToken
				 String accessToken = SynSalaryFromErpUtils.getAccessToken(appToken);
				 log.info("synPostionToErp.accessToken状态为："+accessToken);
				 //岗位明细保存接口
				 gt15_bos_position_add(ctx,accessToken,startDate,endDate);
				
			 } 
		 
			 /**
			  * 禁用：禁用根据编码禁用岗位:主体
			  * @param ctx
			  * @return
			  * @throws Exception
			  */
			 public static String synPositionDisableToErp(Context ctx,String startDate, String endDate) throws Exception{
				 //获取appToken
				 String appToken = SynSalaryFromErpUtils.getAppToken(ctx);
				 log.info("SynPositionToErpUtils.appToken："+appToken);
				 //获取accessToken
				 String accessToken = SynSalaryFromErpUtils.getAccessToken(appToken);
				 log.info("SynPositionToErpUtils.accessToken为："+accessToken);
				 //薪酬明细保存接口
				 bosPositionDisable(ctx,accessToken, startDate, endDate);
				 log.info("SynPositionToErpUtils.responseMsg："+accessToken);
				 
				 return "";
			 }
			 
		 
		 
		 /**
			 * 新增：新增岗位接口，推送到星瀚
			 * @param ctx
			 * @param accessToken
			 * @throws Exception 
			 */
			public static String gt15_bos_position_add(Context ctx,String accessToken,String startDate, String endDate) throws Exception{
				//获取请求地址
				String gt15BosPositionAddUrl = getGt15BosPositionAddUrl();
				
				log.info("SynPositionToErpUtils.gt15_bos_position_add.gt15BosPositionAddUrl:"+gt15BosPositionAddUrl);
				//构建行政组织参数
				String paramJOStr = getBosPositionDetailEntry(ctx,startDate,endDate);
				log.info("SynPositionToErpUtils.gt15_adminorg_add.paramJOStr:"+paramJOStr);
				
				if(StringUtils.isEmpty(paramJOStr)){
					//为空不请求
					return "";
				}
				
				//数据保存接口
		        String  responseMsg = HttpsReqUtil.postByHttps(gt15BosPositionAddUrl, paramJOStr, accessToken);
				
				
				return responseMsg;
			} 
		 
		 
			
			 /**
			  * 禁用：根据编码禁用岗位
			  * @param ctx
			  * @param accessToken
			  * @return
			 * @throws Exception 
			  */
			 public static void bosPositionDisable(Context ctx,String accessToken,String startDate, String endDate) throws Exception{
				 //获取请求地址
				String gtBosPositionDisableUrl = getBosPositionDisableUrl();
					
				log.info("SynPositionToErpUtils.bosPositionDisable.gtBosPositionDisableUrl:"+gtBosPositionDisableUrl);
				//构建行政组织参数
				List<String> numbers =getBosPositionDisableDetailEntry(ctx, startDate,  endDate);
				log.info("SynPositionToErpUtils.bosPositionDisable.numbers:"+numbers.size());
				
				for(String number : numbers){
					String paramJOStr = getParamJOStrByNumber(number);
					//数据保存接口
					   String  responseMsg = HttpsReqUtil.postByHttps(gtBosPositionDisableUrl, paramJOStr, accessToken);
				}		
			   
			 }
			
			 
			 /**
			  * 封存：通过编码获取
			  * @param numbers
			  * @return
			  */
			 public static String getParamJOStrByNumber(String number){
				 JSONObject data = new JSONObject();
				 data.put("number", number);
				 JSONObject paramJO = new JSONObject();
		         paramJO.put("data",data);
		         String paramJOStr  = paramJO.toString();
				 return paramJOStr;
			 }
			
			
			 /**
			  * 禁用：获取禁用岗位的请求参数
			  * @param ctx
			  * @return
			 * @throws BOSException 
			 * @throws SQLException 
			  */
			 public static List<String> getBosPositionDisableDetailEntry(Context ctx ,String startDateStr, String endDateStr) throws BOSException, SQLException{
				
				//获取前一天的0点时间字符串
					String lastDateZeroTimeStr = "";
					
					//获取当前时间的字符串
					String noeTimeStr = "";
					
					if(StringUtils.isEmpty(startDateStr)|| StringUtils.isEmpty(endDateStr) ){
								
						 //获取上次同步结束的时间
						 lastDateZeroTimeStr =  SynPublicUtils.getLastUpdateSynTableTimeStrByEvenName(ctx,"synPositionDisable");
						 
						 if(StringUtils.isEmpty(lastDateZeroTimeStr)){
							 //为空
							//获取前一天的0点时间字符串
							 lastDateZeroTimeStr = SynPublicUtils.getLastDateZeroTime();
						 }
									 
						//更新最新 的时间为event_timeStamp,只有在自动触发的才会修改时间
						 SynPublicUtils.updateSynTimeTable(ctx,"synPositionDisable");
						 
						//获取当前时间的字符串
						 noeTimeStr = SynPublicUtils.getNowTimeStr();
					}else{
						 lastDateZeroTimeStr = startDateStr;
						 noeTimeStr = endDateStr;
					}
				 
				 String sql = " select fnumber as number from T_ORG_Position where fdeletedstatus = 2 " +
				 		" and  (flastupdatetime> {ts '"+lastDateZeroTimeStr+"'} and  flastupdatetime <=  {ts '"+noeTimeStr+"'})";
				 log.info("getBosPositionDisableDetailEntry.sql"+sql);
				 IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);
				 List<String> numbers = new ArrayList<String>();
				 if(executeQuery.size()>0){
						while(executeQuery.next()){
							String number = executeQuery.getString("number");					
							numbers.add(number);
						}				
					} 
				 return numbers;
			 } 
			 
			
			 /**
				 * 获取上次同步结束的时间
				 * @param ctx
				 * @param evenName
				 * @throws BOSException 
				 * @throws SQLException 
				 */
				private static String getLastUpdateSynTableTimeStrByEvenName(Context ctx,String evenName) throws BOSException, SQLException{
					String sql = "select event_timestamp as evenTimeStamp from T_HR_SynTimeTable where event_name = '"+evenName+"'";
					 IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);	 
					 Date evenTimeStamp = null;
					 if(executeQuery.size()>0){
						while(executeQuery.next()){
							evenTimeStamp = executeQuery.getDate("evenTimeStamp");
						}
					 }
					 String lastUpdateTimeStr = "";
					 if(evenTimeStamp != null){
						 lastUpdateTimeStr =  dateFormat.format(evenTimeStamp);
					 }
					 return lastUpdateTimeStr;
				}
			
			
				 /**
				  * 获取当前时间的字符串
				  * @return
				  */
				 private static String getNowTimeStr(){
					 // 获取当前时间  
				        Date now = new Date();  
				          
				        // 创建SimpleDateFormat实例来格式化日期  
				        // 这里使用"yyyy-MM-dd HH:mm:ss"作为日期时间格式  
				          
				        // 格式化日期并获取字符串  
				        String formattedDateTime = dateFormat.format(now);  
					 
					return formattedDateTime;
				 }	
				
				
			/**
			 * 获取岗位接口 参数，查询，并构建参数
			 * @param ctx
			 * @return
			 * @throws BOSException
			 * @throws SQLException
			 */
			private static String getBosPositionDetailEntry(Context ctx,String startDateStr,String endDateStr) throws BOSException, SQLException{
				
				//获取前一天的0点时间字符串
				String lastDateZeroTimeStr = "";
				
				//获取当前时间的字符串
				String noeTimeStr = "";
				
				if(StringUtils.isEmpty(startDateStr)|| StringUtils.isEmpty(endDateStr) ){
							
					 //获取上次同步结束的时间
					 lastDateZeroTimeStr =  SynPublicUtils.getLastUpdateSynTableTimeStrByEvenName(ctx,"SynPosition");
					 
					 if(StringUtils.isEmpty(lastDateZeroTimeStr)){
						 //为空
						//获取前一天的0点时间字符串
						 lastDateZeroTimeStr = SynPublicUtils.getLastDateZeroTime();
					 }
								 
					//更新最新 的时间为event_timeStamp,只有在自动触发的才会修改时间
					 SynPublicUtils.updateSynTimeTable(ctx,"SynPosition");
					 
					//获取当前时间的字符串
					 noeTimeStr = SynPublicUtils.getNowTimeStr();
				}else{
					 lastDateZeroTimeStr = startDateStr;
					 noeTimeStr = endDateStr;
				}
							
				String sql = "/*dialect*/select position.fnumber as  number ,position.fname_l1, position.fname_l2,position.fname_l3,admin.fnumber as dpt_number,position2.fnumber as superiorposition_number,position.fdescription_l1 as description_l1,position.fdescription_l2 as description_l2,position.fdescription_l3 as description_l3,position.fisRespPosition isRespPosition from T_ORG_Position position " +
						" left join T_org_admin admin on admin.fid = position.fadminorgunitid" +
						" left join T_ORG_Position position2 on position2.fid = position.fparentid " +
						" where (  (position.flastupdatetime >  {ts '"+lastDateZeroTimeStr+"'} and  position.flastupdatetime <=  {ts '"+noeTimeStr+"'} )" +
								" or   (admin.flastupdatetime >  {ts '"+lastDateZeroTimeStr+"'} and  admin.flastupdatetime <=  {ts '"+noeTimeStr+"'} )" +
								" or (position2.flastupdatetime >  {ts '"+lastDateZeroTimeStr+"'} and  position2.flastupdatetime <=  {ts '"+noeTimeStr+"'} )) ";
						//" and position.fnumber = 'IT-2016008'";
				log.info("getBosPositionDetailEntry.sql:"+sql);
				
				IRowSet executeQuery = DbUtil.executeQuery(ctx, sql);
				
				JSONArray datas = new JSONArray();
				 String paramJOStr = "";
				if(executeQuery.size()>0){
					while(executeQuery.next()){
						String number = executeQuery.getString("number");
						String name_l1 = executeQuery.getString("fname_l1");
						String name_l2 = executeQuery.getString("fname_l2");
						String name_l3 = executeQuery.getString("fname_l3");
						String dpt_number = executeQuery.getString("dpt_number");
						String superiorposition_number = executeQuery.getString("superiorposition_number");
						String description_l1 = executeQuery.getString("description_l1");
						String description_l2 = executeQuery.getString("description_l2");
						String description_l3 = executeQuery.getString("description_l3");
						boolean isRespPosition = executeQuery.getBoolean("isRespPosition");
						log.info("getBosPositionDetailEntry.isRespPosition:"+isRespPosition);
						JSONObject data = new JSONObject();			
						data.put("number",number);
						
						JSONObject name = new JSONObject();	
						 name.put("en_US", name_l1);
						 name.put("zh_CN", name_l2);
						 name.put("zh_TW", name_l3);
						
						data.put("name",name);
						
						data.put("dpt_number", dpt_number);
						data.put("superiorposition_number", superiorposition_number);
						data.put("ismainposition", isRespPosition);
						/*JSONObject remark = new JSONObject();
						remark.put("en_US", description_l1);
						remark.put("zh_CN", description_l2);
						remark.put("zh_TW", description_l3);
						data.put("remarks",remark);*/
						datas.add(data);
					}
					JSONObject paramJO = new JSONObject();
			         paramJO.put("data",datas);
			         paramJOStr = paramJO.toString();		
				}
				 
				return paramJOStr;
			}
		 
}
