/**
 * @(#)file    QuotPlanSaveBiz.java
 * @(#)author  hooonseok choi
 * @(#)date    2023.01.19
 * Copyright (c) www.udapsoft.co.kr, Inc.
 */
package kr.co.udapsoft.ebid.supplier.portal.quot.biz;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import kr.co.hsnc.common.base.WAFLogger;
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 oracle.toplink.internal.ox.StrBuffer;

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;

public class QuotPlanSaveBiz extends Biz { 

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

	public void doBiz() throws Exception {
		boolean success = false;
		
		try {
			super.conn.begin();

			Connection connection = super.conn.getConnection();

			if (storage.compareEvent("UPDATE_QUOT_DETAIL")) {  //저장
				success = updateQuotDetail(connection, params);
				super.storage.setSuccess(success);
			}else if (storage.compareEvent("FINISH_QUOT_DETAIL")) {
				String fileCnt = getFileCnt(params);
				System.out.println("fileCnt : "+fileCnt);
	            if( "0".equals(fileCnt) ){
	            	super.storage.setSuccess(false);
	            	storage.setMessage("외부파일을 등록해 주시기 바랍니다.");
	            	return;
	            }else{
	            	success = updateQuotDetail(connection, params);
	            	if(success){					
	            		ValueObject SuppInfo = quot_bid_supp_info(params);
						
						MessageSend messageSend = new MessageSend(storage);
			     		StringBuffer mailtitle = new StringBuffer();
			     		StringBuffer mailtitlein = new StringBuffer();
			            StringBuffer mailContent = new StringBuffer();
			            
			            mailtitle.append("* 견적서 제출완료 공지 메일입니다.");
			            mailtitlein.append("* 견적서(견적지원) 제출완료에 대한 공지 메일입니다.");
			            mailContent.append("아래와 같은 내용으로 견적서 제출하였습니다.<br>전자조달 시스템에 접속하시어 견적서 및 자료 확인바랍니다.<br><br>");
			        	mailContent.append("<font style='width:auto; font-size:12px; line-height:18px; padding:5px; text-align:left;'>");
			        	mailContent.append("<br>");
			         	mailContent.append("1.프로젝트 : " + SuppInfo.get("DEPT_NM") + "<br>");
			         	mailContent.append("2.공고번호 : " + SuppInfo.get("QUOT_BID_NO") + "<br>");
			         	mailContent.append("3.공고차수 : " + SuppInfo.get("QUOT_BID_DEG") + "<br>");
			         	mailContent.append("4.공고건명 : " + SuppInfo.get("QUOT_BID_MASTER_NM") + "<br>");
			         	mailContent.append("5.제출업체 : " + SuppInfo.get("VENDOR_NAME") + "<br>");
			         	if(params.get("SITE_ATTEND_YN")=="Y")	mailContent.append("6.견적금액 : " + SuppInfo.get("ESTI_TOT_AMT")+ "<br>");
			         	else{
			         		mailContent.append("6.불참사유" + "<br>");
			         		mailContent.append(SuppInfo.get("SITE_ATTEND_REASON").replaceAll("\n", "<BR>") + "<br>");
			         	}
			         	
			         	mailContent.append("</font>");
			         	
		         		messageSend.sendEmail(SuppInfo.get("CHARGE_EMAIL"), "partner@sgc.co.kr", mailtitle.toString(), mailtitlein.toString(), mailContent,"NO_LINK");
//	         			messageSend.sendSMS(row.get("CHAGE_HP"),"", email_info.get("QUOT_MAN_ID"), "견적서(견적지원) 제출바랍니다.'||CHR(13)||CHR(10)||'협력업체포탈시스템에 접속/확인바랍니다.'||CHR(13)||CHR(10)||'SGC이앤씨(주)");
			         	super.storage.setSuccess(true);
					}
					super.storage.setSuccess(success);
	            }
			}
		} catch (Exception e) {
		    	System.out.println("doBiz" + e );
				WAFLogger.error(e);
				super.doException(e);
				storage.addObject("ibsheet7Data", IBSheet7Utils.exceptionHandle(storage.request, e));
				super.storage.setMessage(e.getMessage());
				super.storage.setDetailMessage(e);

				super.conn.setRollback();
				super.storage.setSuccess(false);
		} finally {
			super.conn.end();
		}
	}

	public boolean updateQuotDetail(Connection connection, ValueObject params) throws Exception {
		Persistent persistent = null;
		StringBuffer sql = new StringBuffer();

		sql.append("	UPDATE QUOT_BID_SUPP SET 		\n");
		sql.append("		  ESTI_TOT_AMT = '"+params.get("ESTI_TOT_AMT")+"'				\n");
		sql.append("		, REMARK = ?													\n");
		sql.append("		, ATT_ID = '"+params.get("ATT_ID")+"'       					\n");
		sql.append("		, BID_STATUS_CD = '"+params.get("BID_STATUS_CD")+"'				\n");
		sql.append("		, SITE_ATTEND_YN = '"+params.get("SITE_ATTEND_YN")+"'			\n");
		sql.append("		, SITE_ATTEND_REASON = '"+params.get("SITE_ATTEND_REASON")+"'	\n");
		if (storage.compareEvent("FINISH_QUOT_DETAIL")){
			sql.append("	, SUBMIT_DT = sysdate											\n");
		}
		sql.append("		, UPD_BY = '"+storage.getUser().get("CORP_ID")+"'			 	\n");
		sql.append("		, UPD_DATE = sysdate       										\n");
		sql.append("	WHERE QUOT_BID_NO = '"+params.get("QUOT_BID_NO")+"'   				\n");
		sql.append("	  AND QUOT_BID_DEG = '"+params.get("QUOT_BID_DEG")+"'   			\n");
		sql.append("	  AND VENDOR_CD = '"+params.get("VENDOR_CD")+"'   					\n");
		try {
			persistent = new PersistentImpl(connection);
			persistent.setStatement(sql.toString());
			persistent.addParameter(params.get("REMARK"));
			WAFLogger.debug(sql.toString());
			persistent.execute();
			persistent.clearParameters();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			super.storage.setMessage(e.getMessage());
			super.storage.setDetailMessage(e);
			throw e;
		}
	}
	
	private String getFileCnt(ValueObject params) {
        
        Search search = new SearchImpl();
        String sqlstr = "";
        try {
            sqlstr 	= 	"select NVL(count(*),0) CNT 					\n"
            		+	"  from pub0500t a, pub0510t b					\n"
		            +	"  where a.file_id = b.file_id					\n"
		            +	"  and file_gb = 'QUOT_SUPP_"+params.get("VENDOR_CD")+params.get("QUOT_ID")+"'		\n";

            search.setStatement(sqlstr);
            return search.execute().getRow(0).get("CNT");
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> getFileCnt() : " + e.getMessage());
            WAFLogger.error("SQL : " + search.getStatement());
            WAFLogger.error(e);
            return null;
        }
    }
	
	public ValueObject quot_bid_supp_info(ValueObject param) {

		Search search = new SearchImpl();
		 ValueObject valueobject = null;
		RowSet rowSet = new RowSetImpl();
        
        StrBuffer sqlstr = new StrBuffer();
        try{ 
        	sqlstr.append("	SELECT a.DEPT_NM,a.QUOT_BID_NO,A.QUOT_BID_DEG,A.QUOT_BID_MASTER_NM,B.VENDOR_NAME,B.ESTI_TOT_AMT,B.charge_email	\n");
			sqlstr.append("	  FROM QUOT_BID_MASTER A, QUOT_BID_SUPP B								\n");
			sqlstr.append("	 WHERE A.QUOT_BID_NO	= '"+param.get("QUOT_BID_NO")+"'				\n");
			sqlstr.append("	   AND A.QUOT_BID_DEG 	= '"+param.get("QUOT_BID_DEG")+"'				\n");
			sqlstr.append("	   AND B.VENDOR_CD 		= '"+params.get("VENDOR_CD")+"'   				\n");
			sqlstr.append("	   AND A.QUOT_BID_NO = B.QUOT_BID_NO									\n");
			sqlstr.append("	   AND A.QUOT_BID_DEG = B.QUOT_BID_DEG   								\n");
        	search.setStatement(sqlstr.toString());
			search.setStatement(sqlstr.toString());
			search.setStatement(sqlstr.toString());
            rowSet = search.execute();
            if( rowSet != null && rowSet.size() > 0 ){
            	valueobject = RowSetUtility.getValueObject(rowSet.getRow(0));
            }
        }
        catch (WAFSQLException se) {
            Logger.err.println("SQL : \n" + se.getStatement());
            Logger.err.println("PARAM : \n" + se.getParameter());
        }
        return valueobject;
	}
}
