/**
 * *********************************************************************************
 * @@ Program Name : DynaReportModifyer.java Description : 보고자 동적 보고자료 변경 Author
 * : 강원중 Create Date : 2004-11-08 History :
 * @@
 **********************************************************************************
 */
package kr.co.kihyun.beans.totsys.report;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import com.sun.xml.internal.ws.util.StringUtils;

import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.db.CommonDBManager;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.report.MReportData;
import kr.co.kihyun.text.javascript.JavaScriptUtil;

    public class DynaReportModifyer extends ReportModifyFormElement implements ReportModifyer {

    private StringBuilder addJSBuf;
    private StringBuilder inDataJSBuf;
    private StringBuilder hiddenDataBuf;
    private StringBuilder insertInputCellName;

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

 /**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    public DynaReportModifyer(HttpServletRequest req, TotReport totReport, TotDoc totDoc, String deptID, String userID, int rowCount) {
        super(totDoc);
        setModifyForm(req, totReport, totDoc, deptID, userID, rowCount);
    }

    public DynaReportModifyer(HttpServletRequest req, TotDoc totDoc, String deptID, String userID, int rowCount,
            String tableRows) {
        super(totDoc, rowCount, tableRows);
        setModifyForm(req, totDoc, deptID, userID, rowCount, tableRows);
    }

 /**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    public DynaReportModifyer(HttpServletRequest req, TotReport totReport, TotDoc totDoc, String deptID, String userID, int rowCount,
            String tableRows) {
        super(totDoc, rowCount, tableRows);
        setModifyForm(req, totReport, totDoc, deptID, userID, rowCount, tableRows);
    }

    private void setModifyForm(HttpServletRequest req, TotDoc totDoc, String deptID, String userID, int rowCount) {
        int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
        String modifyMode = req.getParameter("modifyMode");
        /**
         * ********* Report values **********
         */
        ReportView repoView = new ReportView();
        //v2. 6.SQL 삽입 : DO형식이므로 해결책에 따른 prepare SQL 문으로 변경할 수 없음
        repoView.executeQuery(totDoc.getId(), deptID, userID, "modify");
        //================
        String datas = "";

        if (modifyMode == null) {
            datas = JavaScriptUtil.toCRLF(repoView.getData());
            rowCount = repoView.getRowCount();
        }

        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; r < rowCount; r++) {
                delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제
                for (int c = 0; c < super.getInItemCount(); c++) {
                    inData[r][c] = Encoder.toJava(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] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                        } else if (nameIndex < getInItemNameList().length) { // 삭제 전 line: 아무런 변화가 없으므로 정상 처리
                            inData[r][c] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                        }
                    }
                    nameIndex++;
                }
            }
        } else {
            inData = MReportData.getDataArray(rowCount, 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("\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++;
            }
        }
    }


 /**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    private void setModifyForm(HttpServletRequest req, TotReport totReport, TotDoc totDoc, String deptID, String userID, int rowCount) {
        int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
        String modifyMode = req.getParameter("modifyMode");
        /**
         * ********* Report values **********
         */
        ReportView repoView = new ReportView();
        //v2. 6.SQL 삽입 : DO형식이므로 해결책에 따른 prepare SQL 문으로 변경할 수 없음
        repoView.executeQuery(totReport.getId(), totDoc.getId(), deptID, userID, "modify");
        //================
        String datas = "";

        if (modifyMode == null) {
            datas = JavaScriptUtil.toCRLF(repoView.getData());
            rowCount = repoView.getRowCount();
        }

        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; r < rowCount; r++) {
                delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제
                for (int c = 0; c < super.getInItemCount(); c++) {
                    inData[r][c] = Encoder.toJava(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] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                        } else if (nameIndex < getInItemNameList().length) { // 삭제 전 line: 아무런 변화가 없으므로 정상 처리
                            inData[r][c] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                        }
                    }
                    nameIndex++;
                }
            }
        } else {
            inData = MReportData.getDataArray(rowCount, 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("\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++;
            }
        }
    }

    private void setModifyForm(HttpServletRequest req, TotDoc totDoc, String deptID, String userID, int rowCount,
            String tableRows) {
        int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
        String modifyMode = req.getParameter("modifyMode");
        String tables = req.getParameter("tables");
        int addRowNum = MInteger.parseInt(req.getParameter("addRowNum"), 0);
        /**
         * ********* Report values **********
         */
        ReportView repoView = new ReportView();
        repoView.executeQuery(totDoc.getId(), deptID, userID, "modify");

        String datas = "";
        MString.checkNull(repoView.getNote());

        if (modifyMode == null) {
            datas = JavaScriptUtil.toCRLF(repoView.getData());
            rowCount = repoView.getRowCount();
        }

        /**
         * ********** Report view or report to ***************
         */
        int nameIndex = 0;
        String[] inData = new String[super.getSize()];

        addJSBuf = new StringBuilder();
        inDataJSBuf = new StringBuilder();
        hiddenDataBuf = new StringBuilder();
        insertInputCellName = new StringBuilder();

        if (modifyMode != null && modifyMode.equals("addRow")) { // 행추가
            nameIndex = 0;
            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 ((Integer.parseInt(tables) - 1) == i) {
                            if (stp < (Integer.parseInt(getTableRowList()[i]) - addRowNum)) {
                                inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            } else {
                                inData[idx] = "";
                            }
                        } else {
                            if ((Integer.parseInt(tables) - 1) < i) {
                                String inx = super.getInItemNameList()[nameIndex];
                                String inxA = "";
                                int inxN = 0;
                                int inxD = 0;
                                for (int pi = 0; pi < inx.length(); pi++) {
                                    if (inx.charAt(pi) >= '0' && inx.charAt(pi) <= '9') {
                                        inxD = pi;
                                        break;
                                    }
                                }
                                inxA = inx.substring(0, inxD);
                                inxN = Integer.parseInt(inx.substring(inxD)) - addRowNum;
                                inx = inxA + Integer.toString(inxN);

                                inData[idx] = Encoder.toJava(req.getParameter(inx));
                            } else {
                                inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            }
                        }
                        idx++;
                        nameIndex++;
                    }
                }
                here = here + getTableColNumList()[i];
            }
        } else if (modifyMode != null && modifyMode.equals("delRow")) { // 행삭제
            nameIndex = 0;
            delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제

            // String tmpRows = "";
            StringBuilder tmpRows = new StringBuilder();
            String tmpRowsList[] = tableRows.split(",");

            tmpRowsList[(Integer.parseInt(tables) - 1)] = Integer.toString(Integer.parseInt(tmpRowsList[(Integer.parseInt(tables) - 1)]) + 1);

            for (int tmpR = 0; tmpR < tmpRowsList.length; tmpR++) {
                if (tmpR == 0) {
                    tmpRows.append(tmpRowsList[tmpR]);
                } else {
                    tmpRows.append(",");
                    tmpRows.append(tmpRowsList[tmpR]);
                }
            }

            super.setForm(totDoc, rowCount, tmpRows.toString());

            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++) {

                                            //42.비어있는 if문 : Update by YOUNGJUN,CHO
                        //if (stp == delRowNum && (Integer.parseInt(tables) - 1) == i) {
                        //} else {
                        if (stp != delRowNum || (Integer.parseInt(tables) - 1) != i) {
                            inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            idx++;
                        }

                        //================================================
                        nameIndex++;
                    }
                }
                here = here + getTableColNumList()[i];
            }

            super.setForm(totDoc, rowCount, tableRows);

        } 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++) {
            try {
                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");
                if (c == 0) {
                    insertInputCellName.append(getInItemNameList()[index]);
                } else {
                    insertInputCellName.append(",").append(getInItemNameList()[index]);
                }
                index++;
            } catch (Exception ex) {
                ex.printStackTrace();
                break;
            }
        }
    }


 /**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    private void setModifyForm(HttpServletRequest req, TotReport totReport, TotDoc totDoc, String deptID, String userID, int rowCount,
            String tableRows) {
        int delRowNum = MInteger.parseInt(req.getParameter("delRowNum"), 1);
        String modifyMode = req.getParameter("modifyMode");
        String tables = req.getParameter("tables");
        int addRowNum = MInteger.parseInt(req.getParameter("addRowNum"), 0);
        /**
         * ********* Report values **********
         */
        ReportView repoView = new ReportView();
        repoView.executeQuery(totReport.getId(), totDoc.getId(), deptID, userID, "modify");
        //리포트 데이터 없을 경우 직접 셀렉트
        if(repoView.getData()==null||"".equals(repoView.getData())){
        	String data=null;
        	CommonDBManager db=new CommonDBManager();
        	try {
				ResultSet rs= db.execQuery("select DATA from moumi_tot_report where id=?", totReport.getId());
				if(rs.next()){
					data=rs.getString(1);
					repoView.setData(data);
				}
				rs.close();
				db.execClose();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        //req.setAttribute("debug", repoView.getData());
        String datas = "";
        MString.checkNull(repoView.getNote());

        if (modifyMode == null) {
            datas = JavaScriptUtil.toCRLF(repoView.getData());
            rowCount = repoView.getRowCount();
        }

        /**
         * ********** Report view or report to ***************
         */
        int nameIndex = 0;
        String[] inData = new String[super.getSize()];

        addJSBuf = new StringBuilder();
        inDataJSBuf = new StringBuilder();
        hiddenDataBuf = new StringBuilder();
        insertInputCellName = new StringBuilder();

        if (modifyMode != null && modifyMode.equals("addRow")) { // 행추가
            nameIndex = 0;
            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 ((Integer.parseInt(tables) - 1) == i) {
                            if (stp < (Integer.parseInt(getTableRowList()[i]) - addRowNum)) {
                                inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            } else {
                                inData[idx] = "";
                            }
                        } else {
                            if ((Integer.parseInt(tables) - 1) < i) {
                                String inx = super.getInItemNameList()[nameIndex];
                                String inxA = "";
                                int inxN = 0;
                                int inxD = 0;
                                for (int pi = 0; pi < inx.length(); pi++) {
                                    if (inx.charAt(pi) >= '0' && inx.charAt(pi) <= '9') {
                                        inxD = pi;
                                        break;
                                    }
                                }
                                inxA = inx.substring(0, inxD);
                                inxN = Integer.parseInt(inx.substring(inxD)) - addRowNum;
                                inx = inxA + Integer.toString(inxN);

                                inData[idx] = Encoder.toJava(req.getParameter(inx));
                            } else {
                                inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            }
                        }
                        idx++;
                        nameIndex++;
                    }
                }
                here = here + getTableColNumList()[i];
            }
        } else if (modifyMode != null && modifyMode.equals("delRow")) { // 행삭제
            nameIndex = 0;
            delRowNum = delRowNum - 1; // 배열은 0부터 시작하니까 1삭제

            // String tmpRows = "";
            StringBuilder tmpRows = new StringBuilder();
            String tmpRowsList[] = tableRows.split(",");

            tmpRowsList[(Integer.parseInt(tables) - 1)] = Integer.toString(Integer.parseInt(tmpRowsList[(Integer.parseInt(tables) - 1)]) + 1);

            for (int tmpR = 0; tmpR < tmpRowsList.length; tmpR++) {
                if (tmpR == 0) {
                    tmpRows.append(tmpRowsList[tmpR]);
                } else {
                    tmpRows.append(",");
                    tmpRows.append(tmpRowsList[tmpR]);
                }
            }

            super.setForm(totDoc, rowCount, tmpRows.toString());

            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++) {

                        //42.비어있는 if문 : Update by YOUNGJUN,CHO
                        //if (stp == delRowNum && (Integer.parseInt(tables) - 1) == i) {
                        //} else {
                        if (stp != delRowNum || (Integer.parseInt(tables) - 1) != i) {
                            inData[idx] = Encoder.toJava(req.getParameter(super.getInItemNameList()[nameIndex]));
                            idx++;
                        }

                        //================================================
                        nameIndex++;
                    }
                }
                here = here + getTableColNumList()[i];
            }

            super.setForm(totDoc, rowCount, tableRows);

        } 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++) {
            try {
                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");
                if (c == 0) {
                    insertInputCellName.append(getInItemNameList()[index]);
                } else {
                    insertInputCellName.append(",").append(getInItemNameList()[index]);
                }
                index++;
            } catch (Exception ex) {
                ex.printStackTrace();
                break;
            }
        }
    }

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

    public String getAddJavaScript() {
        return addJSBuf.toString();
    }

    public String getInDataJavaScript() {
        return inDataJSBuf.toString();
    }

    public String getHiddenData() {
        return hiddenDataBuf.toString();
    }

    public String getInsertInputCellName() {
        return insertInputCellName.toString();
    }

    public void initDes() {
        addJSBuf = inDataJSBuf = hiddenDataBuf = insertInputCellName = null;
    }
}
