/**
 * @(#)file    FileListWorkerSaveHtmlBiz.java.java
 * @(#)author  chj
 * @(#)version 1.0
 * @(#)date    2014-06-24
 * @(#)since   JDK1.6
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 */
package kr.co.udapsoft.ebid.buyer.common.file.biz;


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

import kr.co.hsnc.common.base.WAFLogger;
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.sql.util.RowSetUtility;
import kr.co.hsnc.common.util.StringUtil;
import kr.co.hsnc.common.util.ValueObject;
import kr.co.hsnc.j2ee.components.multipart.UploadedFile;

import com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;

/**
 * 첨부파일을 저장 처리 Biz
 * 
 * @author 
 */
public class FileListWorkerSaveHtmlBiz extends Biz {

	public FileListWorkerSaveHtmlBiz(HandlerStorage storage) {

		super(storage);
	}

	/**
     * 첨부파일을 저장 처리한다.
	 */
	public void doBiz() throws Exception {

        String fileGB = params.get("file_gb");
        String ID     = params.get("id");
        String modNo  = params.get("mod_no");
        String acctid = params.get("acct_id") + "0";  //2017.10.10 경영정보 호출시 id 긑자리0은 FROM 경영정보 
        if(acctid.length() <= 1 && storage.getUser() != null ) acctid = String.valueOf(storage.getUser().getInt("ACCT_ID")); //2017.10.10 전자조달 호출시 
       
        WAFLogger.debug("fileGB===>" + fileGB);
        WAFLogger.debug("ID===>" + ID);
        WAFLogger.debug("modNo===>" + modNo);
        WAFLogger.debug("acctid===>" + acctid);
        
        if( storage.isMultiPart() ) {
        	
        	boolean success = false;
        	
        	UploadedFile [] fileList = storage.getUploadedFiles("attach_file");

        	for(int i=0;i<fileList.length;i++){
        		
        		String fileName    = fileList[i].getOriginalFileName();
        		WAFLogger.debug("fileName===>" + fileName);
        		
            	if(!"".equals(params.get("user_filename")) && params.get("user_filename") != null){
            		int pos = fileList[i].getOriginalFileName().lastIndexOf( "." );
            		String ext = fileList[i].getOriginalFileName().substring( pos + 1 );
            		fileName = params.get("user_filename")+"_"+fileList[i].getOriginalFileName();
            		//fileName = params.get("user_filename")+"_"+fileName;
            	}
            	WAFLogger.debug("fileName===>" + fileName);
            	
                String contentType = fileList[i].getFilesystemName();
                File file          = fileList[i].getFile();
                
                success = addFilesProc(file, fileName, contentType, fileGB, ID, modNo, acctid);
        	}
        	
        	//String fileName    = storage.getOriginalFileName("attach_file");
            //String contentType = storage.getContentType("attach_file");
            //File file          = storage.getFile("attach_file");
            //boolean success = addFilesProc(file, fileName, contentType, fileGB, ID, modNo);
        	
            storage.setSuccess(success);
        }
        else {
            storage.setSuccess(false);
            storage.setMessage("Multipart/form-data 형식의 데이타가 전송되지 않았습니다.");
        }
	}

    /**
     * 변경(추가 0802 SMH) 첨부파일정보를 추가 처리한다.
     * @param files
     * @param fileNames
     * @param fileGB
     * @param ID
     * @return
     */
	public boolean addFilesProc(String fileGB, String ID, String modNO, String acctid) {
        try {
        	this.conn.begin();
		
			for( int i = 0 ; i < params.getInt("file_count") ; i++ ) {
    			File file          = this.storage.getFile("file" + (i+1));
                String fileName    = this.storage.getOriginalFileName("file" + (i+1));
                String contentType = this.storage.getContentType("file" + (i+1));

                if((fileGB.equals("PUR_M_CST")||fileGB.equals("SUB_M_CST")) && !modNO.equals("")){
                    addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, "F", modNO, acctid);
                }
                else {
                    addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, acctid);
                }
			}
            return true;
        }
        catch(Exception e) {
            WAFLogger.error(this.getClass().getName() + " --> addFilesProc() : " + e.getMessage());
            WAFLogger.error(e);
            this.conn.setRollback();
            this.storage.setMessage(e.getMessage());
            this.storage.setDetailMessage(e);
            return false;
        }
        finally {
        	this.conn.end();
        }
	}
    /******
     * 
     * 기존 방식으로  참조 변경 
     * @param file
     * @param fileName
     * @param contentType
     * @param fileGB
     * @param ID
     * @param modNO
     * @return
     */
	public boolean addFilesProc(File file, String fileName, String contentType, String fileGB, String ID, String modNO, String acctid) {

        try {
            conn.begin();
            
            WAFLogger.debug("ID==============>" + ID);

            if((fileGB.equals("PUR_M_CST")||fileGB.equals("SUB_M_CST")) && !modNO.equals("")){
                
                addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, "F", modNO, acctid);
            } else {
                addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, acctid);

            }
            
//            if ( fileGB.equals("DEMANDED_INNER") || fileGB.equals("DEMANDED_OUTER") ||
//            		fileGB.equals("OUTSOURCING_DEMANDED_INNER") || fileGB.equals("OUTSOURCING_DEMANDED_OUTER") ) {
//            	String returnFileMapId = addDemandedFileMap(conn.getConnection(), fileGB, ID);
//            	addDemandedFile(conn.getConnection(), file, fileName, contentType, returnFileMapId);
//            }
            return true;
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFilesProc() : " + e.getMessage());
            WAFLogger.error(e);

            conn.setRollback();
            storage.setDetailMessage(e);
            return false;
        }
        finally {

            conn.end();
        }
    }
	public boolean addFilesProc(File file, String fileName, String contentType, String fileGB, String ID, String modNO ) {

        try {
            conn.begin();
            
            WAFLogger.debug("ID===acctid===========>" + ID);

            if((fileGB.equals("PUR_M_CST")||fileGB.equals("SUB_M_CST")) && !modNO.equals("")){                
                addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, "F", modNO, "0");
            } else {
                addFile(conn.getConnection(), file, fileName, contentType, fileGB, ID, "0");
            }
            
//            if ( fileGB.equals("DEMANDED_INNER") || fileGB.equals("DEMANDED_OUTER") ||
//            		fileGB.equals("OUTSOURCING_DEMANDED_INNER") || fileGB.equals("OUTSOURCING_DEMANDED_OUTER") ) {
//            	String returnFileMapId = addDemandedFileMap(conn.getConnection(), fileGB, ID);
//            	addDemandedFile(conn.getConnection(), file, fileName, contentType, returnFileMapId);
//            }
            return true;
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFilesProc() : " + e.getMessage());
            WAFLogger.error(e);

            conn.setRollback();
            storage.setDetailMessage(e);
            return false;
        }
        finally {

            conn.end();
        }
    }
    /**
     * 첨부파일정보를 추가 처리한다.
	 * @param connection
	 * @param file
	 * @param fileName
	 * @param contentType
	 * @param fileGB
	 * @param ID
	 * @throws Exception
	 */
	public void addFile(Connection connection, File file, String fileName, String contentType, String fileGB, String ID, String acctid) throws Exception {

        addFile(connection, file, fileName, contentType, fileGB, ID, "F", acctid);
    }

    /**
     * 첨부파일정보를 추가 처리한다.
	 * @param connection
	 * @param file
	 * @param fileName
	 * @param contentType
	 * @param fileGB
	 * @param ID
	 * @param addGB
	 * @throws Exception
	 */
	public void addFile(Connection connection, File file, String fileName, String contentType, String fileGB, String ID, String addGB, String acctid) throws Exception {

        String fileID = addFile(connection, file, fileName, contentType, acctid);
        addFileMap(connection, fileID, fileGB, ID, addGB, acctid);
    }

    //변경차수 추가
    public void addFile(Connection connection, File file, String fileName, String contentType, String fileGB, String ID, String addGB, String modNo, String acctid) throws Exception {

        String fileID = addFile(connection, file, fileName, contentType, acctid);
        addFileMap(connection, fileID, fileGB, ID, addGB, modNo, acctid);
    }

    /**
     * 파일 정보를 추가한다.
	 * @param connection
	 * @param file
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	private String addFile(Connection connection, File file, String fileName, String contentType, String acctid) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        ACCT_ID = Integer.parseInt(acctid); //2017.10.10 경영정보 아이디
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");        

        try {

            sqlstr = " INSERT INTO PUB0500T "
                   + " ( FILE_ID, REAL_FILE_NAME, FILE_NAME, FILE_PATH, FILE_EXT,  "
                   + "   FILE_SIZE, MINE_TYPE, CONTENT_TYPE, CONTENT_DISP, SUB_MINE_TYPE,  "
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( ?, ?, ?, ?, ?, "
                   + "   ?, ?, ?, ?, ?, "
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);

            String fileID = getFileID(connection);

            String defaultDir = WAFConfig.get("waf.repository.path");
            String path = StringUtil.replace( StringUtil.replace(file.getPath(), "\\", "/"), "/" + file.getName(), "");
            path = path.substring(defaultDir.length(), path.length());

            String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());

            fileName = StringUtil.replace( fileName, "\\", "/");
            //fileName = fileName.substring( fileName.lastIndexOf("/") + 1, fileName.length());

            persistent.addParameter(fileID);
            persistent.addParameter(file.getName());
            persistent.addParameter(fileName);
            persistent.addParameter(path);
            persistent.addParameter(ext);
            
            persistent.addParameter((int)file.length());
            persistent.addParameter("");
            persistent.addParameter(contentType);
            persistent.addParameter("");
            persistent.addParameter("");

            persistent.addParameter(ACCT_ID);

            persistent.execute();
            
//            WAFLogger.debug("파일 정보를 추가한다. sql->"+persistent.getStatement());
//            WAFLogger.debug("params->"+persistent.getParameters());

            return fileID;
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }

    /**
     * 파일맵을 추가한다.
	 * @param connection
	 * @return
	 * @throws Exception
	 */
    private String getFileID(Connection connection) throws Exception {

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

            sqlstr = " SELECT PUB0500T_S.NEXTVAL AS FILE_ID \n"
                   + " FROM   DUAL                          \n" ;

            persistent.setStatement(sqlstr);

            return persistent.query().getRow(0).get("FILE_ID");
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> getFileID() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }

    /**
	 * @param connection
	 * @param fileID
	 * @param fileGB
	 * @param ID
	 * @throws Exception
	 */
    private void addFileMap(Connection connection, String fileID, String fileGB, String ID, String addGB, String acctid) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        if(acctid != null) ACCT_ID = Integer.parseInt(acctid); //2017.10.10 경영정보 아이디
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");
        try {

            sqlstr = " INSERT INTO PUB0510T "
                   + " ( FILE_MAP_ID, FILE_ID, O_FILE_GB, O_ID, FILE_GB, ID, OPEN_CORP_YN, USE_CON_YN, ADD_GB, "
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( PUB0510T_S.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, "
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);

            persistent.addParameter(fileID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter("N");
            persistent.addParameter("Y");
            persistent.addParameter(addGB);
            persistent.addParameter(ACCT_ID);

            persistent.execute();

            //계약시 첨부파일 추가할 경우 계약문서 테이블에도 insert한다
            if(  fileGB.equals("SUB_G_CST") || fileGB.equals("SUB_M_CST")  
              || fileGB.equals("PUR_G_CST") || fileGB.equals("PUR_M_CST") ){
                addConDocFile(connection, fileID, fileGB, "0", ID);
            }
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }

    //변경차수 추가
    private void addFileMap(Connection connection, String fileID, String fileGB, String ID, String addGB, String modNo, String acctid) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        int ACCT_ID = 0;
        if(acctid != null) ACCT_ID = Integer.parseInt(acctid); //2017.10.10 경영정보 아이디
        if(storage.getUser() != null) ACCT_ID = storage.getUser().getInt("ACCT_ID");
        try {

            sqlstr = " INSERT INTO PUB0510T "
                   + " ( FILE_MAP_ID, FILE_ID, O_FILE_GB, O_ID, FILE_GB, ID, OPEN_CORP_YN, USE_CON_YN, ADD_GB, MOD_NO, " //변경차수 추가
                   + "   CRE_BY, CRE_DATE ) "
                   + " VALUES "
                   + " ( PUB0510T_S.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
                   + "   ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') ) " ;

            persistent.setStatement(sqlstr);

            persistent.addParameter(fileID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter(fileGB);
            persistent.addParameter(ID);
            persistent.addParameter("N");
            persistent.addParameter("Y");
            persistent.addParameter(addGB);
            persistent.addParameter(modNo); //변경차수 추가
            persistent.addParameter(ACCT_ID);

            persistent.execute();
            
            //계약시 첨부파일 추가할 경우 계약문서 테이블에도 insert한다
            if(  fileGB.equals("SUB_G_CST") || fileGB.equals("SUB_M_CST")  
              || fileGB.equals("PUR_G_CST") || fileGB.equals("PUR_M_CST") ){
                addConDocFile(connection, fileID, fileGB, modNo, ID);
            }
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }

    /**
     * 계약문서 테이블에 첨부파일을 추가한다.
     * 계약시 첨부문서 추가할 경우 사용된다.
     * @param connection
     * @param file
     * @param fileName
     * @return
     * @throws Exception
     */
    private void addConDocFile(Connection connection, String fileID, String fileGB, String modNo, String ID) throws Exception {

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

            if( fileGB.equals("PUR_G_CST") || fileGB.equals("PUR_M_CST") ){
                tableName = "PUR5080T";
                tableKey  = "CON_ADD_DOC_ID";
            }else if( fileGB.equals("SUB_G_CST") ||  fileGB.equals("SUB_M_CST") ){
                tableName = "SUB5510T";
                tableKey  = "CON_DOC_ID";
            }

            ValueObject vo = getConDocInfo(connection, tableName, ID, modNo);
            
            //계약생성이 된 이후에만 첨부문서를 추가한다.
            if( !vo.get("cst_doc_no").equals("") ){
            
                StringBuffer sql = new StringBuffer();
    
                sql.append(" insert into " + tableName + " (   \n");
                sql.append(tableKey + ",    dept_cd,          cst_doc_no,       mod_no,           file_map_id, \n");  
                sql.append(" unique_file_name,   file_path,        file_ext,         file_size,        file_name,   \n");
                sql.append(" mine_type,          contents_type,    contents_disp,    sub_mine_type,    cst_info_id, \n");
                sql.append(" cre_by,             cre_date)         \n");
                sql.append(" select                                \n");
                sql.append(tableName + "_s.nextval, ?,                ?,                ?,                f1.file_map_id, \n");
                sql.append(" f2.real_file_name,  ?,                f2.file_ext,      f2.file_size ,    f2.file_name,   \n");
                sql.append(" f2.mine_type,       f2.content_type,  f2.content_disp,  f2.sub_mine_type, f1.id,           \n");
                sql.append(" f2.cre_by,          f2.cre_date       \n");
                sql.append(" from   pub0510t f1, pub0500t f2       \n");
                sql.append(" where  f1.file_id=? and f1.use_con_yn = 'Y' and f1.file_id=f2.file_id   \n");                     
                
                persistent.setStatement(sql.toString());
                persistent.addParameter(vo.get("dept_cd"));            
                persistent.addParameter(vo.get("cst_doc_no"));            
                persistent.addParameter(modNo);                                    
                persistent.addParameter(vo.get("file_path"));                                                
                persistent.addParameter(fileID);
                persistent.execute();
            
            }

        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> addFile() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }

    /**
     * 첨부파일 맵 정보를 가져온다.
     * @param connection
     * @return
     * @throws Exception
     */
    private ValueObject getFileMapInfo(Connection connection, String fileID) throws Exception {

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

            sqlstr = " SELECT *                 \n"
                   + " FROM   PUB0510T          \n" 
                   + " WHERE  FILE_ID = ?       \n";

            persistent.setStatement(sqlstr);
            persistent.addParameter(fileID);
            
            return RowSetUtility.getValueObject(persistent.query().getRow(0));

        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> getFileMapInfo() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }


    /**
     * 계약문서 정보를 가져온다.
     * 계약시 첨부문서 추가할 경우 사용된다.
     * @param connection
     * @return
     * @throws Exception
     */
    private ValueObject getConDocInfo(Connection connection, String table, String ID, String modNo) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {
            
            sqlstr = " SELECT *                 \n"
                   + " FROM   " + table + "     \n" 
                   + " WHERE  CST_INFO_ID = ?   \n"
                   + " AND    MOD_NO      = ?   \n";

            persistent.setStatement(sqlstr);
            persistent.addParameter(ID);
            persistent.addParameter(modNo);

//            return RowSetUtility.getValueObject(persistent.query().getRow(0));

            RowSet rowset = persistent.query();
            
            if( rowset != null && rowset.size() > 0){
                return RowSetUtility.getValueObject(rowset.getRow(0));
            }else{
                ValueObject vo = new ValueObject();
                return vo;
            }

        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> getConDocInfo() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            storage.setDetailMessage(e);
            throw e;
        }
    }
    
   	
 	

}
