/*************************************************************************************************
 * 프로그램명 : HttpReportPrssChange.java 프로그램설명 : Dept Prss Change 작성자 : 작성일 : 변경일 :
 **************************************************************************************************/

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

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
//import java.util.List;

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 kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.lang.Encoder;
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.report.MReport;
import kr.co.kihyun.text.html.ServletUtil;

import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.Memo;
//import kr.co.kihyun.beans.entity.Repoadm;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
//import kr.co.kihyun.beans.entity.Board;
//import kr.co.kihyun.beans.entity.TotDocProcess;

import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.db.CommonDBManager;

import org.datanucleus.ObjectManager;
import org.datanucleus.jdo.JDOPersistenceManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.totper.HttpReportPrssChange")
public class HttpReportPrssChange extends HttpServlet {
	private static final Logger LOG = LoggerFactory.getLogger(HttpReportPrssChange.class);

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

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

		/********** parameter value **********/
		String usID = HttpSSOLogin.getLoginID(req);
		int sysAuth = HttpSSOLogin.getSysAuth(req);
		String dtID = HttpSSOLogin.getDeptID(req);
		Long docID = MLong.parseLong(req.getParameter("docID"));
		int listType = MInteger.parseInt(req.getParameter("listType"), -1);
		String url = MString.checkNull(req.getParameter("url"));
		String changeReportID = MString.checkNull(req.getParameter("changeReportID"));
		String changePrss = MString.checkNull(req.getParameter("changePrss"));
		String contents = Encoder.toJava(MString.checkNull(req.getParameter("contents")));
		String docType = MString.checkNull(req.getParameter("docType"));
        String strPage = (String) Encoder.toJava(req.getParameter("strPage"));
        String innerStrPage = (String) Encoder.toJava(req.getParameter("strPage"));
        String findOption = MString.checkNull(Encoder.toJava(req.getParameter("findOption")));
        String findWord = MString.checkNull(Encoder.toJava(req.getParameter("findWord")));
		LOG.debug("changePrss: {}, changeReportID: {}", changePrss, changeReportID);
		out.println(ServletUtil
				.getJavaScript("<script> history.go(-1);</script>"));

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem
        CommonDBManager acdbm1=new CommonDBManager();
		try {
			String[] splitReportIDs = changeReportID.split(",");
			TotReport totReport = null;
			Memo memo = null;
			TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);

			tx.begin();

			if (sysAuth == MoumiConfig.TOTPER && !usID.equals(totDoc.getUser(pm).getId())) {
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc")
						+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.status") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.change") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" !"+MoumiConfig.getMessageBundle().getString("moumi.message.popup.normalHandle")));
				if ("report_view".equals(url)) {
					out.println(ServletUtil
							.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_view.jsp?reportID="
									+ changeReportID + "&docType=" + docType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
				} else {
					out.println(ServletUtil
							.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_list.jsp?docID="
									+ docID + "&docType=" + docType + "&listType=" + listType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
				}
				return;
			}

      		StringBuilder sql = new StringBuilder(250);
            for (int i = 0; i < splitReportIDs.length; i++){

            	totReport = pm.getObjectById(TotReport.class, MLong.parseLong(splitReportIDs[i]));


            	if ("accept".equals(changePrss)){
            		//20170830 부서초기화시 첨부파일경로 삭제 by wonseok Lee
            		sql.delete(0, sql.length());
            		sql.append("UPDATE MOUMI_TOT_REPORT SET ATTACHMENTS_PATH = null WHERE DEL_TYPE = 'N' and ID = '"+splitReportIDs[i]+"'");
            		//LOG.debug("UPDATE MOUMI_TOT_REPORT SET ATTACHMENTS_PATH = "+null+" WHERE DEL_TYPE = 'N' and ID = '"+splitReportIDs[i]+"'");
            		acdbm1.execUpdate(sql.toString());
            		acdbm1.pstmt.close();

            		sql.delete(0, sql.length());
            		sql.append("UPDATE MOUMI_TOT_REPORT_VERSION SET ATTACHMENTS_PATH = null WHERE REPORT_ID = '"+splitReportIDs[i]+"' AND ID=(SELECT MAX(ID) FROM MOUMI_TOT_REPORT_VERSION  WHERE DEL_TYPE = 'N' AND REPORT_ID = '"+splitReportIDs[i]+"')");
            		acdbm1.execUpdate(sql.toString());
            		acdbm1.pstmt.close();

            		//20170830 부서초기화시 첨부파일 삭제  by wonseok Lee
            		String attacheFileDir = MoumiConfig.getFileDirectory()+"/"+Long.toString(docID)+"/"+splitReportIDs[i]+"/"+totReport.getDept()+"/";

            		File Dir = new File(attacheFileDir);

            		if(Dir.isDirectory()){
            			File[] files = Dir.listFiles();
            			if(files.length>0){
            				for(File f: files){
            					if(f.isFile()) {
            						f.delete();
            						LOG.debug("f.getName()["+f.getName()+"]");
            					}
            				}//end of for
            			}
            		}

            		/*부서초기화 시 기관코드로 업데이트  17.06.20 by jskim*/
            		String organ = totReport.getDept(pm).getGrade().toString();
            		if(organ.equals("")){
            			MDept organId = totReport.getDept(pm).getOrgan(pm);
            			totReport.setDept(organId);
            		}
            		totReport.clearAttachment();
            		totReport.setData(null);
            		totReport.setProcess(TotReportProcess.ACCEPT);
            		totReport.setUser(null);
            		TotDoc td=totReport.getSlaveTotDoc();

            		if(td != null){
            			td.setDeleted("Y");
            			pm.makePersistent(td);
            			totReport.setSlaveTotDoc(null);
            		}
                    acdbm1.commit();
            	}else if ("return".equals(changePrss)){
            		if (totReport.getProcess() == TotReportProcess.COMP) {         //제출완료 6   --> 재입력요청 3
            			totReport.setProcess(TotReportProcess.RETURN);
            		} else if (totReport.getProcess() == TotReportProcess.NOTE) {  //회수요청 14  --> 재입력요청 3
            			totReport.setProcess(TotReportProcess.RETURN);
            		} else if (totReport.getProcess() == TotReportProcess.NOT) {   //해당없음 12  --> 접수    0(X), 재입력요청 3(O)
            			//totReport.setProcess(TotReportProcess.ACCEPT);
            			totReport.setProcess(TotReportProcess.RETURN);
            		}
            		memo = new Memo("555", pm.getObjectById(MUser.class, usID), totReport.getUser(pm), contents,
            				totReport.getTotDoc(), pm.getObjectById(MDept.class, dtID), totReport.getDept(pm));
            		memo.setTotReport(totReport);
            		pm.makePersistent(memo);
            	}
            	totReport.setCurrentRepoadm(null);
            	pm.makePersistent(totReport);
            }

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

            tx.commit();

            if ("report_view".equals(url)) {
            	out.println(ServletUtil
            			.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_view.jsp?reportID="
            					+ changeReportID + "&docType=" + docType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
            } else {
            	out.println(ServletUtil
            			.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_list.jsp?docID="
            					+ docID + "&docType=" + docType + "&listType=" + listType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
            }
		} catch (Exception ex) {
			ex.printStackTrace();
        	acdbm1.rollback();
			if ("report_view".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_view.jsp?reportID="
								+ changeReportID + "&docType=" + docType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
			} else {
                                //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//				out.println(ServletUtil
//						.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/reports/report_list.jsp?docID="
//								+ docID + "&docType=" + docType + "+&listType=" + listType + "';"));

                                // 수정 : 외부 입력값 필터링
                                String callbackFunc = "document.location='/totsys/totper/mydocbox/prssbox/reports/report_list.jsp?docID="
								+ docID + "&docType=" + docType + "+&listType=" + listType + "&innerStrPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';";
                                String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll(",","");
                                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpReportPrssChange.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                                out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                                //========================================
			}
		} finally {
			if (tx.isActive())
				tx.rollback();

        	acdbm1.execClose();
			pm.close();
		}
	}
}
