/**
 * @(#)file    TermsAgreeBiz.java
 * @(#)author  이성민
 * @(#)version 1.0
 *
 */
package kr.co.udapsoft.ebid.buyer.supplier.result.biz;



import java.io.File;
import java.sql.Connection;
import java.util.Random;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.base.WAFMessages;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.persistent.Persistent;
import kr.co.hsnc.common.sql.persistent.PersistentImpl;
import kr.co.hsnc.common.util.ValueObject;
import kr.co.udapsoft.common.sender.MessageSend;
import kr.co.udapsoft.common.util.Crosscert;
import kr.co.udapsoft.ebid.buyer.common.file.FileManager;
import kr.co.udapsoft.ebid.buyer.common.file.biz.FileListWorkerDelBiz;
import kr.co.udapsoft.ebid.buyer.common.file.biz.FileListWorkerSaveHtmlBiz;
import m2soft.ers.invoker.InvokerException;
import m2soft.ers.invoker.http.ReportingServerInvoker;
import oracle.toplink.internal.ox.StrBuffer;

import com.udapsoft.waf.common.util.ClobUtils;
import com.udapsoft.waf.common.util.StringUtils;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

public class PurResultDetail01SaveBiz extends Biz {

	public PurResultDetail01SaveBiz(HandlerStorage storage) 
	{
		super(storage);
	}

	/* (non-Javadoc)
	 * @see kr.co.hwenc.system.Biz#doBiz()
	 */
	public void doBiz() throws Exception 
	{
		WAFLogger.debug(":::::::::::::::::::::::::::::::::::::::::::::::::::::::PurResultDetail01SaveBiz 내부 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
	    
	    if(storage.compareEvent("SAVE_STATUS"))
        {
            boolean success = false;
            
            try 
            {
                conn.begin();
                
                success = save_status(params); 
                
                sendMSG(success);
                
                
                super.storage.setSuccess(success);
                
                WAFLogger.debug(success);
                
            } catch (Exception e) {
            	WAFLogger.error("SAVE_STATUS e======>" + e);
                e.printStackTrace();
                conn.setRollback();
            } finally {
                if(params.get("p_reson").equals("30"))
                {
                    //createPdf(params);
                    //insetrtPdfInfo(params);
                }
                conn.end();
            }
        }else if(storage.compareEvent("SIGN_OK")){
			boolean success = false;
			String sMsg="";
			String signedData="";
			Crosscert crossErt = new Crosscert();
			signedData = crossErt.signCrosscert(params.get("CONT_HASH"));
			sMsg = crossErt.chkSignVerify(signedData);
			if(sMsg.equals("SIGN_SUCCESS")){
				params.set("CONT_SIGNDN", crossErt.getDn());
				params.set("CONT_SIGNDATA", signedData);
				success = endSignProc(super.conn.getConnection(), params, true);
				sendMSG(success);
				super.storage.setSuccess(success);
			}else{
				super.storage.setSuccess(false);	
				super.storage.setMessage("인증서 검증에 실패 하였습니다.");
			}		
		}
    }
	
	private boolean save_status(ValueObject params) throws Exception
    {
        
        Persistent persistent = null;
        StringBuffer sqlstr = new StringBuffer();
        
        
        try{
            
            persistent = new PersistentImpl(super.conn.getConnection());
            
            sqlstr.append("             UPDATE PUR_RESULT_PLOOF_INFO SET                  \n")
                    .append("                   PROG_STAT_CD    = ?                      \n")
                    .append("                 , RETURN_RESON  = ?                                           \n")
                    .append("                 WHERE CORP_ID = ?                        \n")
                    .append("                 AND PUR_CONT_MOD_ID = ?                        \n")
                    .append("                 AND ACMP_YYYY = ?                        \n")
                    .append("                 AND SOC_CD = ?                        \n");
            
            
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(params.get("p_reson").trim());
            persistent.addParameter(params.get("p_return_reson").trim());
            persistent.addParameter(params.get("corp_id").trim());
            persistent.addParameter(params.get("pur_cont_mod_id").trim());
            persistent.addParameter(params.get("acmp_yyyy").trim());
            persistent.addParameter(params.get("soc_cd").trim());
            
            
            
            WAFLogger.debug(persistent.getParameters());
            WAFLogger.debug(sqlstr.toString());
            persistent.execute();
            persistent.clearParameters();
            
            return true;
            
            
        } catch(Exception e) {
        	WAFLogger.error("e===>" +e);
            e.printStackTrace();
            return false;            
        }
    }
	
	public void createPdf(ValueObject params) throws Exception
	{
	    ReportingServerInvoker invoker = new ReportingServerInvoker(WAFConfig.get("waf.rd_report.searver"));
	      
	      invoker.setCharacterEncoding("euc-kr"); //캐릭터셋
	      invoker.setReconnectionCount(3);        //재접속 시도 회수
	      invoker.setConnectTimeout(10000);           //커넥션 타임아웃
	      invoker.setReadTimeout(30000);             //송수신 타임아웃
	      
	      
//	      String rd_path = WAFConfig.get("waf.rd_report.path.root");
	      String sever_root = WAFConfig.get("waf.ServerURL");

	      
	      invoker.addParameter("opcode", "500");
	      
	      if(params.get("soc_cd").equals("01"))
	      {
	          invoker.addParameter("mrd_path", sever_root + "/report/mrd/buyer/supplier/pur_buld_application2.mrd");
	          invoker.addParameter("mrd_param", "/rp ["+params.get("corp_id")+"] ["+params.get("pur_cont_mod_id")+"] ["+params.get("acmp_yyyy")+"] ["+params.get("soc_cd")+"]");  // CORP_ID, PUR_CONT_MOD_ID, ACMP_YYYY
	      }
	      else if(params.get("soc_cd").equals("02"))
          {
              invoker.addParameter("mrd_path", sever_root + "/report/mrd/buyer/supplier/pur_buld_application.mrd");
              invoker.addParameter("mrd_param", "/rp ["+params.get("corp_id")+"] ["+params.get("pur_cont_mod_id")+"] ["+params.get("acmp_yyyy")+"] ["+params.get("soc_cd")+"]");  // CORP_ID, PUR_CONT_MOD_ID, ACMP_YYYY
          }
	      else if(params.get("soc_cd").equals("03"))
          {
              invoker.addParameter("mrd_path", sever_root + "/report/mrd/buyer/supplier/pur_fire_application.mrd");
              invoker.addParameter("mrd_param", "/rp ["+params.get("corp_id")+"] ["+params.get("pur_cont_mod_id")+"] ["+params.get("acmp_yyyy")+"] ["+params.get("soc_cd")+"]");  // CORP_ID, PUR_CONT_MOD_ID, ACMP_YYYY
          }
	      else if(params.get("soc_cd").equals("04"))
          {
              invoker.addParameter("mrd_path", sever_root + "/report/mrd/buyer/supplier/pur_info_application.mrd");
              invoker.addParameter("mrd_param", "/rp ["+params.get("corp_id")+"] ["+params.get("pur_cont_mod_id")+"] ["+params.get("acmp_yyyy")+"] ["+params.get("soc_cd")+"]");  // CORP_ID, PUR_CONT_MOD_ID, ACMP_YYYY
          }
	      else if(params.get("soc_cd").equals("05"))
          {
              invoker.addParameter("mrd_path", sever_root + "/report/mrd/buyer/supplier/pur_electricity_application.mrd");
              invoker.addParameter("mrd_param", "/rp ["+params.get("corp_id")+"] ["+params.get("pur_cont_mod_id")+"] ["+params.get("acmp_yyyy")+"] ["+params.get("soc_cd")+"]");  // CORP_ID, PUR_CONT_MOD_ID, ACMP_YYYY
          }
	      
	      WAFLogger.debug(params.get("corp_id"));
	      WAFLogger.debug(params.get("pur_cont_mod_id"));
	      WAFLogger.debug(params.get("acmp_yyyy"));
	      WAFLogger.debug(params.get("soc_cd"));
	      
	      
	      invoker.addParameter("export_type", "pdf");
	      invoker.addParameter("export_name","");
	      invoker.addParameter("protocol", "file");
	      
	      try
	      {
	    	  FileListWorkerSaveHtmlBiz fileSave = new FileListWorkerSaveHtmlBiz(storage);
	          FileListWorkerDelBiz delFile = new FileListWorkerDelBiz(storage);
	          
              
	        // 방법 1,2,3 중 한 가지를 선택하여 사용.
	                 // 방법 1 : 파일 경로 전달
//	      invoker.invoke("C:/test.pdf"); 
	        
		        // 방법 2 : 파일 객체 전달
	           String path = WAFConfig.get("waf.repository.path") + "/";
	           String yyyymmdd = (new java.text.SimpleDateFormat ("yyyyMMdd")).format (new java.util.Date());
	           String yyyymm = (new java.text.SimpleDateFormat ("yyyyMM")).format (new java.util.Date());
		          
		        String fileName = "";
		        String saveFileName = "";
		        
		        if(params.get("soc_cd").equals("01"))
		        {
		            fileName = "대한전문건설협회_실적증명서";
		            saveFileName ="pur_buld_application2";
		        }
		        else if(params.get("soc_cd").equals("02"))
		        {
		            fileName = "대한기계설비공사협회_실적증명서";
		            saveFileName ="pur_buld_application";
		        }
		        else if(params.get("soc_cd").equals("03"))
		        {
		            fileName = "한국소방시설협회_실적증명서";
		            saveFileName ="pur_fire_application";
		        }
		        else if(params.get("soc_cd").equals("04"))
		        {
		            fileName = "한국정보통신공사협회_실적증명서";
		            saveFileName ="pur_info_application";
		        }
		        else if(params.get("soc_cd").equals("05"))
		        {
		            fileName = "한국전기공사협회_실적증명서";
		            saveFileName ="pur_electricity_application";
		        }
		        
		        
		        RowSet fileRowSet = FileManager.getFileList("RESULT_PDF", params.get("pur_cont_mod_id")+params.get("soc_cd")+params.get("p_acmp_yyyy"));
		        if(fileRowSet.size() != 0)
		        {
	           	   	String file_map_id[] =  {fileRowSet.getRow(0).get("FILE_MAP_ID")};
	           	   	delFile.delFiles(file_map_id);
		        }
		        
		        File file = new File(path + "result/" + params.get("pur_cont_mod_id") + "/" +  params.get("acmp_yyyy"));
		           if(!file.exists()){
		                //없다면 생성
		               file.mkdirs(); 
		           }
		           
		           
		        
		        invoker.invoke(new File(path + "result/" + params.get("pur_cont_mod_id") + "/" +  params.get("acmp_yyyy") + "/" + saveFileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf"));
		        
		        
		        // 방법 3 : 스트림 전달
		        /*
		        InputStream is = null;
		        OutputStream os = null;
		        try
		        {
		           is = invoker.invokeAndGetStream();
		           os = new FileOutputStream(new File("C:/test.pdf"));
		                     
		           byte[] buffer = new byte[102400];
		           int read = -1;
		           while((read = is.read(buffer)) != -1)
		           {
		              os.write(buffer, 0, read);
		           }
		        }
		        finally
		        {
		        try{ if(is != null) is.close(); } catch(IOException ignore){}
		            try{ if(os != null) os.close(); } catch(IOException ignore){}
		                    
		            invoker.disconnect();
		        }
		      */
		        
		        
		        
		           
		           /*
		           // 삭제할 파일맵에 연결된 FILE_ID를 가진 RowSet을 리턴한다.
		           RowSet fileIDrowSet =getFileIDRowSet(conn.getConnection(), fileRowSet.getRow(0).get("FILE_MAP_ID"));
		
		           // 파일맵 삭제
		           delFileMap(conn.getConnection(), fileRowSet.getRow(0).get("FILE_MAP_ID"));
		           
		           // 파일맵과 연결이 끈어진 파일 정보를 삭제한다.
		           FileManager fileManager = new FileManager();
		           fileManager.delDisConnectFileProc(conn.getConnection(), fileIDrowSet);
		           */
		           
		        WAFLogger.debug("fileRowSet=====?????==============>" + fileRowSet.size());
		           
		           boolean success = fileSave.addFilesProc(new File(path + "result/" + params.get("pur_cont_mod_id") + "/" +  params.get("acmp_yyyy") + "/" + saveFileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf"), fileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf", "", "RESULT_PDF", params.get("pur_cont_mod_id")+params.get("soc_cd")+params.get("p_acmp_yyyy"), "");
	          
//	              if(fileRowSet.size() != 0)
//	              {
//	                  boolean success = fileSave.addFilesProc(new File(path + "result/" + params.get("pur_cont_mod_id") + "/" +  params.get("acmp_yyyy") + "/" + saveFileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf"), fileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf", "", "RESULT_PDF", params.get("pur_cont_mod_id")+params.get("soc_cd"), "");
//	              }
//	              else
//	              {
//	                  boolean success = fileSave.addFilesProc(new File(path + "result/" + params.get("pur_cont_mod_id") + "/" +  params.get("acmp_yyyy") + "/" + saveFileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf"), fileName + "_" + yyyymmdd + "_" + params.get("corp_id") + ".pdf", "", "RESULT_PDF", params.get("pur_cont_mod_id")+params.get("soc_cd"), "");
//	              }
	              
		        
	      }
	      catch(InvokerException e)
	      {
	    	  WAFLogger.error("=================>" + e);
	    	  e.printStackTrace();
	    	  invoker.disconnect();
	      
	      }
	      
	      invoker.disconnect();
	}
	
	
	/**
     * 파일맵 삭제
     * @param connection
     * @param fileMapIDS
     * @throws Exception
     */
    public void delFileMap(Connection connection, String fileMapID) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {

            sqlstr = " DELETE                                       \n"
                   + " FROM   PUB0510T                              \n"
                   + " WHERE  FILE_MAP_ID IN ( " + fileMapID + " ) \n" ;

            persistent.setStatement(sqlstr);
            persistent.execute();
        }
        catch(Exception e) {
            super.doException(e);
            throw e;
        }
    }

    /**
     * 삭제할 파일맵에 연결된 FILE_ID를 리턴한다.
     * @param connection
     * @param fileMapIDS
     * @return
     * @throws Exception
     */
    public RowSet getFileIDRowSet(Connection connection, String fileMapID) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {

            sqlstr = " SELECT DISTINCT FILE_ID                      \n"
                   + " FROM   PUB0510T                              \n"
                   + " WHERE  FILE_MAP_ID IN ( " + fileMapID + " ) \n" ;

            persistent.setStatement(sqlstr);
            return persistent.query();
        }
        catch(Exception e) {
            super.doException(e);
            throw e;
        }
    }
	
	
	public boolean endSignProc(Connection connection, ValueObject valueObject, boolean signChk) throws Exception {
		//WAFLogger.debug("valueObject : " + valueObject);

        try {
        	conn.begin();
        	//boolean bSuccess = false;
        	
        	
        	if(signChk){
        		CONT_SignOk(super.conn.getConnection(), params);	//서명저장
        	}

			return true;
        }
        catch(Exception e) {
        	//WAFLogger.debug("Exception deleteContProc : " + e.getMessage());
            WAFLogger.error(this.getClass().getName() + " --> deleteContProc() : " + e.getMessage());
            WAFLogger.error(e);

            conn.setRollback();
            
            this.storage.setSuccess(false);  
            this.storage.setMessage(e.getMessage());            
            storage.setDetailMessage(e);
            return false;
        }
        finally {
        	super.conn.end();
        	if(params.get("p_reson").equals("30"))
            {
                createPdf(params);
            }
        }        
    }			
	
	
	public boolean CONT_SignOk(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        StrBuffer sqlstr = new StrBuffer();
        try {
        	sqlstr.append("UPDATE PUR_RESULT_PLOOF_INFO SET  	\n");
        	sqlstr.append(" SIGN_DT = SYSDATE					\n");
        	sqlstr.append(" ,SIGN_USER = ?					\n");
        	sqlstr.append(" ,PROG_STAT_CD = ?					\n");
        	sqlstr.append(" ,TRUE_RANDOM = ?					\n");
        	sqlstr.append("WHERE PUR_CONT_MOD_ID = ?						\n");
        	sqlstr.append("  AND SOC_CD = ?						\n");
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(valueObject.get("CONT_SIGNDN"));
            persistent.addParameter("30");
            persistent.addParameter(getTrueRamdom());
            persistent.addParameter(valueObject.get("P_PUR_CONT_MOD_ID"));
            persistent.addParameter(valueObject.get("p_soc_cd"));
            persistent.execute();
            //SIGN_HASH
            ClobUtils.setClob( conn.getConnection(), "PUR_RESULT_PLOOF_INFO", "SIGN_DATA", " WHERE PUR_CONT_MOD_ID = '"+valueObject.get("P_PUR_CONT_MOD_ID")+"' AND SOC_CD = '"+valueObject.get("p_soc_cd")+"'", valueObject.get("CONT_SIGNDATA"));
            
            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            return false;
        }
    }
	
	
	/*진위확인문자열을 구한다.*/
	public String getTrueRamdom(){
		Random r = new Random();
		int str =  r.nextInt(99999);
		return StringUtils.rightPad(str+"",5,"0");		
	}
	
	public void sendMSG(boolean success){
		
		try{
	        if(success == true && (params.get("p_reson").equals("30") || params.get("p_reson").equals("91")) )
	        {
	            MessageSend messageSend = new MessageSend(storage);
	            
	          //SMS
	            String smsContent = "";
	            
	            if(params.get("p_reson").equals("30"))
	            {
	                smsContent = WAFMessages.getMessage("Complete.approved.Result"); 
	            }
	            else
	            {
	                smsContent = WAFMessages.getMessage("Complete.approved.Result").replace("완료", "반려"); 
	            }
	            
	            WAFLogger.debug("smsContent===>" + smsContent);
	            
	            String phon_no = params.get("isu_req_hp1") + params.get("isu_req_hp2") + params.get("isu_req_hp3");
	            String re_phon_no = "024898264"; //SGC이앤씨 번호(23년 2월 박은종 과장)
	            
	            WAFLogger.debug("phon_no===>" + phon_no);
	            System.out.println("전송");
	            messageSend.sendSMS(phon_no, re_phon_no, params.get("corp_id"), smsContent); //2015.9.21 실적증명  대표번호 차후확인.
	        }
		}catch(Exception e){
            e.printStackTrace();
		}
	}
}