/*************************************************************************************************
 * 프로그램명 : DocView.java 프로그램설명 : 집계자가 올린 프로젝트 리스트 작성자 : 강원중 작성일 : 2004.01.09 변경일 : 2003.11.30
 **************************************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
//import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
//import javax.jdo.Query;
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.Board;

import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotDocType;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.TotTable;
import kr.co.kihyun.beans.entity.util.*;
//import kr.co.kihyun.beans.totsys.report.ReportUpdate;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.db.CommonDBManager;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.moumi.doc.table.MTableRemaker;
import kr.co.kihyun.moumi.doc.table.item.MItemInfo;
import kr.co.kihyun.service.TotReportService;
//import kr.co.kihyun.moumi.report.MReport;
import kr.co.kihyun.text.html.ServletUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocReFormConfig2")
public class HttpDocReFormConfig2 extends HttpServlet {

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

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		if (req.getMethod().equals("HEAD"))
			return;
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);
		HashMap<String, String> map = new HashMap<String, String>();
		/*********** User HttpLogin check ***********/
		if (!HttpSSOLogin.isLogin(req)) {
			String connURL = "document.location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);
		int sysAuth = HttpSSOLogin.getSysAuth(req);
		/********** parameter value **********/
		Long docID = new Long(MInteger.parseInt(req.getParameter("docID"), -1));

		int tableType = MInteger.parseInt(req.getParameter("tableType"));
		String itemNames = Encoder.toJava(req.getParameter("itemNames"));
		String itemSizes = Encoder.toJava(req.getParameter("itemSizes"));
		String itemExprs = Encoder.toJava(req.getParameter("itemExprs"));
		String itemDescs = Encoder.toJava(req.getParameter("itemDescs"));
		String itemTypes = Encoder.toJava(req.getParameter("itemTypes"));

		String tableNums = Encoder.toJava(req.getParameter("tableNums"));
		String colNums = Encoder.toJava(req.getParameter("colNums"));
		String rowNums = Encoder.toJava(req.getParameter("rowNums"));
		int defItemSize = MInteger.parseInt(req.getParameter("defItemSize"), 10);
		String docForm = (String) session.getAttribute("docForm");
		String tableTypes = MString.checkNull(req.getParameter("tableTypes")); // 새버전
																				// 동적/정적
																				// 선택#
																				// 2008.03.18
																				// 구경모

		//연계서식까지 같이 수정
		CommonDBManager db=new CommonDBManager();
		ResultSet rs = null;
		String sql="select REP_ID from MOUMI_TOT_DOC where id=?";
		ArrayList<Long> docids=new ArrayList<Long>();
		docids.add(docID);
		try {
			rs= db.execQuery(sql, docID);
			if(rs.next()){
				String rep_id=rs.getString(1);
				if(rep_id!=null){
					out.println(ServletUtil.alert("연계문서는 수정할 수 없습니다."));
					out.println(ServletUtil.getJavaScript("history.back();"));
					return;
				}
			}
			rs.close();
			db.pstmt.close();



//			sql="select ID from MOUMI_TOT_DOC where REP_ID=?";
//			rs= db.execQuery(sql, docID);
//			while (rs.next()) {
//				Long did=rs.getLong(1);
//				if(!docids.contains(did))docids.add(did);
//			}
//			rs.close();
//			db.pstmt.close();


//			sql="select * from MOUMI_TOT_report where doc_id in(seqs) and prss in(5,6) and del_type = 'N'";
//			String txtids=StringUtils.join(docids.toArray(),",");
//			sql=sql.replace("seqs", txtids);
//			rs= db.execQuery(sql);
//			if(rs.next()){
//				out.println(ServletUtil.alert("집계자료의 서식을 수정할 수 없습니다. 제출자료 및 연계자료 중 결재대기중, 결재완료 상태인 제출자료가 있습니다."));
//				out.println(ServletUtil.getJavaScript("history.back();"));
//				db.execClose();
//				return;
//			}
//			rs.close();
//			db.pstmt.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally{
			try{
	    		if(null != rs) rs.close();
	    	}catch(Exception e1){
	    		e1.printStackTrace();
	    	}
		    	db.execClose();

		}


		for (Long did : docids) {
			docID=did;
			PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();

				// 결재대기중(진행), 결재완료 되었거나 연계등록 상태인 자료의 갯수를 조회한다. 2014.12.05 by
				// YOUNGJUN,CHO
				// 1건이라도 있으면 서식을 수정해선 안된다.
//				TotReportService totReportService = new TotReportService(pm);
//				System.out.println("====> totReportService : ");
//				int unModifiableCount = totReportService.getUnModifiableTotReportCount(docID);
//				System.out.println("====> unModifiableCount : ");
//
//				// System.out.println("====> HttpDocReFormConfig2 approveCompCount : "
//				// + approveCompCount);
//				LOG.info("====> [At kr.co.kihyun.beans.totsys.doc.HttpDocReFormConfig2] docID : {}, report count(prss = 5 or 6 / down_doc_id is not null) : {}",
//						new Object[] { docID, unModifiableCount });
//
//				// 건수가 1개라도 있으면 집계자료의 서식을 수정하지 못하게 한다.
//				if (unModifiableCount > 0) {
//					out.println(ServletUtil.alert("집계자료의 서식을 수정할 수 없습니다. 제출자료 중 결재대기중, 결재완료, 연계등록 상태인 제출자료가 있습니다."));
//					out.println(ServletUtil.getJavaScript("history.back();"));
//					return;
//				}

				TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
				if (sysAuth == MoumiConfig.TOTPER && !usID.equals(totDoc.getUser(pm).getId())) {
					out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.formDoc")
							+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.modifyFail")));
					out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/formbox/doc_list.jsp';"));
					return;
				}
				// item info value set
				MItemInfo itemInfo = new MItemInfo();
				itemInfo.itemInfo(itemNames, itemSizes, itemExprs, itemDescs, itemTypes, tableNums, colNums, rowNums, defItemSize);
				// 셀정의 수식을 엑셀 수식으로 변환하여 form에 적용 시킴
				docForm = MTableRemaker.remake(docForm, itemInfo); // 셀정의 수식을 엑셀저장시
																	// 적용되게 해줌
				totDoc.setForm(docForm);

				Set<TotTable> totTables = totDoc.getTotTables();
				for (TotTable table : totTables) {
					table.setType(TotTable.TotTableType.asType(tableType));
					table.setTypes(tableTypes);
					table.setItemSize(defItemSize);
					table.setForm(docForm);
					pm.deletePersistentAll(totDoc.getTotItems());
				}

				pm.makePersistent(totDoc);
				pm.makePersistentAll(itemInfo.toTotItemList(totDoc));
				pm.makePersistentAll(totTables);

				Set<TotReport> reports = totDoc.getTotReports();
				for (TotReport report : reports) {
					//연계된 리포트 설정값 유지
					if(report.getSlaveTotDoc()==null){
						report.setProcess(TotReportProcess.ACCEPT);
						report.setUser(null);
						//서식수정시 기존 데이터 삭제
						report.setData(null);
						report.setTotData(null);
						report.setAttachmentsPath(null);
						report.clearAttachment();
					}
					//연계서식 삭제 안되게
					/*TotDoc td = report.getSlaveTotDoc();
					if (td != null) {
						td.setDeleted(true);
						pm.makePersistent(td);
						report.setSlaveTotDoc(null);
					}*/
				}
				pm.makePersistentAll(reports.toArray()); // 모든 totReport process를
															// 접수로 변경
				tx.commit();

				String targetURI = "";
				LOG.info(TotDocType.FORM_DOC + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify")
								+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success")
								+ " {}, {}, {}", new Object[] { usID, req.getRemoteAddr(), docID });
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.formChangeSuccess2")
						+ "(" + TotDocType.FORM_DOC + ")"));
				targetURI = (String) session.getAttribute("modifySuccTargetURI2") + "?docID=" + docID;
				out.println(ServletUtil.redirect(targetURI));
			} catch (Exception e) {
				LOG.error(TotDocType.FORM_DOC + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify")
								+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail")
								+ "  {}, {}, {}", new Object[] { usID, req.getRemoteAddr(), docID });
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.alterFail")));
				// 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) : HttpDocReFormConfig2.doPost() filtered_callbackFunc={}, Not Test",filtered_callbackFunc);
				out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
				// ============================================================

			} finally {
				if (tx.isActive()) {
					tx.rollback();
				}
				pm.close();
			}
		}

	}
}
