/*************************************************************************************************
 * 프로그램명 : HttpReportRegister.java 프로그램설명 : 집계 문서에대한 보고자 보고 또는 보고자 자료 변경에 사용 작성자 : 강원중 작성일 : 2004.01.12 변경일 : 2003.11.30
 * 변경일 : 20170817. 첨부파일의 경로를 DB에 저장하는 부분 추가함 by wonseok Lee
 **************************************************************************************************/

package kr.co.kihyun.beans.totsys.report;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;

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.MUser;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotDoc.TotRange;
import kr.co.kihyun.beans.entity.TotReport;
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.db.CommonDBManager;
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.excel.Excel;
import kr.co.kihyun.text.html.HtmlUtil;
import kr.co.kihyun.text.html.ServletUtil;
import kr.co.kihyun.text.html.TagFilter;

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.HttpReportRegister")
public class HttpReportRegister extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpReportRegister.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/tempbox/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);

		//20170816 첨부파일 경로를 DB에 입력하기 위해 추가 by wonseok Lee.
		String dtID = HttpSSOLogin.getDeptID(req);

		/********** parameter value **********/
		String savePath = MoumiConfig.getRepoPerTmp().getPath(); // 업로드된 파일의 임시 저장 경로

                long limitSize=5*1024*1024;

		MultipartRequest multi = new MultipartRequest(req, savePath, limitSize);

		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 status = MString.checkNull(multi.getParameter("stat")); // 접수함에서 해당없음 1, 자료입력은 "";
		Long repDocID = MLong.parseLong(req.getParameter("repDocID"));
		String docID = MString.checkNull(multi.getParameter("repDocID"));//20170816 첨부파일경로 저장을 위해 추가 by wonseok Lee.
		int insertType = MInteger.parseInt(multi.getParameter("insertType"), 0);
		String svrFilenames = multi.getParameter("svrFilenames");
		String usrFilenames = multi.getParameter("usrFilenames");
                String doctName = multi.getParameter("doctName");
                String callbackFunc = MString.checkNull(multi.getParameter("callbackFunc"));
        String mode = MString.checkNull(multi.getParameter("mode"));	//20170818 제추첨부파일 경로
        int appro = MInteger.parseInt(multi.getParameter("appro"), 0); //2018.02.26 부서공유여부 체크
        String secuYn = MString.checkNull(multi.getParameter("secuYn"), "N"); //2018.03.30 보안지정여부 체크

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem

		CommonDBManager dbmanager=new CommonDBManager();
		try {

			LOG.debug("savePath:["+ savePath +"]");
			LOG.debug("usrFilenames:["+ usrFilenames +"]");

			tx.begin();
			TotReport totReport = pm.getObjectById(TotReport.class, reportID);
			dynaReportRegist(pm, totReport, multi, acptNum, inForm, usID, comment, usrFilenames, svrFilenames, tableRows, status, appro, secuYn);
			String targetURI = "";

			//LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.save")
            //+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") + "  {}, {}, {}", new Object[] {usID, req.getRemoteAddr(), reportID });
			TotRange totRange = totReport.getTotDoc().getTotRange();
			TotDoc masterDoc = repDocID == null ? null : pm.getObjectById(TotDoc.class, repDocID);

			if (totRange == TotRange.INTERNAL && status.length() == 0) {
				if (insertType == 0) {// 자료저장
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
							+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.saved2") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report")
							+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.is") + tempboxMenu + MoumiConfig.getMessageBundle().getString("moumi.message.popup.inConfirm") + tempboxMenu
							+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.draft")));
					out.println(ServletUtil
							.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/tempbox/report_list.jsp?reportType=TEMP')"));
				   } else if (insertType == 1) {// 기안결제
					String ApproveURL = "";
					out.println("<html><head>" + "<script>function excelApprove(){\n" + "approve = getOpener(\""
							+ ApproveURL
							+ "\", 'approve', 730, 700, 'center', 'middle', 'yes', 'yes');\n"
							+ "approve.focus();\nsetTimeout('relogin.submit()',3000);\n"
							+ "}"
							+ "function getOpener(url, target, width, height, align, valign, scroll, resize){\n"
							+ "var scWidth = screen.width;\n"
							+ "var scHeight = screen.height;\n"
							+ "var toppos = 0;\n"
							+ "var leftpos = 0;\n"
							+ "if(align == \"center\"){\n"
							+ "leftpos = (scWidth- width) / 2 ;\n"
							+ "}else if(align == \"right\"){"
							+ "\nleftpos = (scWidth- width);\n"
							+ "}else if(align == ''){\n"
							+ "leftpos = (scWidth- width) / 2 ;\n"
							+ "}\n"
							+ "if(valign == \"middle\"){\n"
							+ "toppos = (scHeight- height) / 2 ;\n"
							+ "}else if(valign == \"buttom\"){\n"
							+ "\ntoppos = (scHeight- height);\n"
							+ "}else if(valign == ''){\n"
							+ "toppos = (scHeight- height) / 2 ;\n"
							+ "}\n"
							+ "target = window.open(url, target, \"width=\"+width+\", height=\"+height+\", toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=\"+scroll+\", resizable=\"+resize+\", left=\"+leftpos+\", top=\"+ toppos);\n"
							+ "return target;\n}\n"
							+ "</script></head>\n<body onload=\"excelApprove();\"></body>\n</html>");
					// approve = getOpener(\""+ApproveURL+"\", 'approve', 730, 700, 'center', 'middle', 'yes', 'yes');\n
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.submittedBoxConfirm")));
					// out.println(ServletUtil.getJavaScript("parent.left.location='/totsys/common/inc/totper/left/left.jsp?On=main';"));
					out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/totper/main.jsp')"));
				} else if (insertType == 2) {
					totReport.setProcess(TotReportProcess.COMP);
					totReport.setRepTotDoc(masterDoc);

					pm.makePersistent(totReport);
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.submittedBoxConfirm2")));
					// out.println(ServletUtil.getJavaScript("parent.left.location='/totsys/common/inc/totper/left/left.jsp?On=comp';"));
					out.println(ServletUtil
							.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/endbox/report_list.jsp?reportType=COMP')"));
				}

			} else if (totRange == TotRange.EXTERNAL && status.length() == 0) {
				if (insertType == 0) {// 자료저장
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.submittedBoxConfirm3")));
					//out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/tempbox/report_list.jsp?reportType=TEMP')"));
                                        out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/tempbox/report_view.jsp?doctName="+doctName+"&reportID="+reportID+"&totperInfo=true&reportType=TEMP')"));
				} else if (insertType == 2) {
					totReport.setProcess(TotReportProcess.COMP);
					totReport.setRepTotDoc(masterDoc);
                    pm.makePersistent(totReport);
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.submittedBoxConfirm2")));
					// out.println(ServletUtil.getJavaScript("parent.left.location='/totsys/common/inc/totper/left/left.jsp?On=comp';"));
					out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/endbox/report_list.jsp?reportType=COMP')"));
				}
			}
			if (status.equals("1")) {
				out.println(ServletUtil.alert(TotReportProcess.NOT + MoumiConfig.getMessageBundle().getString("moumi.message.popup.toReported")));
		      //out.println(ServletUtil.getJavaScript("parent.left.location='/totsys/common/inc/totper/left/left.jsp?On=comp';"));
                                if( MString.isNull(callbackFunc) ) {
                                    out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/repoper/mydocbox/endbox/report_list.jsp?reportType=COMP')"));
                                }else{
                                    out.println(ServletUtil.getJavaScript(callbackFunc));
                                }
			}

			if (insertType != 1) {
				targetURI = (String) session.getAttribute("regSuccTargetURI");
				out.println(ServletUtil.redirect(targetURI));
			}


			//수정 이력 추가 시작
//			String templateHtml=Excel.adjustFmlaToExcel(TagFilter.removeBlankPara(TotReportUtil.toHTML(totReport)));
//			String sqlEmptyLob = "UPDATE MOUMI_TOT_REPORT_VERSION SET TEMPLATE_HTML = EMPTY_CLOB(), DATA=EMPTY_CLOB(), TOT_DATA=EMPTY_CLOB() WHERE REPORT_ID = ?";
//			String sql="INSERT INTO MOUMI_TOT_REPORT_VERSION( "+
//					   "REPORT_ID "+
//					  ",ACPT_CODE "+
//					  ",APPRO "+
//					  ",DOC_TYPE "+
//					  ",ATTACHMENTS "+
//					  ",CURRENT_REPOADM_ID "+
//					  ",DATA "+
//					  ",DEL_TYPE "+
//					  ",DEPT_ID "+
//					  ",USER_ID "+
//					  ",NOTE "+
//					  ",NUM "+
//					  ",PRSS "+
//					  ",RECOG "+
//					  ",REG_DATE "+
//					  ",REP_DOC_ID "+
//					  ",DOWN_DOC_ID "+
//					  ",SUBMIT_DATE "+
//					  ",TABLE_NUM "+
//					  ",TOT_DATA "+
//					  ",DOC_ID "+
//					  ",TYPE "+
//					  ",MNG_CODE "+
//					  ",OWNER_EMAIL "+
//					  ",OWNER_NAME "+
//					  ",OWNER_PHONE "+
//					  ",ACPT_DOC_CODE "+
//					  ",SECU_YN "+
//					  ",MODIFIER_ID "+
//					  ",MODIFIER_NAME "+
//					  ",TEMPLATE_HTML "+
//					  ",MODIFIER_DEPT_ID "+
//					  ",MODIFIER_DEPT_NAME "+
//					  ",ATTACHMENTS_PATH "+
//						") select "+
//					   "ID "+
//					  ",ACPT_CODE "+
//					  ",APPRO "+
//					  ",DOC_TYPE "+
//					  ",ATTACHMENTS "+
//					  ",CURRENT_REPOADM_ID "+
//					  ",DATA "+
//					  ",DEL_TYPE "+
//					  ",DEPT_ID "+
//					  ",USER_ID "+
//					  ",NOTE "+
//					  ",NUM "+
//					  ",PRSS "+
//					  ",RECOG "+
//					  ",SYSDATE "+
//					  ",REP_DOC_ID "+
//					  ",DOWN_DOC_ID "+
//					  ",SUBMIT_DATE "+
//					  ",TABLE_NUM "+
//					  ",TOT_DATA "+
//					  ",DOC_ID "+
//					  ",TYPE "+
//					  ",MNG_CODE "+
//					  ",OWNER_EMAIL "+
//					  ",OWNER_NAME "+
//					  ",OWNER_PHONE "+
//					  ",ACPT_DOC_CODE"+
//					  ",SECU_YN "+
//					  ",? "+ //로그인아이디
//					  ",? "+ //유저이름
//					  ",? "+ // 서식 html
//					  ",(select dept_id from moumi_muser where id=?) "+ //로그인아이디
//					  ",(select name from moumi_dept where id=(select dept_id from moumi_muser where id=?)) "+//로그인아이디
//					  ",ATTACHMENTS_PATH "+
//					  "FROM MOUMI_TOT_REPORT where id=?";// tot report id
//				// loginid, username ,templatehtml,loginid,loginid,totreportid
//				System.out.println("sql   \n" + sql.toString() +"\n report "+ totReport.getId().intValue() );
//				dbmanager.execUpdate(sqlEmptyLob,totReport.getId());
//
//
//				dbmanager.execUpdate(sql,usID,HttpSSOLogin.getUserName(req),templateHtml,usID,usID,totReport.getId());
//
//				dbmanager.commit();

				if (totReport.getSlaveTotDoc() != null)
					om.postCommit(); // jeus 6 problem

				tx.commit();

				//System.out.println("수정 이력 인서트 "+rsltcnt);
			//수정 이력 추가 끝

		} catch (Exception ex) {
			if (tx.isActive())
				tx.rollback();
			dbmanager.rollback();
			ex.printStackTrace();
			//LOG.error(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.save")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" {}, {}, {}",
					//new Object[] { usID, req.getRemoteAddr(), reportID });
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.saveFailAdmin")));

                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(ServletUtil.getJavaScript("history.back();"));

                        // 수정 : 외부 입력값 필터링
                        String callbackFunc2 = "history.back();";
                        String filtered_callbackFunc2 = callbackFunc2.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        //LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpReportRegister.doPost() filtered_callbackFunc2={}, Test OK ", filtered_callbackFunc2);
                        out.println(ServletUtil.getJavaScript(filtered_callbackFunc2));
                        //========================================

		} finally {
			dbmanager.execClose();
			pm.close();
		}
	}

	/************
	 * 보고 등록 ************* return -1 => 실패 return =0 => 변경사항 없음 return >0 => 성공
	 ********************************/
	private void dynaReportRegist(PersistenceManager pm, TotReport totReport, MultipartRequest multi, int acptNum, String inForm,
			String usID, String comment, String upFileName, String saveFileName, String tableRows, String status, int appro, String secuYn)
			throws Exception {
		Long formID = totReport.getTotDoc().getId();
		String tableTypes = totReport.getTotDoc().getTotTables().isEmpty() ? "" : totReport.getTotDoc().getTotTables()
				.iterator().next().getTypes();
		TotReportProcess prss = status.equals("1") ? TotReportProcess.NOT : TotReportProcess.TEMP;
//System.out.println("====> prss.toString() : " + prss.toString());
		Item item = new Item();
		int[] itemTypeList = item.getType(formID);
		int[] itemInTypeList = item.getInTypeList(formID);
		int inItemCount = item.getInCount(formID);
//		LOG.debug("totReport: {}", totReport);
//		LOG.debug("inItemCount: {}, formID: {}", inItemCount, formID);

		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();

		String[] tableRowList = tableRows.split(",");
		String[] tableTypeList = tableTypes.split(",");

		InsertMTable inMTable = new InsertMTable();
		int subFpos = 0;
		int[] tableColNumList = new int[tableTypeList.length]; // 원본 폼의 각 테이블당 몇개의 입력칸이 존재 하는지 그 수 저장

		for (int i = 0; i < tableTypeList.length; i++)
        {
			String subForm = inForm.substring(subFpos, inForm.indexOf("</table>", subFpos) + 8);
			subFpos = inForm.indexOf("</table>", subFpos) + 8;
			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++)
			tableColNumList[a] = tableColNumList[a] / Integer.parseInt(tableRowList[a]);

		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("'", "`");
	//	LOG.debug("datas: {}", datas);

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

		String totDatas = MReportData.getTotDatas(tableColNumList, totDataList);
       // LOG.debug("실제 데이타들: {}", totDatas);

		// 보고자료 DB에 입력
		int tableNum = 1; // Table 별 입력 할 때 사용 예정
		MUser mUser = pm.getObjectById(MUser.class, usID);
		if (acptNum >= 0)
		totReport.setAcceptanceCode(new AcceptanceCode(mUser.getUpperDept(pm).getName(), acptNum));
		totReport.setTableNum(tableNum);
		totReport.setUser(mUser);
		totReport.setData(datas);
		totReport.setTotData(totDatas);
		totReport.setNote(comment);
		totReport.setProcess(prss);
        /* 20110728 LJH */
        totReport.setDept(mUser.getUpperDept(pm));
        totReport.setAppro(appro); // 2018.02.26 부서공유 여부저장
        totReport.setSecuYn(secuYn);

        // 2014.09.24 by youngjun cho (해당없음으로 제출하는 경우에 submit_date 가 저장되도록 수정.)
        if (prss == TotReportProcess.NOT) {
        	totReport.setSubmitDate(new Date());
        }

        //20170821 수정 by wonseok Lee
        //FileUtil.putInFiles(saveFileName, totReport);//디비에 첨부파일 입력
//        FileUtil.putInFiles(saveFileName, totReport, multi);//디비에 첨부파일 입력

		pm.makePersistent(totReport);
//                FileUtil.delUpFiles(saveFileName, totReport);//물리 디렉토리에서 첨부파일 삭제
	}
}
