package com.eactive.eai.batch.job.jobItem.school;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import com.eactive.eai.batch.job.jobItem.DefaultTelegram;
import com.eactive.eai.batch.job.jobItem.TelegramService;

import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.osd.OutsideVO;
import com.eactive.eai.batch.rule.dirInfo.BatchJobInfoVO;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.common.exception.ExceptionUtil;


public class RECV_SCBANK_100 extends DefaultTelegram implements TelegramService
{
    /**
     * 생성자
     */
    public RECV_SCBANK_100() {
        //송신 파일 통보
    }

    /**
     * 전문 해체하기
     */
    public boolean doExecute() {
        if (!super.doExecute()) return false;

        try{
            String fileName = new String ((byte[]) al_Field.get(5)).trim();
//            String endGb = new String ((byte[]) al_Field.get(11));
            //파일명으로 부터 거래 구분 코드 추출
    		int bizCodeStartIndex = 0;
    		int bizCodeEndIndex   = 0;
    		String processCode = batchDoc.getBatchMsg().getHeader().getProcessCode();
    		String institutionCode = batchDoc.getBatchMsg().getHeader().getInstitutionCode();
    		ArrayList<OutsideVO> organList = OutsideManager.getInstance().getOutsideInfo(processCode);
    		for (int i=0; organList!=null && i<organList.size(); i++) {
    			OutsideVO organInfo = organList.get(i);
    			if ( institutionCode.equals(organInfo.getOsdCode()) ) {
    				bizCodeStartIndex = organInfo.getBizCdStartIdx();
    				bizCodeEndIndex   = organInfo.getBizCdEndIdx();
    				break;
    			}
    		}
    		if (bizCodeStartIndex <= 0 || bizCodeStartIndex >= fileName.length()) bizCodeStartIndex = 0;
    		if (bizCodeEndIndex   <= 0 || bizCodeEndIndex   >  fileName.length()) bizCodeEndIndex = fileName.length();
            String bizCode = fileName.substring(bizCodeStartIndex, bizCodeEndIndex);

            long fileSize = Long.parseLong(new String ((byte[]) al_Field.get(6)));     //화일 size
            String bizFld = new String ((byte[]) al_Field.get(3));
            String basedate = bizFld.substring(6, 14);
//            batchDoc.getEAIBatchMessage().getHeader().setFileName(bizCode+"RE");
            batchDoc.getBatchMsg().getHeader().setFileName(fileName);
            batchDoc.getBatchMsg().getHeader().setFileSize(fileSize);
            batchDoc.getBatchMsg().getHeader().setBizCode(bizCode);
            batchDoc.getBatchMsg().getHeader().setBaseDate(basedate);
            batchDoc.getBatchMsg().getBody().setSeqNum(0);
            batchDoc.getBatchMsg().getBody().setCurFileSize(0);
            BatchJobInfoVO vo = DirInfoManager.getInstance().getFileInfoByDstcd(processCode, bizCode);
            if ( vo != null ){
            	batchDoc.getBatchMsg().getHeader().setJobCode(vo.getBatchCode());
            	batchDoc.getBatchMsg().getHeader().setRecLen((int)vo.getFileRecSize());
            //}	// 20250910 npe
            	
            	try {
                	batchDoc.getBatchMsg().getHeader().setTotRecCnt(fileSize/(int)vo.getFileRecSize());
    			} catch (Exception e) {
    	        	batchDoc.getBatchMsg().getHeader().setTotRecCnt(1);
    			}
            }
        	
//            if ( endGb.equalsIgnoreCase(TelegramKeys.MAGICLINK_END)) {
//                this.setConditionTxt(TelegramKeys.NOFILE);
//            }

        } catch ( Exception e) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI001";
            String errMsg = ExceptionUtil.getErrorCode (e, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( e.getMessage(), e);
            return false;
        }
        return true;
    }

    /**
     * 전문 Validation
     */
    public boolean doValidation()
    {
        if (!super.doValidation()) return false;

        return true;
    }

    public boolean doPostExecute() {
        if (!super.doPostExecute()) return false;
        try {
			//DB로그에 남길 전문 헤더 설정
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            for (int i=0; i<5; i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramHeader(new String(baout.toByteArray()));

            //DB로그에 남길 전문 바디 설정
            baout = new ByteArrayOutputStream();
            for (int i=5; i< al_Field.size(); i++) {
                baout.write((byte[])this.al_Field.get(i));
            }
            batchDoc.getBatchMsg().setTelegramBody(new String(baout.toByteArray()));

            return true;

        } catch(Exception ex) {
            String[] msgArgs = new String[1];
            msgArgs[0] = this.batchDoc.getBatchMsg().getHeader().getProcessCode();
            String errCode = "BECEAIFJI002";
            String errMsg = ExceptionUtil.getErrorCode (ex, errCode, msgArgs);
            this.batchDoc.getBatchMsg().getBody().setErrorMsg(errMsg);
            logger.error( ex.getMessage(), ex);
            return false;
        }
    }

    //---------------- 특정 필드값을 구하는 부분
    // 전문종별코드 필드값 리턴
    public String getTelegramType()
    {
		return super.getFieldValueString(1);
    }
    //응답코드 필드값 리턴
    public String getResCode()
    {
		return super.getFieldValueString(2);
    }
}
