package eo.business.service;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import eo.business.common.JBSbatBusinessService;
import eo.business.common.JCCBatCommon;
import eo.business.common.JKKBatCommon;
import eo.business.common.JKKBatConst;
import eo.business.util.table.JBSbatCC_T_DLYD_TRN_REQ;
import eo.business.util.table.JBSbatKK_T_COURSE_TK_JKN;
import eo.business.util.table.JBSbatZM_T_DL_FILE_KANRI;
import eo.common.constant.JKKStrConst;
import eo.common.util.JCCFileUtil;
import eo.common.util.JKKCommonUtil;
import eo.common.util.JPCDateUtil;
import eo.framework.application.JBSbatBusinessBase;
import eo.framework.application.JBSbatBusinessException;
import eo.framework.application.JCCbatFrameworkException;
import eo.framework.db.JBSbatSQLAccess;
import eo.framework.file.JBSbatDefFileUtil;
import eo.framework.file.JBSbatInputFileUtil;
import eo.framework.file.JBSbatOutputFileUtil;
import eo.framework.item.JBSbatCommonDBInterface;
import eo.framework.item.JBSbatCommonItem;
import eo.framework.item.JBSbatOutputItem;
import eo.framework.item.JBSbatServiceInterfaceMap;
import eo.framework.util.JBSbatAplConst;
import eo.framework.util.JBSbatCheckUtil;

/**
 * 
 * @author ニール
 * 
 */
public class JBSbatKKSvctkareaUpd extends JBSbatBusinessService {
	private static final String STAT_TEXT = "未登録";
	private static final String ROW_NO_TEXT = "行目";
	private static final String ERROR_FILE_NAME_FORMAT = "サービス提供エリア更新結果_%s.csv";
	private static final String TK_JKN_TENDYMD_DEFAULT = "20991231";
	private static final String TEXT_VALUE_REGEX = "^\"?(.*?)\"?$";
	private static final String SYSTEM_DATE_DATE_REMOVAL_REGEX = "\\d{2}$";
	private static final String KKLST11201_DEF_INPUT = "KKLST11201.def";
	private static final String KKLST11202_DEF_OUTPUT = "KKLST11202.def";
	private static final String D_TBL_NAME_KK_T_COURSE_TK_JKN = "KK_T_COURSE_TK_JKN";
	private static final String D_TBL_NAME_ZM_T_DL_FILE_KANRI = "ZM_T_DL_FILE_KANRI";
	private static final String EMPTY_STRING = "";
	private static final String FILE_CD_COURSE_TK_JKN_INFO = "000000000191";

	/** テーブル(ダウンロードファイル管理) */
	private static final String SEQ_PREFIX_SEQ_FILE_NAME = "SEQ_FILE_NO";
	private static final String SEQ_PREFIX_SEQ_FILE_NO = EMPTY_STRING;

	private static final int SEQ_LEN_SEQ_FILE_NO = 12;
	private static final int FILE_UTIL_RECORD = 0;
	private static final int E_FILE_KANRI_NO_INDEX = 0;
	private static final int EMPTY_FILE_ROW_NUMBER = 0;

	private JBSbatSQLAccess db_KK_T_COURSE_TK_JKN = null;
	/** テーブルアクセスクラス(ダウンロードファイル管理) */
	private JBSbatSQLAccess db_ZM_T_DL_FILE_KANRI = null;

	private enum InFileCheckCd {
		COURSE_TK_JKN_NOT_CSV(JKKStrConst.SVTA_NOT_CSV_ERR_ID, "File Extension"),
		COURSE_TK_JKN_ZERO_RSLT(JKKStrConst.SVTA_ZERO_RSLT_ERR_ID, ""),
		COURSE_TK_JKN_KMKSUU(JKKStrConst.SVTA_KMKSUU_ERR_ID, ""),
		COURSE_TK_JKN_HISSU_SVC_KEI_KAISEN_UCWK_NO(JKKStrConst.SVTA_HISSU_ERR_ID,
				"サービス契約回線内訳番号"),
		COURSE_TK_JKN_DIGITNO_SVC_KEI_KAISEN_UCWK_NO(JKKStrConst.SVTA_DIGITNO_ERR_ID,
				"サービス契約回線内訳番号"),
		COURSE_TK_JKN_ZOKU_SVC_KEI_KAISEN_UCWK_NO(JKKStrConst.SVTA_ZOKU_ERR_ID,
				"サービス契約回線内訳番号"),
		COURSE_TK_JKN_HISSU_TK_JKN_TSTAYMD(JKKStrConst.SVTA_HISSU_ERR_ID, "サービス提供エリア適用開始日"),
		COURSE_TK_JKN_DIGITNO_TK_JKN_TSTAYMD(JKKStrConst.SVTA_DIGITNO_ERR_ID,
				"サービス提供エリア適用開始日"),
		COURSE_TK_JKN_ZOKU_TK_JKN_TSTAYMD(JKKStrConst.SVTA_ZOKU_ERR_ID, "サービス提供エリア適用開始日"),
		COURSE_TK_JKN_DIGITNO_TK_JKN_TENDYMD(JKKStrConst.SVTA_DIGITNO_ERR_ID,
				"サービス提供エリア適用終了日"),
		COURSE_TK_JKN_ZOKU_TK_JKN_TENDYMD(JKKStrConst.SVTA_ZOKU_ERR_ID, "サービス提供エリア適用終了日");

		private final String code;
		private final String message;

		private InFileCheckCd(String code, String message) {
			this.code = code;
			this.message = message;
		}

		public String getCode() {
			return this.code;
		}

		public String getMessage() {
			return this.message;
		}
	}

	private enum ValidationCd {
		LENGTH_CHECK_8_STR(new String[] { "ketasuu1", "8" }),
		LENGTH_CHECK_12_STR(new String[] { "ketasuu1", "12" }),
		LENGTH_CHECK_14_STR(new String[] { "ketasuu1", "14" }),
		LENGTH_CHECK_16_STR(new String[] { "ketasuu1", "16" }),
		FORMAT_CHECK_STR(new String[] { "hannkakusuuji1" }),
		FORMAT_YMD_CHECK_STR(new String[] { "year_month_day1" }),
		FULL_WIDTH_CHECK_STR(new String[] { "hannkakusuuji1" });

		private final String[] value;

		private ValidationCd(String[] value) {
			this.value = value;
		}

		public String[] getValue() {
			return value;
		}
	}

	private enum ErrorCd {
		ROW_NO, TRAN_NITI, STAT,
		/** エラーID Error ID */
		ERR_ID,
		/** エラー項目（値） Error Value */
		ERR_KMK_VALUE,
		/** エラー項目（名称） Error Name */
		ERR_KMK_NM;
	}

	private enum KK_T_COURSE_TK_JKN_SQL {
		KK_INSERT_001, KK_DELETE_001;
	}

	/**
	 * Initialization of the objects and DB access.
	 */
	@Override
	public void initial(JBSbatCommonItem commonItem) throws Exception {
		super.setCommonInfo(commonItem);

		db_KK_T_COURSE_TK_JKN = new JBSbatSQLAccess(commonItem, D_TBL_NAME_KK_T_COURSE_TK_JKN);
		db_ZM_T_DL_FILE_KANRI = new JBSbatSQLAccess(commonItem,
				D_TBL_NAME_ZM_T_DL_FILE_KANRI);

		super.logPrint.printDebugLog("Initialization");
	}

	/**
	 * Clean-up or closing of the objects.
	 */
	@Override
	public void terminal() throws Exception {
		super.logPrint.printDebugLog("Doing cleanup");

		if (db_KK_T_COURSE_TK_JKN != null) {
			db_KK_T_COURSE_TK_JKN.close();
		}

		if (db_ZM_T_DL_FILE_KANRI != null) {
			db_ZM_T_DL_FILE_KANRI.close();
		}
	}

	/**
	 * Removal of the double qoute for the first and end of the string.
	 * 
	 * @param text
	 * @return String
	 */
	private String getStringValue(String text) {
		Pattern p = Pattern.compile(TEXT_VALUE_REGEX, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(text);
		String val = text;

		if (m.find()) {
			val = m.group(1);
		}

		return val;
	}

	/**
	 * Main method
	 * 
	 * @return JBSbatOutputItem
	 * @throws Exception
	 */
	public JBSbatOutputItem execute() throws Exception {
		super.logPrint.printDebugLog("Executing JBSbatKKSvctkareaUpd::execute()");
		ArrayList<HashMap<String, Object>> dlydTrnMapList = JKKBatCommon.getShoriIraiInfo(commonItem,
				commonItem.getJobid());

		if (JKKCommonUtil.isNull(dlydTrnMapList) || dlydTrnMapList.isEmpty()) {
			super.logPrint.printDebugLog("Empty Delayed Transaction List");
			return null;
		}

		int length = dlydTrnMapList.size();
		int errorCount = 0;
		super.logPrint.printDebugLog(String.format("Delayed Transaction List Size : %d",
				length));

		File outputDir = new File(commonItem.getFreeItem());

		if (!outputDir.exists()) {
			String logMessage = String.format("Output Directory %s does not exit.",
					outputDir.getAbsoluteFile());
			super.logPrint.printDebugLog(logMessage);
			throw new Exception(logMessage);
		}

		for (int i = 0; i < length; i++) {
			File outputFileName = new File(outputDir,
					String.format(ERROR_FILE_NAME_FORMAT,
							JCCBatCommon.getSysDateTimeStamp()));
			super.logPrint.printDebugLog(String.format("Processing index : %d ; Output File Name : %s.",
					i,
					outputFileName));

			JBSbatOutputFileUtil outputFileUtil = new JBSbatOutputFileUtil(outputFileName.getAbsolutePath());
			outputFileUtil.setEncode(JKKStrConst.ENCODE_SJIS);
			outputFileUtil.createWriter();

			HashMap<String, Object> hashMap = dlydTrnMapList.get(i);
			String inputFileName = (String) hashMap.get(JBSbatCC_T_DLYD_TRN_REQ.INPUT_EFILE_KANRI_NO);

			if (JKKCommonUtil.isNull(inputFileName)
					|| inputFileName.trim().isEmpty()) {
				super.logPrint.printDebugLog(String.format("Empty inputFileName for index : %d.",
						i));
				continue;
			}

			JBSbatInputFileUtil jbsBatInputFileUtil = null;
			String dlydTrnReqNo = hashMap.get(JBSbatCC_T_DLYD_TRN_REQ.DLYD_TRN_REQ_NO).toString();

			try {
				super.logPrint.printDebugLog(String.format("[%d] Searching Denshi File : %s",
						i,
						inputFileName));
				String searchDenshiFile = JKKBatCommon.searchDenshiFile(commonItem,
						inputFileName);
				int fileSize = 0;

				try {
					fileSize = Integer.valueOf(JCCFileUtil.getFileSize(searchDenshiFile));
				} catch (Exception e) {
					super.logPrint.printDebugLog(stackTracesToString(e));
				}

				super.logPrint.printDebugLog(String.format("File Size : %d for %s",
						fileSize,
						searchDenshiFile));

				if (fileSize == 0) {
					courseTkJknFileOutput(EMPTY_FILE_ROW_NUMBER,
							setOutputMap(InFileCheckCd.COURSE_TK_JKN_ZERO_RSLT.getMessage(),
									InFileCheckCd.COURSE_TK_JKN_ZERO_RSLT),
							outputFileUtil);

					updateShoriIrai(i,
							JKKStrConst.DLYD_TRN_RSLT_CD_APP_ERR,
							dlydTrnReqNo);
					super.logPrint.printDebugLog(String.format("Empty File Size for %s at index %d. Moving to next data.",
							searchDenshiFile,
							i));
					continue;
				}

				jbsBatInputFileUtil = new JBSbatInputFileUtil(searchDenshiFile);
				jbsBatInputFileUtil.setEncode(JKKBatConst.SJIS);
				jbsBatInputFileUtil.createReader();
				errorCount = this.doInputProcess(jbsBatInputFileUtil,
						outputFileUtil);
				String rsltCd = JKKStrConst.DLYD_TRN_RSLT_CD_COMPLETE;

				if (errorCount != 0) {
					rsltCd = JKKStrConst.DLYD_TRN_RSLT_CD_APP_ERR;
				}

				updateShoriIrai(i, rsltCd, dlydTrnReqNo);
			} catch (Exception e) {
				super.logPrint.printDebugLog(stackTracesToString(e));
				updateShoriIrai(i,
						JKKStrConst.DLYD_TRN_RSLT_CD_SYS_ERR,
						dlydTrnReqNo);
				throw new Exception(e);
			} finally {
				if (!JKKCommonUtil.isNull(jbsBatInputFileUtil)) {
					super.logPrint.printDebugLog(String.format("Closing Input File : %s",
							inputFileName));
					jbsBatInputFileUtil.close();
				}

				if (!JKKCommonUtil.isNull(outputFileUtil)) {
					super.logPrint.printDebugLog(String.format("Closing Output File : %s",
							outputFileName));
					outputFileUtil.close();
					int result = executeZM_T_DL_FILE_KANRI(errorCount,
							outputFileName);

					if (result == 0) {
						super.logPrint.printDebugLog("Empty result when saving in ZM_T_DL_FILE_KANRI table.");
					}
				}
			}
		}

		int result = executeKK_T_COURSE_TK_JKN_KK_DELETE_001(JCCBatCommon.getSysDate());
		super.logPrint.printDebugLog(String.format("KK_T_COURSE_TK_JKN Delete Result : %d",
				result));
		super.logPrint.printDebugLog("Done executing JBSbatKKSvctkareaUpd::execute()");

		return null;
	}

	/**
	 * Processing of the input file by reading the CSV file line by line. Error
	 * and validation check.
	 * 
	 * @param kkiFm858CSV
	 * @param outputFileUtil
	 * @return int
	 * @throws JBSbatBusinessException
	 */
	private int doInputProcess(JBSbatInputFileUtil kkiFm858CSV,
			JBSbatOutputFileUtil outputFileUtil) throws JBSbatBusinessException {
		super.logPrint.printDebugLog("Executing JBSbatKKSvctkareaUpd::doInputProcess()");
		int errorCount = 0;

		try {
			int numberOfLines = 0;
			JBSbatDefFileUtil jbsBatDefFileUtil = new JBSbatDefFileUtil(JBSbatAplConst.getAplConstValue("IND")
					+ KKLST11201_DEF_INPUT,
					kkiFm858CSV);

			for (; kkiFm858CSV.ready(); numberOfLines++) {
				String line = kkiFm858CSV.readLine();
				JBSbatServiceInterfaceMap inMap = jbsBatDefFileUtil.lineToObject(line,
						kkiFm858CSV,
						FILE_UTIL_RECORD);

				if (inMap.isInputErrorFlg()) {
					errorCount++;
					super.logPrint.printDebugLog(String.format("Has Input Error in Line : %d. Incorrect Item Columns.",
							numberOfLines + 1));
					courseTkJknFileOutput(numberOfLines,
							setOutputMap(InFileCheckCd.COURSE_TK_JKN_KMKSUU.getMessage(),
									InFileCheckCd.COURSE_TK_JKN_KMKSUU),
							outputFileUtil);
					continue;
				}

				JBSbatServiceInterfaceMap errorOutputMap = null;
				String svcKeiKaisenUCWKNo = getStringValue(inMap.getString(JBSbatKK_T_COURSE_TK_JKN.SVC_KEI_KAISEN_UCWK_NO));
				String TkJknTstaYMD = getStringValue(inMap.getString(JBSbatKK_T_COURSE_TK_JKN.TK_JKN_TSTAYMD));
				String TkJknTendYMD = getStringValue(inMap.getString(JBSbatKK_T_COURSE_TK_JKN.TK_JKN_TENDYMD));

				if (JKKCommonUtil.isNull(svcKeiKaisenUCWKNo)
						|| svcKeiKaisenUCWKNo.trim().isEmpty()) {
					super.logPrint.printDebugLog("Empty SVC_KEI_KAISEN_UCWK_NO");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_HISSU_SVC_KEI_KAISEN_UCWK_NO);
				} else if (!JBSbatCheckUtil.invoke(svcKeiKaisenUCWKNo,
						ValidationCd.FULL_WIDTH_CHECK_STR.getValue())) {
					super.logPrint.printDebugLog("Full-Width SVC_KEI_KAISEN_UCWK_NO");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_ZOKU_SVC_KEI_KAISEN_UCWK_NO);
				} else if (JBSbatCheckUtil.invoke(svcKeiKaisenUCWKNo,
						ValidationCd.LENGTH_CHECK_14_STR.getValue())) {
					super.logPrint.printDebugLog("Length of SVC_KEI_KAISEN_UCWK_NO is 14 characters");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_DIGITNO_SVC_KEI_KAISEN_UCWK_NO);
				} else if (JBSbatCheckUtil.invoke(svcKeiKaisenUCWKNo,
						ValidationCd.LENGTH_CHECK_16_STR.getValue())) {
					super.logPrint.printDebugLog("Length of SVC_KEI_KAISEN_UCWK_NO is 16 characters");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_DIGITNO_SVC_KEI_KAISEN_UCWK_NO);
				} else if (JKKCommonUtil.isNull(TkJknTstaYMD)
						|| TkJknTstaYMD.trim().isEmpty()) {
					super.logPrint.printDebugLog("Empty TK_JKN_TSTAYMD");
					errorOutputMap = setOutputMap(TkJknTstaYMD,
							InFileCheckCd.COURSE_TK_JKN_HISSU_TK_JKN_TSTAYMD);
				} else if (!JBSbatCheckUtil.invoke(svcKeiKaisenUCWKNo,
						ValidationCd.LENGTH_CHECK_12_STR.getValue())) {
					super.logPrint.printDebugLog("Length SVC_KEI_KAISEN_UCWK_NO");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_DIGITNO_SVC_KEI_KAISEN_UCWK_NO);
				} else if (!JBSbatCheckUtil.invoke(TkJknTstaYMD,
						ValidationCd.LENGTH_CHECK_8_STR.getValue())) {
					super.logPrint.printDebugLog("Length TK_JKN_TSTAYMD");
					errorOutputMap = setOutputMap(TkJknTstaYMD,
							InFileCheckCd.COURSE_TK_JKN_DIGITNO_TK_JKN_TSTAYMD);
				} else if (!JKKCommonUtil.isNull(TkJknTendYMD)
						&& !TkJknTendYMD.trim().isEmpty()
						&& !JBSbatCheckUtil.invoke(TkJknTendYMD,
								ValidationCd.LENGTH_CHECK_8_STR.getValue())) {
					super.logPrint.printDebugLog("Length TK_JKN_TENDYMD");
					errorOutputMap = setOutputMap(TkJknTendYMD,
							InFileCheckCd.COURSE_TK_JKN_DIGITNO_TK_JKN_TENDYMD);
				} else if (!JBSbatCheckUtil.invoke(svcKeiKaisenUCWKNo,
						ValidationCd.FORMAT_CHECK_STR.getValue())) {
					super.logPrint.printDebugLog("Format SVC_KEI_KAISEN_UCWK_NO");
					errorOutputMap = setOutputMap(svcKeiKaisenUCWKNo,
							InFileCheckCd.COURSE_TK_JKN_ZOKU_SVC_KEI_KAISEN_UCWK_NO);
				} else if (!JBSbatCheckUtil.invoke(TkJknTstaYMD,
						ValidationCd.FORMAT_YMD_CHECK_STR.getValue())) {
					super.logPrint.printDebugLog("Format TK_JKN_TSTAYMD");
					errorOutputMap = setOutputMap(TkJknTstaYMD,
							InFileCheckCd.COURSE_TK_JKN_ZOKU_TK_JKN_TSTAYMD);
				} else if (!JKKCommonUtil.isNull(TkJknTendYMD)
						&& !TkJknTendYMD.trim().isEmpty()
						&& !JBSbatCheckUtil.invoke(TkJknTendYMD,
								ValidationCd.FORMAT_YMD_CHECK_STR.getValue())) {
					super.logPrint.printDebugLog("Format TK_JKN_TENDYMD");
					errorOutputMap = setOutputMap(TkJknTendYMD,
							InFileCheckCd.COURSE_TK_JKN_ZOKU_TK_JKN_TENDYMD);
				} else {
					int result = executeKK_T_COURSE_TK_JKN_KK_INSERT_001(svcKeiKaisenUCWKNo,
							TkJknTstaYMD,
							TkJknTendYMD);

					if (result == 0) {
						super.logPrint.printDebugLog("Empty result when saving in KK_T_COURSE_TK_JKN table.");
					}
				}

				if (!JKKCommonUtil.isNull(errorOutputMap)) {
					errorCount++;
					courseTkJknFileOutput(numberOfLines,
							errorOutputMap,
							outputFileUtil);
				}
			}
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}

		return errorCount;
	}

	/**
	 * Saving to the output file.
	 * 
	 * @param rowNumber
	 * @param errorOutputMap
	 * @param outputFileUtil
	 * @throws JBSbatBusinessException
	 */
	private void courseTkJknFileOutput(int rowNumber,
			JBSbatServiceInterfaceMap errorOutputMap,
			JBSbatOutputFileUtil outputFileUtil) throws JBSbatBusinessException {

		super.logPrint.printDebugLog(String.format("Saving Error Log with row number : %d",
				rowNumber + 1));

		if (this.commonItem.getErrorCount() == 0) {
			this.commonItem.setErrFlg(true);
		}

		this.commonItem.setErrorCount(this.commonItem.getErrorCount() + 1);

		try {
			errorOutputMap.set(ErrorCd.ROW_NO.name(), (rowNumber + 1)
					+ ROW_NO_TEXT);
			errorOutputMap.set(ErrorCd.TRAN_NITI.name(),
					JCCBatCommon.getSysDateTime());
			errorOutputMap.set(ErrorCd.STAT.name(), STAT_TEXT);
			outputFileUtil.print(errorOutputMap,
					new JBSbatDefFileUtil(JBSbatAplConst.getAplConstValue("IND")
							+ KKLST11202_DEF_OUTPUT,
							outputFileUtil));
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}
	}

	/**
	 * Data insert to the KK_T_COURSE_TK_JKN.
	 * 
	 * @param svcKeiKaisenUCWKNo
	 * @param TkJknTstaYMD
	 * @param TkJknTendYMD
	 * @return int
	 * @throws JBSbatBusinessException
	 */
	private int executeKK_T_COURSE_TK_JKN_KK_INSERT_001(String svcKeiKaisenUCWKNo,
			String TkJknTstaYMD, String TkJknTendYMD) throws JBSbatBusinessException {
		int result = 0;

		if (JKKCommonUtil.isNull(TkJknTendYMD) || TkJknTendYMD.trim().isEmpty()) {
			TkJknTendYMD = TK_JKN_TENDYMD_DEFAULT;
		}

		try {
			String systemDate = JKKBatCommon.getSysDate();
			systemDate = systemDate.replaceAll(SYSTEM_DATE_DATE_REMOVAL_REGEX,
					EMPTY_STRING);

			// バイント変数のリストを生成します
			JBSbatCommonDBInterface paramList = new JBSbatCommonDBInterface();
			paramList.setValue(JBSbatKK_T_COURSE_TK_JKN.SVC_KEI_KAISEN_UCWK_NO,
					svcKeiKaisenUCWKNo);
			paramList.setValue(JBSbatKK_T_COURSE_TK_JKN.GENE_ADD_DTM,
					JKKBatCommon.getSysDateTimeStamp());
			paramList.setValue(JBSbatKK_T_COURSE_TK_JKN.TK_JKN_TSTAYMD, TkJknTstaYMD);
			paramList.setValue(JBSbatKK_T_COURSE_TK_JKN.TK_JKN_TENDYMD, TkJknTendYMD);
			paramList.setValue(JBSbatKK_T_COURSE_TK_JKN.ADD_YM, systemDate);
			result = this.db_KK_T_COURSE_TK_JKN.insertByPrimaryKeys(paramList);
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}

		return result;
	}

	/**
	 * Data insert to the ZM_T_DL_FILE_KANRI.
	 * 
	 * @param totalErrorCount
	 * @param outputFile
	 * @return int
	 * @throws JBSbatBusinessException
	 */
	private int executeZM_T_DL_FILE_KANRI(int totalErrorCount, File outputFile) throws JBSbatBusinessException {
		super.logPrint.printDebugLog("executeZM_T_DL_FILE_KANRI");
		int result = 0;
		String[] rc = null;
		super.logPrint.printDebugLog(String.format("Saving ZM_T_DL_FILE_KANRI with errorCount : %d ; Output File : %s.",
				totalErrorCount,
				outputFile.getAbsolutePath()));

		try {
			rc = JCCBatCommon.createDenshiFile(this.commonItem,
					EMPTY_STRING,
					outputFile.getAbsolutePath(),
					null);
		} catch (JCCbatFrameworkException e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}

		if (JKKCommonUtil.isNull(rc) || rc.length == 0) {
			throw new JBSbatBusinessException("Empty Denshi File Creation");
		}

		String fileKanriNo = rc[E_FILE_KANRI_NO_INDEX];
		String opeDate = this.commonItem.getOpeDate();
		super.logPrint.printDebugLog(String.format("Retrieve OPEDate : %s",
				opeDate));
		JBSbatCommonDBInterface param = new JBSbatCommonDBInterface();

		try {
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.FILE_NO,
					JCCBatCommon.getFormatedNextSeq(super.commonItem,
							SEQ_PREFIX_SEQ_FILE_NAME,
							SEQ_PREFIX_SEQ_FILE_NO,
							SEQ_LEN_SEQ_FILE_NO));
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.TRN_KANRI_NO,
					FILE_CD_COURSE_TK_JKN_INFO);
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.EFILE_KANRI_NO, fileKanriNo);
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.FILE_NM,
					outputFile.getName());
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.FILE_SIZE,
					JCCFileUtil.getFileSize(outputFile.getAbsolutePath()));
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.DATA_CNT, totalErrorCount);
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.FILE_ADD_DTM,
					JCCBatCommon.getSysDateTimeStamp());

			String computedOpeDate = JPCDateUtil.addMonth(opeDate, 1);
			super.logPrint.printDebugLog(String.format("Computed OPEDate : %s",
					computedOpeDate));

			param.setValue(JBSbatZM_T_DL_FILE_KANRI.FILE_DEL_YMD,
					computedOpeDate);
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.ADD_DTM, null);
			// 10.登録オペレータアカウント
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.ADD_OPEACNT, null);
			// 11.更新年月日時分秒
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.UPD_DTM, null);
			// 12.更新オペレータアカウント
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.UPD_OPEACNT, null);
			// 13.削除年月日時分秒
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.DEL_DTM, null);
			// 14.削除オペレータアカウント
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.DEL_OPEACNT, null);
			// 15.無効フラグ
			param.setValue(JBSbatZM_T_DL_FILE_KANRI.MK_FLG, null);

			result = db_ZM_T_DL_FILE_KANRI.insertByPrimaryKeys(param);
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}

		super.logPrint.printDebugLog("Done executeZM_T_DL_FILE_KANRI");
		return result;
	}

	/**
	 * Data delete to the KK_T_COURSE_TK_JKN using the KK_DELETE_001 key.
	 * 
	 * @param date
	 * @return int
	 * @throws JBSbatBusinessException
	 */
	private int executeKK_T_COURSE_TK_JKN_KK_DELETE_001(String date) throws JBSbatBusinessException {
		int executionCount = 0;

		try {
			// バイント変数のリストを生成します
			JBSbatCommonDBInterface paramList = new JBSbatCommonDBInterface();
			String dateToDelete = JPCDateUtil.addMonth(date, -2);
			paramList.setValue(dateToDelete);

			super.logPrint.printDebugLog(String.format("Executing KK_T_COURSE_TK_JKN_SQL.KK_DELETE_001 with date : %s",
					dateToDelete));

			// DBアクセスを実行します
			executionCount = db_KK_T_COURSE_TK_JKN.executeBySqlDefine(paramList,
					KK_T_COURSE_TK_JKN_SQL.KK_DELETE_001.name());
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
			throw new JBSbatBusinessException(e.getMessage());
		}

		return executionCount;
	}

	/**
	 * Conversion of the Exception to printable stacktrace in String.
	 * 
	 * @param e
	 * @return String
	 */
	private String stackTracesToString(Exception e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));

		return sw.toString();
	}

	/**
	 * Setting of the output map.
	 * 
	 * @param errKMKValue
	 * @param inFileCheckCd
	 * @param outMap
	 */
	private JBSbatServiceInterfaceMap setOutputMap(String errKMKValue,
			InFileCheckCd inFileCheckCd) {

		JBSbatServiceInterfaceMap outMap = new JBSbatServiceInterfaceMap();
		outMap.setOutFlg(true);

		try {
			outMap.setString(ErrorCd.ERR_ID.name(), inFileCheckCd.getCode());
			outMap.setString(ErrorCd.ERR_KMK_NM.name(),
					inFileCheckCd.getMessage());
			outMap.setString(ErrorCd.ERR_KMK_VALUE.name(), errKMKValue);
		} catch (Exception e) {
			super.logPrint.printDebugLog(stackTracesToString(e));
		}

		return outMap;
	}

	/**
	 *ディレイド処理依頼結果更新処理<br>
	 * 
	 * @param fileCnt
	 *            ファイル件数
	 * @param isSysErrFlg
	 *            エラーフラグ
	 * @throws Exception
	 */
	private void updateShoriIrai(int fileCnt, String rsltCd, String dlydTrnReqNo) throws Exception {
		super.logPrint.printDebugLog("Doing updateShoriIrai");

		if (JKKStrConst.DLYD_TRN_RSLT_CD_SYS_ERR.equalsIgnoreCase(rsltCd)) {
			// エラーの場合
			// DBロールバック処理
			super.logPrint.printDebugLog(String.format("[%s] Performing rollback for System Error",
					dlydTrnReqNo));
			JBSbatBusinessBase.dbcon.rollback();
		} else {
			super.logPrint.printDebugLog(String.format("ShoriIrai Status : %s with dlydTrnReqNo : %s",
					rsltCd,
					dlydTrnReqNo));
		}

		// ディレイド処理依頼結果更新部品呼び出し
		HashMap<String, String> results = JKKBatCommon.updateShoriIraiResult(commonItem,
				dlydTrnReqNo,
				rsltCd,
				null);

		if (!JKKCommonUtil.isNull(results) && results.size() != 0) {
			super.logPrint.printDebugLog(String.format("JKKBatCommon.updateShoriIraiResult : %s",
					results.toString()));
		} else {
			super.logPrint.printDebugLog("Empty JKKBatCommon.updateShoriIraiResult");
		}

		// DBコミット処理
		JBSbatBusinessBase.dbcon.commit();
	}
}
