/**
 * @(#)file    UserListSaveBiz.java
 * @(#)author  gyeongmo an
 * @(#)date    2014.6.24
 * Copyright (c) www.udapsoft.co.kr, Inc.
 */

package kr.co.udapsoft.ebid.buyer.sycs.user.biz;


import java.net.URLDecoder;
import java.sql.Connection;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.base.WAFMessages;
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 com.udapsoft.waf.system.Biz;
import com.udapsoft.waf.system.HandlerStorage;


public class UserListSaveBiz extends Biz {

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

	public void doBiz() throws Exception {
		
		String event = storage.getEvent();
        boolean success = false;

        params.set("login_user", storage.getUser().get("ACCT_ID"));
        success = saveUserProc(event, params);
        storage.setSuccess(success);
	}
	
	public boolean saveUserProc(String event, ValueObject valueObject) {

        try {
            conn.begin();

            if( event.equals("SAVE_USER_LIST") ) {
            	
                updUser(conn.getConnection(), valueObject);
            }
            else if( event.equals("UserForm_Reg") ) {

                UserManager userManager = new UserManager();
                params.set("acct_id", userManager.getAcctID(conn.getConnection()));
                regUser(conn.getConnection(), params);
            }else if(event.equals("SMS_TEST")){
            	
            	MessageSend messageSend = new MessageSend(storage);
            	String recvAddress = "01028093685";
         
            	String mailContent = WAFMessages.getMessage("Register.Supplier.Complete");
            	System.out.println(mailContent);
            	messageSend.sendSMS(recvAddress, "01028093685", storage.getUser().get("ACCT_ID"),mailContent);  //2015.9.21 테스트 전송 
            	
            	
         
            }else if(event.equals("EMAIL_TEST")){
            	
            	MessageSend messageSend = new MessageSend(storage);
            	StringBuffer mailContent = new StringBuffer();
            	messageSend.sendEmail("partner@sgc.co.kr", "partner@sgc.co.kr", "test 입니다.", "test", mailContent);
            	
            }else if( event.equals("SAVE_PWD_INIT") ) {
            	
                updUserPwdInit(conn.getConnection(), valueObject);
            }

            
            if( !valueObject.get("selected_right_ids").equals("") ) {

                updUserRight(conn.getConnection(), valueObject);
            }
            
            storage.setMessage("1111");
            storage.setDetailMessage("2222222222");
            return true;
        }
        catch(Exception e) {
    
            WAFLogger.error(this.getClass().getName() + " --> saveUserProc() : " + e.getMessage());
            WAFLogger.error(e);
            conn.setRollback();

            storage.setDetailMessage(e);
            storage.setMessage(e.getMessage());
            return false;
        }
        finally {
            conn.end();
        }
    }
		
	public void updUser(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {
            sqlstr += " UPDATE PUB0120T                \n"
                    + " SET    USER_PW      = ? ,      \n"
                    + "        ACCT_TYPE_ID = ? ,      \n"
                    + "        TEL_NO       = ? ,      \n"
                    + "        HAND_TEL_NO  = ? ,      \n"
                    + "        FAX_NO       = ? ,      \n"
                    + "        E_MAIL       = ? ,      \n"
                    + "        CERT_DN      = ? ,      \n"
                    + "        RIGHT_GB     = ? ,      \n"
                    + "        UPD_BY       = ? ,      \n"
                    + "        UPD_DATE     = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'),  \n"
                    + "        PSOSO   		= ? ,						       		 \n"
                    + "        BUSEO   		= ? ,						       		 \n"
                    + "        INACTIVE_DATE = to_date(?) 						     \n"
                    + " WHERE  ACCT_ID      = ?        \n" ; 
            
            
            persistent.setStatement(sqlstr);
            persistent.addParameter(valueObject.get("user_pw"));
            persistent.addParameter(valueObject.get("acct_type_id"));
            persistent.addParameter(valueObject.get("tel_no"));
            persistent.addParameter(valueObject.get("hand_tel_no"));
            persistent.addParameter(valueObject.get("fax_no"));
            persistent.addParameter(valueObject.get("e_mail"));
            persistent.addParameter(valueObject.get("cert_dn"));
            persistent.addParameter(valueObject.get("right_gb"));           
            persistent.addParameter(valueObject.get("login_user"));
            persistent.addParameter(valueObject.get("job_Cd"));
            persistent.addParameter(valueObject.get("dept_cd"));
            persistent.addParameter(valueObject.get("inactive_date").replace("-", ""));
            
            persistent.addParameter(valueObject.get("acct_id"));
            
            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> updUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            throw e;
        }
    }
	
	/**
     * 사용자 등록
	 * @param connection
	 * @param valueObject
	 * @throws Exception
	 */
	public void regUser(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {
            sqlstr += " INSERT INTO PUB0120T                                        \n"
                    + " ( ACCT_ID, USER_SABUN, USER_PW, ACCT_TYPE_ID, TEL_NO,       \n"
                    + "   HAND_TEL_NO, FAX_NO, E_MAIL, CERT_DN, RIGHT_GB,           \n"
                    + "   CRE_BY, CRE_DATE,											\n"
                    + "   GRADE_CODE, GRADE_NAME, DUTYC, PSOSO, BUSEO, USER_NAME)   \n"
                    + " VALUES                                                      \n"
                    + " ( ?, ?, ?, ?, ?,                                            \n"
                    + "   ?, ?, ?, ?, ?, ?, TO_CHAR(SYSDATE, 'YYYYMMDDHH24MI'),		\n"
                    + "   ?, ?, ?, ?, ?, ?)     									\n" ;
            
            persistent.setStatement(sqlstr);
            persistent.addParameter(valueObject.get("acct_id"));
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.addParameter(valueObject.get("user_pw"));
            persistent.addParameter(valueObject.get("acct_type_id"));
            persistent.addParameter(valueObject.get("tel_no"));
            
            persistent.addParameter(valueObject.get("hand_tel_no"));
            persistent.addParameter(valueObject.get("fax_no"));
            persistent.addParameter(valueObject.get("e_mail"));
            persistent.addParameter(valueObject.get("cert_dn"));
            persistent.addParameter(valueObject.get("right_gb"));
            persistent.addParameter(valueObject.get("login_user"));
            
            persistent.addParameter(valueObject.get("buseo_Cd"));
            persistent.addParameter(valueObject.get("buseo_nm"));
            persistent.addParameter(valueObject.get("10"));
            persistent.addParameter(valueObject.get("job_Cd"));
            persistent.addParameter(valueObject.get("dept_cd"));
            persistent.addParameter(valueObject.get("user_name"));
            
            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> regUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            throw e;
        }
    }
	
	public void updUserRight(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {
            String rightIDs = URLDecoder.decode(valueObject.get("selected_right_ids"), "UTF-8");

            sqlstr += " DELETE                                                                \n"
                    + " FROM   PUB0350T                                                       \n"
                    + " WHERE  RIGHT_ID NOT IN ( SELECT RIGHT_ID                              \n"
                    + "                          FROM   PUB0350T A,                           \n"
                    + "                                 PUB0120T B                            \n"
                    + "                          WHERE  A.ACCT_ID = B.ACCT_ID                 \n"
                    + "                          AND    B.USER_SABUN = ?                      \n"
                    + "                          AND    A.RIGHT_ID IN ( " + rightIDs  + ") )  \n"
                    + " AND    ACCT_ID = ( SELECT ACCT_ID                                     \n"
                    + "                    FROM   PUB0120T                                    \n"
                    + "                    WHERE  USER_SABUN = ? )                            \n" ;
            persistent.setStatement(sqlstr);
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.execute();

            persistent.clear();

            sqlstr = " INSERT INTO PUB0350T                                                        \n"
                   + " ( RIGHT_LIST_ID, RIGHT_ID, ACCT_ID, CRE_BY, CRE_DATE )                      \n"
                   + " ( SELECT PUB0350T_S.NEXTVAL,                                                \n"
                   + "          RIGHT_ID,                                                          \n"
                   + "          ( SELECT ACCT_ID FROM PUB0120T WHERE USER_SABUN = ? ) AS ACCT_ID,  \n"
                   + "          ?,                                                                 \n"
                   + "          TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS')                                                            \n"
                   + "   FROM   PUB0340T                                                           \n"
                   + "   WHERE  RIGHT_ID NOT IN ( SELECT RIGHT_ID                                  \n"
                   + "                            FROM   PUB0350T A,                               \n"
                   + "                                   PUB0120T B                                \n"
                   + "                            WHERE  A.ACCT_ID = B.ACCT_ID                     \n"
                   + "                            AND    B.USER_SABUN = ? )                        \n"
                   + "   AND    RIGHT_ID IN ( " + rightIDs  + " ) )                                \n" ; 
            persistent.setStatement(sqlstr);
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.addParameter(valueObject.get("login_user"));
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.execute();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> regUser() : " + e.getMessage());
            WAFLogger.error("SQL : " + sqlstr);
            WAFLogger.error(e);
            throw e;
        }
    }
	
	public void updUserPwdInit(Connection connection, ValueObject valueObject) throws Exception {

        Persistent persistent = new PersistentImpl(connection);
        String sqlstr = "";
        try {
            sqlstr += " UPDATE PUB0120T                          \n"
                    + " SET    USER_PW         = F_SHA256(?)     \n"
                    + "   ,    PWD_VALID_CNT   = 5               \n"
                    + "   ,    PWD_VALID_FROM  = TO_DATE(TO_CHAR(SYSDATE+180,'YYYYMMDD'))    \n"
                    + " WHERE  ACCT_ID         = ?               \n" ; 
            
            
            persistent.setStatement(sqlstr);
            persistent.addParameter(valueObject.get("user_sabun"));
            persistent.addParameter(valueObject.get("acct_id"));
            
            persistent.execute();
        }
        catch(Exception e) {

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

}
