/***********************************************************************************
 * @@ Program Name : HttpReportModifyer.java Description : 보고자 보고자료 변경 Author : 강원중 Create Date : 2004-11-08 History :
 * @@
 ***********************************************************************************/
package kr.co.kihyun.beans.totsys.report;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.co.kihyun.beans.entity.AcceptanceCode;
import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.TotDocType;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportHistory;
import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.totsys.doc.table.item.Item;
import kr.co.kihyun.beans.totsys.doc.table.item.ItemList;
import kr.co.kihyun.beans.totsys.menu.MenuBean;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.io.MultipartRequest;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.moumi.doc.table.InsertMTable;
import kr.co.kihyun.moumi.doc.table.item.MItem;
import kr.co.kihyun.moumi.report.MReportData;
import kr.co.kihyun.text.html.HtmlUtil;
import kr.co.kihyun.text.html.ServletUtil;
import org.datanucleus.ObjectManager;
import org.datanucleus.jdo.JDOPersistenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.report.ApproveReportModifyer")
public class ApproveReportModifyer extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(ApproveReportModifyer.class);

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);
		MenuBean tempboxMenu = new MenuBean(req, "/totsys/repoper/mydocbox/approve/report_list.jsp");

		/*********** User HttpLogin check ***********/
		if (!HttpSSOLogin.isLogin(req)) {
			String connURL = "location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);
		String dtID = HttpSSOLogin.getDeptID(req);

		/********** parameter value **********/
		String savePath = MoumiConfig.getRepoPerTmp().getPath(); // 업로드된 파일의 임시 저장 경로
		MultipartRequest multi = new MultipartRequest(req, savePath, 10 * 1024 * 1024);

		Long reportID = MLong.parseLong(multi.getParameter("reportID"));
		int acptNum = MInteger.parseInt(multi.getParameter("acptNum"), -1);
		LOG.debug("acptNum: {}", acptNum);
		String comment = multi.getParameter("comment");
		String tableRows = multi.getParameter("tableRows"); // 각 테이블당 입력칸이 몇줄 인지 데이터 예 : 2,3,2
		String inForm = URLDecoder.decode(MString.checkNull(multi.getParameter("inForm")), "UTF-8");
		String svrFilenames = multi.getParameter("svrFilenames");
		String usrFilenames = multi.getParameter("usrFilenames");
		int repoState = MInteger.parseInt(multi.getParameter("repoState"), 0); // 교육부 내부사용 모우미
		String memo = multi.getParameter("memo");

		// 승인자가 자료수정할때
		String deptID = null;
		String repUserID = null;
		String isRecog = MString.checkNull(multi.getParameter("isRecog"));

		if (isRecog.equals("recog")) {
			deptID = multi.getParameter("deptID");
			repUserID = multi.getParameter("repUserID");
		}

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem
		try {
			tx.begin();
			TotReport totReport = pm.getObjectById(TotReport.class, reportID);
			/********** regist **********/
			if (isRecog.equals("recog")) {
				dynaReportModify(pm, totReport, multi, acptNum, inForm, deptID, repUserID, comment, usrFilenames, svrFilenames,
						repoState, tableRows, TotReportProcess.APPROVE);
			} else {
				dynaReportModify(pm, totReport, multi, acptNum, inForm, dtID, usID, comment, usrFilenames, svrFilenames,
						repoState, tableRows, TotReportProcess.TEMP);
			}

			String targetURI = (String) session.getAttribute("modifySuccTargetURI");
			if (targetURI.equals(tempboxMenu.getUrl().toString())) {
				//LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") + "  {}, {}, {}",
						//new Object[] { usID, req.getRemoteAddr(), reportID });
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
						+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.complete") +" !\\n \\n" + MoumiConfig.getMessageBundle().getString("moumi.message.popup.reported") + tempboxMenu
						+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.inConfirm")));
			} else {
				//LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") +"  {}, {}, {}",
						//new Object[] { usID, req.getRemoteAddr(), reportID });
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
						+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.saved") + tempboxMenu + MoumiConfig.getMessageBundle().getString("moumi.message.popup.inConfirm")));
			}

			if (totReport.getSlaveTotDoc() != null) {
				TotReportHistory docHistory = new TotReportHistory(totReport, memo);
				pm.makePersistent(docHistory);

				//LOG.info(TotDocType.SUB_DOC + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify") +" {}, {}, {}, {}", new Object[] { usID,
						//totReport.getSlaveTotDoc().getId(), dtID, memo });
			}
			if (totReport.getSlaveTotDoc() != null)
				om.postCommit(); // jeus 6 problem
			tx.commit();
			TotReport savedReport = pm.getObjectById(TotReport.class, reportID);
			//LOG.debug("totReport.data: {}", savedReport.getData());

			out.println(ServletUtil.redirect((String) session.getAttribute("modifySuccTargetURI")));
		} catch (Exception ex) {
			//LOG.error(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" {}, {}, {}",
					//new Object[] { usID, req.getRemoteAddr(), reportID });
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN                     
//			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
//					+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.modifyFailAdmin")));
                        
                        // 수정 : 외부 입력값 필터링
                        String callbackFunc = MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
					     + MoumiConfig.getMessageBundle().getString("moumi.message.popup.modifyFailAdmin");
                        String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : ApproveReportModifyer.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                        out.println(ServletUtil.alert(filtered_callbackFunc));
                        //========================================                        
                        
                        
			ex.printStackTrace();
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
	}

	/************
	 * 보고 등록 ************* return -1 => 실패 return =0 => 변경사항 없음 return >0 => 성공
	 ********************************/
	private void dynaReportModify(PersistenceManager pm, TotReport totReport, MultipartRequest multi, int acptNum, String inForm,
			String dtID, String usID, String comment, String upFileName, String saveFileName, int repoState,
			String tableRows, TotReportProcess prss) throws Exception {
		Long formID = totReport.getTotDoc().getId();
		String tableTypes = totReport.getTotDoc().getTotTables().isEmpty() ? "" : totReport.getTotDoc().getTotTables()
				.iterator().next().getTypes();

		Item item = new Item();
		item.getStartInNum(formID);
		int[] itemTypeList = item.getType(formID);
		int[] itemInTypeList = item.getInTypeList(formID);

		String[] tableRowList = tableRows.split(",");
		String[] tableTypeList = tableTypes.split(",");
		int[] tableColNumList = new int[tableTypeList.length]; // 원본 폼의 각 테이블당 몇개의 입력칸이 존재 하는지 그 수 저장

		ItemList itemList = new ItemList();
		itemList.executeQuery(formID);
		String[] itemExprList = itemList.getExprList();
        for(int ii=0;ii<itemExprList.length;ii++) itemExprList[ii]=itemExprList[ii].replaceAll("=","");
		String[] itemNameList = itemList.getNameList();
		int inItemCount = item.getInCount(formID); // 입력할 수 있는 item count

		int subFpos = 0;
		for (int i = 0; i < tableTypeList.length; i++) {
			String subForm = inForm.substring(subFpos, inForm.indexOf("</table>", subFpos) + 8);
			subFpos = inForm.indexOf("</table>", subFpos) + 8;
			InsertMTable inMTable = new InsertMTable();
			String inBodyForms = "";
			if (tableTypeList[i].equals("1")) {
				inMTable.getInputTitleForm(subForm);
				inBodyForms = inMTable.getInputBodyForm(subForm);
				// 몇개의 입력칸이 존재하는지 숫자 파악
				tableColNumList[i] = inBodyForms.split("<input type").length - 1;
				tableColNumList[i] = tableColNumList[i] + inBodyForms.split("<textarea ").length - 1;
				tableColNumList[i] = tableColNumList[i] + inBodyForms.split("<select ").length - 1;
			} else {
				inBodyForms = subForm.substring(0, subForm.indexOf("</table"));
				// 몇개의 입력칸이 존재하는지 숫자 파악
				tableColNumList[i] = inBodyForms.split("<input type").length - 1;
				tableColNumList[i] = tableColNumList[i] + inBodyForms.split("<textarea ").length - 1;
				tableColNumList[i] = tableColNumList[i] + inBodyForms.split("<select ").length - 1;
			}
			HtmlUtil.getTailForm(subForm);
		}

		int itemSize = 0;
		for (int a = 0; a < tableColNumList.length; a++)
			itemSize = itemSize + tableColNumList[a];

		for (int a = 0; a < tableColNumList.length; a++)
        {
            try { 
                tableColNumList[a] = tableColNumList[a] / Integer.parseInt(tableRowList[a]); 
            //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
            } catch(NumberFormatException nfex) { 
                break; 
            //++++++++++++++++++++++++++++++++++++++++++++++++
            } catch(Exception ex) { 
                break; 
            }
        }

		String[] stItemNameList = MItem.getStartNameList(inForm, itemSize);
		String[] stItemNumList = MItem.getStartNumList(inForm, itemSize);
		String[] inItemNameList = new String[itemSize];

		for (int a = 0; a < itemSize; a++)
			inItemNameList[a] = stItemNameList[a] + stItemNumList[a];

		/*********** Report data values ***********/
		// 기본입력자료
		String[] dataList = MReportData.getDataList(multi, itemInTypeList, inItemNameList, tableColNumList,
				tableRowList);
		String datas = MReportData.getDatas(tableColNumList, tableRowList, dataList).replaceAll("'", "`");

		// 집계입력자료
		String[] totDataList = MReportData.getTotalDataList(itemSize, inItemCount, tableColNumList, tableRowList,
				itemTypeList, itemExprList, dataList, itemNameList);
		String totDatas = MReportData.getTotDatas(tableColNumList, totDataList);

		int tableNum = 1; // Table 별 입력 할 때 사용 예정
		MUser mUser = pm.getObjectById(MUser.class, usID);
		MDept mDept = pm.getObjectById(MDept.class, dtID);
		if (acptNum >= 0)
			totReport.setAcceptanceCode(new AcceptanceCode(mUser.getUpperDept(pm).getName(), acptNum));
		totReport.setTableNum(tableNum);
        //기존 부서사용자데이타가 있으므로 안넣어도 된다.
		/*
         totReport.setUser(mUser);
		 totReport.setDept(mDept);
         totReport.setProcess(prss);
         */
        //끝
		totReport.setData(datas);
		//LOG.debug("is report data null? {}", datas == null);
		totReport.setTotData(totDatas);
		totReport.setAppro(repoState);
		totReport.setNote(comment);

		
		FileUtil.putInFiles(saveFileName, totReport);
		pm.makePersistent(totReport);
	}
}
