/***********************************************************************************
 * @@ Program Name : TotReportModifyManager.java Description :보고양식을 동적, 정적 페이지에 맞게 반환해줌 Author : 강원중 Create Date :
 *    2004-11-08 History :
 * @@
 ***********************************************************************************/
package kr.co.kihyun.beans.totsys.report.tot;

import javax.servlet.http.HttpServletRequest;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;

import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.moumi.doc.table.MTable;
import kr.co.kihyun.moumi.report.MReportData;
import kr.co.kihyun.beans.totsys.doc.Doc;
import kr.co.kihyun.beans.totsys.report.ReportModifyFormElement;
import kr.co.kihyun.beans.totsys.report.ReportsView;

public class TotReportModifyer extends ReportModifyFormElement {

	/********* insert form: doc, table, javascript **********/
	private int tableType = 0;
	/********* insert form: item values **********/
	private String tableRows = "";
	private StringBuilder addJSBuf;
	private StringBuilder inDataJSBuf;
	private StringBuilder hiddenDataBuf;

	public TotReportModifyer(HttpServletRequest req, TotDoc totDoc, String deptID, int rowCount) {
		super(totDoc);
		setTableType(totDoc);
		setModifyForm(req, totDoc, deptID, rowCount);
	}

	public TotReportModifyer(HttpServletRequest req, TotDoc totDoc, String deptID, int rowCount, String tableRows) {
		super(totDoc, rowCount, tableRows);
		setTableType(totDoc);
		setModifyNewForm(req, totDoc, deptID, rowCount, tableRows);
	}

	private void setModifyForm(HttpServletRequest req, TotDoc totDoc, String deptID, int rowCount) {
		int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
		String modifyMode = req.getParameter("modifyMode");
		int reportCount = 0;
		String datas = "";

		ReportsView reposView = new ReportsView();
		reposView.executeQuery(super.getTotDoc().getId());

		if (modifyMode == null) {
			reportCount = reposView.getCount();
			rowCount = reportCount;
			datas = reposView.getDatas();
			rowCount = (datas.split(TotReport.ROW_DELIMITER)).length;
			reportCount = rowCount;
		}

		super.setRowCount(rowCount);
		super.setForm(totDoc, rowCount);

		/************ Report view or report to ****************/
		String[][] inData = null;
		addJSBuf = new StringBuilder();
		inDataJSBuf = new StringBuilder();
		hiddenDataBuf = new StringBuilder();

		if (modifyMode != null && modifyMode.equals("addRow")) { // 행추가
			int nameIndex = 0;
			inData = new String[rowCount][super.getInItemCount()];
			for (int r = 0, c = 0; r < rowCount; r++) {
				delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제
				for (c = 0; c < super.getInItemCount(); c++) {
					inData[r][c] = req.getParameter(super.getInItemNameList()[nameIndex]);
					nameIndex++;
				}
			}
		} else if (modifyMode != null && modifyMode.equals("delRow")) { // 행삭제
			int nameIndex = 0;
			boolean isDelete = false;
			delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제
			inData = new String[rowCount][super.getInItemCount()];

			for (int r = 0, c = 0; r < rowCount + 1; r++) {
				for (c = 0; c < super.getInItemCount(); c++) {
					if (delRowNum == r) { // 삭제 line checking
						isDelete = true;
					} else {
						if (isDelete && nameIndex < getInItemNameList().length) { // 삭제 다음 line:한깐씩 줄임
							inData[r - 1][c] = req.getParameter(super.getInItemNameList()[nameIndex]);
						} else if (nameIndex < getInItemNameList().length) { // 삭제 전 line: 아무런 변화가 없으므로 정상 처리
							inData[r][c] = req.getParameter(super.getInItemNameList()[nameIndex]);
						}
					}
					nameIndex++;
				}
			}
		} else {
			inData = MReportData.getDataArray2(reportCount, super.getInItemCount(), datas);
		}

		// 입력셀이 숫자이고 입력된 값이 없거나 숫자가 아닌경우 0으로 치환함
		inData = MReportData.getReportData(inData, super.getItemList().getTypeList());

		int index = 0;
		for (int r = 0, c = 0; r < rowCount; r++) {
			for (c = 0; c < super.getInItemCount(); c++) {
				inData[r][c] = inData[r][c].replaceAll("'", "`");
				inData[r][c] = inData[r][c].replaceAll("\r\n", "\\\\n");
				inDataJSBuf.append("dform.").append(super.getInItemNameList()[index]).append(".value='").append(inData[r][c]).append("';\n");
				addJSBuf.append("modifyForm.").append(super.getInItemNameList()[index]).append(".value=dform.").append(super.getInItemNameList()[index]).append(".value;\n");
				hiddenDataBuf.append("<input type='hidden' name='").append(super.getInItemNameList()[index]).append("' value=''>\n");
				index++;
			}
		}
	}

	/****************************************************************************
	 ***************************************************************************** 
	 ** 다수 동적테이블 등에 맞춰 새로 만들어진 함수 ** 2008 04 16 - 배정환 **
	 ***************************************************************************** 
	 *****************************************************************************/
	private void setModifyNewForm(HttpServletRequest req, TotDoc totDoc, String deptID, int rowCount, String tableRows) {
		int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
		String modifyMode = req.getParameter("modifyMode");
		String tables = req.getParameter("tables");
		// int rowCount = 0;
		int reportCount = 0;
		String datas = "";

		ReportsView reposView = new ReportsView();
		reposView.executeQuery(super.getTotDoc().getId());

		if (modifyMode == null) {
			reportCount = reposView.getCount();
			rowCount = reportCount;
			datas = reposView.getDatas();
			rowCount = (datas.split(TotReport.ROW_DELIMITER)).length;
			reportCount = rowCount;
			tableRows = reposView.getTableRows();
		}

		super.setRowCount(rowCount);
		super.setForm(totDoc, rowCount, tableRows);

		this.tableRows = tableRows;

		/************ Report view or report to ****************/
		String[] inData = new String[super.getInItemNameList().length];
		addJSBuf = new StringBuilder();
		inDataJSBuf = new StringBuilder();
		hiddenDataBuf = new StringBuilder();

		if (modifyMode != null && modifyMode.equals("addRow")) { // 행추가
			int nameIndex = 0;
			for (int r = 0; r < super.getSize(); r++) {
				inData[r] = req.getParameter(super.getInItemNameList()[nameIndex]);
				nameIndex++;
			}
		} else if (modifyMode != null && modifyMode.equals("delRow")) { // 행삭제
			int nameIndex = 0;
			delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제

			int idx = 0;
			int here = 0;
			for (int i = 0; i < getTableRowList().length; i++) {
				for (int stp = 0; stp < Integer.parseInt(getTableRowList()[i]); stp++) {
					for (int p = here; p < (here + getTableColNumList()[i]); p++) {
						if (stp != delRowNum && (Integer.parseInt(tables) - 1) != i) {
							inData[idx] = req.getParameter(super.getInItemNameList()[nameIndex]);
							idx++;
						}
						nameIndex++;
					}
				}
				here = here + getTableColNumList()[i];
			}
		} else {
			inData = MReportData.getDataArray(datas);
		}

		// 입력셀이 숫자이고 입력된 값이 없거나 숫자가 아닌경우 0으로 치환함
		inData = MReportData.getReportData(inData, super.getItemList().getTypeList(), super.getTableColNumList(), super.getTableRowList());

		int index = 0;

		for (int c = 0; c < super.getSize(); c++) {
			inData[c] = inData[c].replaceAll("'", "`");
			inData[c] = inData[c].replaceAll("\r\n", "\\\\n");
			inDataJSBuf.append("dform.").append(getInItemNameList()[index]).append(".value='").append(inData[c]).append("';\n");
			addJSBuf.append("modifyForm.").append(getInItemNameList()[index]).append(".value=dform.").append(getInItemNameList()[index]).append(".value;\n");
			hiddenDataBuf.append("<input type='hidden' name='").append(getInItemNameList()[index]).append("' value=''>\n");
			index++;
		}
	}

	private void setTableType(TotDoc totDoc) {
		Doc doc = new Doc();
		tableType = doc.getTableType(totDoc.getId());

		this.setTableTypes(doc.getTableTypes(totDoc.getId()));

		if (doc.isDynaTable(totDoc.getId())) {
			tableType = MTable.DYNA;
		} else {
			tableType = MTable.STATIC;
		}
	}

	public int getTableType() {
		return tableType;
	}

	public String getInsertForm() {
		return getInFormBuf().toString();
	}

	public String getAddJavaScript() {
		return addJSBuf.toString();
	} // 계산 수식 script

	public String getInDataJavaScript() {
		return inDataJSBuf.toString();
	} // 계산 수식 script

	public String getHiddenData() {
		return hiddenDataBuf.toString();
	} // 계산 수식 script

	public String getTableRows() {
		return tableRows;
	}
}
