/*************************************************************************************************
 * 프로그램명 : HttpAssign.java 프로그램설명 : 보고자 이관 요청에 대한 정보 작성자 : 작성일 : 변경일 :
 **************************************************************************************************/

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

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

import javax.jdo.PersistenceManager;
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.AcptDoc;

import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.repoper.HttpPrssUpdate")
public class HttpPrssUpdate extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpPrssUpdate.class);

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

		/*********** 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 deptName = HttpSSOLogin.getDeptName(req);

		/********** parameter value **********/
		Long reportID = MLong.parseLong(req.getParameter("reportID"), null);
		Long repDocID = MLong.parseLong(req.getParameter("repDocID"), null);
               
		int prss = MInteger.parseInt(req.getParameter("prss"));
		int totRange = MInteger.parseInt(req.getParameter("totRange"), 0);
                int accDocCd = MInteger.parseInt(req.getParameter("accDocCd"));
                //out.println("accDocCd: {}"+ accDocCd);
                LOG.debug("deptName :  {}",deptName);
		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		try {
			/********** regist **********/
			TotReport totReport = pm.getObjectById(TotReport.class, reportID);            
            
            

            if (prss == MReport.COMP) {
				totReport.setProcess(TotReportProcess.COMP);
				totReport.setRegDate(new Date());
				totReport.setRepTotDoc(repDocID == null ? null : pm.getObjectById(TotDoc.class, repDocID));
                                AcptDoc acptDoc =null;
                                if(accDocCd > 0 && !MString.isNull(deptName)){
                                    acptDoc = new AcptDoc(deptName, accDocCd);
                                }
                                totReport.setAcptDoc(acptDoc);

				pm.makePersistent(totReport);
			} else if (prss == MReport.ACCEPT_LIST) {
                totReport.clearAttachment();
                totReport.setData(null);
				totReport.setProcess(TotReportProcess.values()[prss]);
				totReport.setNote(null);
				//if (totRange == 0)
					totReport.setUser(null);
				pm.makePersistent(totReport);
			} else if (prss == MReport.RETURN) {
				totReport.setProcess(TotReportProcess.values()[prss]);
				pm.makePersistent(totReport);
			} else {
				throw new IllegalArgumentException("prss("+prss+") is incorrect.");
			}
			LOG.info(TotReportProcess.COMP + "{}, {}, {}", new Object[] { usID, req.getRemoteAddr(), reportID });
			// out.println(ServletUtil.alert("제출완료!\\n \\n제출된 자료는 제출완료함에서 확인할 수 있습니다."));
			String targetURI = (String) session.getAttribute("compSuccTargetURI");
			out.println(ServletUtil.redirect(targetURI));
                //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
		} catch (IllegalArgumentException iaex) {
                        LOG.error(TotReportProcess.COMP + "{}, {}, {}", new Object[] { usID, req.getRemoteAddr(), reportID });
			out.println(ServletUtil.alert(TotReportProcess.COMP + MoumiConfig.getMessageBundle().getString("moumi.message.popup.failTryAgain")));
			out.println(ServletUtil.getJavaScript("history.back();"));
			iaex.printStackTrace();
                //++++++++++++++++++++++++++++++++++++++++++++++++
                } catch (Exception ex) {
			LOG.error(TotReportProcess.COMP + "{}, {}, {}", new Object[] { usID, req.getRemoteAddr(), reportID });
			out.println(ServletUtil.alert(TotReportProcess.COMP + MoumiConfig.getMessageBundle().getString("moumi.message.popup.failTryAgain")));
			//v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN   
//                        out.println(ServletUtil.getJavaScript("history.back();"));
                        
                        // 수정 : 외부 입력값 필터링
                        String callbackFunc = "history.back();";
                        String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpPrssUpdate.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                        out.println(ServletUtil.getJavaScript(filtered_callbackFunc));      
                        //========================================
                
			ex.printStackTrace();
		} finally {
			pm.close();
		}
	}
}
