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



import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.springframework.web.servlet.ModelAndView;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.base.WAFMessages;
import kr.co.hsnc.common.logger.Logger;
import kr.co.hsnc.common.sql.Row;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.sql.RowSetImpl;
import kr.co.hsnc.common.sql.WAFSQLException;
import kr.co.hsnc.common.sql.persistent.Persistent;
import kr.co.hsnc.common.sql.persistent.PersistentImpl;
import kr.co.hsnc.common.sql.search.Search;
import kr.co.hsnc.common.sql.search.SearchImpl;
import kr.co.hsnc.common.sql.util.RowSetUtility;
import kr.co.hsnc.common.util.ValueObject;
import kr.co.udapsoft.common.sender.MessageSend;
import kr.co.udapsoft.common.sender.SmtpAuth;
import kr.co.udapsoft.common.util.Crosscert;
import kr.co.udapsoft.ebid.buyer.common.file.FileManager;

import com.udapsoft.modular.web.ibsheet7.IBSheet7Factory;
import com.udapsoft.modular.web.ibsheet7.util.IBSheet7Utils;
import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;


import crosscert.Base64;
import crosscert.Certificate;
import crosscert.Decrypt;
import crosscert.PrivateKey;
import crosscert.Verifier;






public class SuppSearchIdBiz extends Biz {
    
    Crosscert Crosscert = new Crosscert();

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

	/* (non-Javadoc)
	 * @see kr.co.hwenc.system.Biz#doBiz()
	 */
	public void doBiz() throws Exception 
	{
		//System.out.println("SuppSearchIdBiz event==============>" + storage.getEvent());
		
		
		if(storage.compareEvent(""))
		{
		    
		}
		else if(storage.compareEvent("GET_EMAIL"))
        {
		    params.set("sheet1", getCorpInfoList(params));
            storage.addObject("ibsheet7Data", IBSheet7Factory.createIBSheet7(params, storage.request));
        }
		else if(storage.compareEvent("SEND_EMAIL"))
        {
		    boolean success = false;
		    String pass = getRandomPassWd();
		    success = defaultSuppInfo(params, pass);
		    
		    //System.out.println("success===>" + pass);
		    
		    if(success == true)
		    {
		    	
                MessageSend messageSend = new MessageSend(storage);
                
                //EMAIL
                String subject = "문의하신  ID/PW 입니다.";
                String subject_in = "문의하신 ID/PW 입니다.<br/>ID는 " + params.get("p_user_id") + " 이며<br/>패스워드는 " + pass + "로 초기화 되었습니다.";
                String subject_sms_in = "문의하신 ID/PW 입니다.'||CHR(13)||CHR(10)||'ID는 " + params.get("p_user_id") + " 이며 패스워드는  " + pass +"로 초기화 되었습니다.'||CHR(13)||CHR(10)||'SGC이앤씨";
                //String subject_sms_in = "문의하신 ID/PW 입니다.'||CHR(13)||CHR(10)||'ID는 aaaaaaaaaaaaaaaaaaa 이며 패스워드는  \"1111\" 로 초기화 되었습니다.'||CHR(13)||CHR(10)||'SGC이앤씨";
                String email = params.get("p_email");
                String hp = params.get("p_hp");
                
                StringBuffer mailContent = new StringBuffer();
//                mailContent.append( WAFMessages.getMessage("Complete.approved.Supplier.Mail.Content") );
                mailContent.append(subject_in);
                
                if(!email.isEmpty()){
                	messageSend.sendEmail(email, "etec", subject, subject, mailContent);
                }
                
                RowSet rsUserInfo = getSMS(params.get("p_corp_id"));
                String shp = rsUserInfo.getRow(0).get("SPH");
                
                if(!hp.isEmpty()){
                	messageSend.sendSMS(hp.replace("-", ""),shp,"", subject_sms_in); //2015.9.21 구매,외주 번호로 전송 
                }
                
                
                
		    }
		    
		    super.storage.setSuccess(success);
            storage.addObject("ibsheet7Data", IBSheet7Factory.createIBSheet7(params, storage.request));
        }
	}
	
	//password create
	public String getRandomPassWd() {
		String passWord = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234507890abcdefghijklmnopqrstuvwxyz";
		String pass = "";
		
		float n = 0 ;
		int i = 0 ;		
		int len = 8;
		
		for(int k=1; k<=len; k++){		
			n = (float) (Math.random()*62);		
			i = Math.round(n);		
			pass += passWord.charAt(i); 		
		}
        return pass;
    }
	
	 /**
     * 회사정보 저장
     * @param params
     * @return
     * @throws Exception
     */
    private boolean defaultSuppInfo(ValueObject params, String pass) throws Exception
    {
        
        Persistent persistent = null;
        StringBuffer sqlstr = new StringBuffer();
        
        
        try{
            
            conn.begin();
            persistent = new PersistentImpl(super.conn.getConnection());
            
            
            sqlstr.append("     UPDATE SUPP_CHARGE SET            \n")
                   .append("           PASSWD = F_SHA256('" + pass + "')              \n") //SHA256
                   .append("      WHERE CORP_ID = ?                 \n")
                   .append("      AND DEFAULT_YN = 'Y'                 \n");
            
            
            persistent.setStatement(sqlstr.toString());
            persistent.addParameter(params.get("p_corp_id").trim());
            
            //System.out.println(persistent.getParameters());
            //System.out.println(sqlstr.toString());
            
            
            persistent.execute();
            persistent.clearParameters();
            
            return true;
            
            
        } catch(Exception e) {
            //System.out.println("updateInfo====>" + e);
            e.printStackTrace();
            conn.setRollback();
            throw e;
            
        }
        
        finally {
            super.conn.end();
        }
    }
	
	
	public RowSet getCorpInfoList(ValueObject params){
        Search search = new SearchImpl();
        ValueObject vo = null;
        RowSet rowSet = new RowSetImpl();
        
        StringBuffer sqlstr = new StringBuffer();
        
        
        try{
            
                sqlstr.append("                 SELECT                      \n");
                sqlstr.append("                          A.CORP_ID          \n");
                sqlstr.append("                        , A.JOB_DIV          \n");
                sqlstr.append("                        , DECODE(A.JOB_DIV, 'P', '구매', '외주') JOB_DIV_NAME          \n");
                sqlstr.append("                        ,B.EMAIL          \n");
                sqlstr.append("                        ,B.HP1||'-'||HP2||'-'||HP3 AS HP          \n");
                sqlstr.append("                        ,USER_ID          \n");
                sqlstr.append("                        ,USER_NAME          \n");
                sqlstr.append("                        ,SUBSTR(USER_ID, 0, LENGTH(USER_ID)-3) || '***' USER_ID_GET          \n");
                sqlstr.append("                    FROM SUPP_INFO A, SUPP_CHARGE B          \n");
                sqlstr.append("                    WHERE A.CORP_ID = B.CORP_ID          \n");
                sqlstr.append("                        AND B.DEFAULT_YN = 'Y'          \n");
                sqlstr.append("                        AND A.JOB_DIV = ?          \n");
                sqlstr.append("                        AND CORP_REG_NO = ?                           \n");
                sqlstr.append("                        AND A.STATUS  IS NOT NULL                          \n");
                sqlstr.append("                        AND A.STATUS NOT IN ('00')                           \n");
            
            
            search.setStatement(sqlstr.toString());
            search.addParameter(params.get("p_job_div_gubun"));
            search.addParameter(params.get("p_corp_reg_no"));
            
            
             
            search.setStatement(sqlstr);
            rowSet = search.execute();
            
        }catch(Exception e){
            e.printStackTrace();
            //System.out.println("getCorpInfoList===>" + e);
            
        }finally{
            return rowSet;
        }
    }
	
    
	//2015.10.16
	public RowSet getSMS(String corp_id) throws Exception{
        
        Search search = new SearchImpl();
        RowSet rowSet = new RowSetImpl();
        
        StringBuffer sqlstr = new StringBuffer();       
        
        try {
            sqlstr.append("  SELECT DETAILNM SPH                           \n");
            sqlstr.append("    FROM SUPP_INFO A, EBID_COM911T B            \n");
            sqlstr.append(" WHERE A.CORP_ID = "+corp_id+"                  \n");
            sqlstr.append("   AND B.BASECD = 'SMS'                         \n");
            sqlstr.append("   AND B.DETAILCD = A.JOB_DIV                   \n");
            
            search.setStatement(sqlstr.toString());
            rowSet = search.execute();            
        }
        catch(WAFSQLException se) {
            se.printStackTrace();
            throw se;
        }
        finally {
            if( rowSet == null ) rowSet = new RowSetImpl();
            return rowSet;
        }
    }
}