
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.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.HttpReportPrssChange2")
public class HttpReportPrssChange2 extends HttpServlet
{
	private static final Logger LOG = LoggerFactory.getLogger(HttpReportPrssChange2.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();
		if (!HttpSSOLogin.isLogin(req))
		{
			String connURL = "location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}
		String usID=HttpSSOLogin.getLoginID(req);
		int sysAuth=HttpSSOLogin.getSysAuth(req);
		String dtID=HttpSSOLogin.getDeptID(req);
		Long docID=MLong.parseLong(req.getParameter("docID"));
		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"));
		LOG.debug("changePrss: {}, changeReportID: {}", changePrss, changeReportID);

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx=pm.currentTransaction();
		ObjectManager om=((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager();
        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")));
				out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/tot_reports/total_reports.jsp?docID="+docID+"&docType="+docType+"';"));
				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 ID = '"+splitReportIDs[i]+"'");
                    //LOG.debug("UPDATE MOUMI_TOT_REPORT SET ATTACHMENTS_PATH = "+null+" WHERE 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]+"')");
                    //LOG.debug("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);
					if(totReport.getSlaveTotDoc() != null) pm.deletePersistent(totReport.getSlaveTotDoc());
					acdbm1.commit();
				}
				else if ("return".equals(changePrss))
				{
					if (totReport.getProcess() == TotReportProcess.COMP) totReport.setProcess(TotReportProcess.RETURN);
					else if (totReport.getProcess() == TotReportProcess.NOT) totReport.setProcess(TotReportProcess.ACCEPT);
					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();
			tx.commit();
			out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/tot_reports/total_reports.jsp?docID="+docID+"&docType="+docType+"';"));
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
            acdbm1.rollback();
                         //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/tot_reports/total_reports.jsp?docID="+docID+"&docType="+docType+"';"));

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