/*************************************************************************************************
 * 프로그램명 : HttpReportRegister.java 프로그램설명 : 집계 문서에대한 보고자 보고 또는 보고자 자료 변경에 사용 작성자 : 강원중 작성일 : 2004.01.12 변경일 : 2003.11.30
 **************************************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.ecross.ECrossInterface;
import kr.co.kihyun.beans.ecross.VCMCCMC2015;

import kr.co.kihyun.beans.entity.AcceptanceCode;
import kr.co.kihyun.beans.entity.AssignType;
import kr.co.kihyun.beans.entity.MDept;
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.ecross.CRUD;
import kr.co.kihyun.beans.entity.ecross.ECross;
import kr.co.kihyun.beans.entity.ecross.ECrossTotReport;
import kr.co.kihyun.beans.entity.ecross.IRemotePersistable;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.totsys.doc.table.DataDupCheck;
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.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.service.PrssReportsService;
import kr.co.kihyun.service.vo.PrssReportsVO;
import kr.co.kihyun.service.vo.TotReportVO;
import kr.co.kihyun.text.html.HtmlUtil;
import kr.co.kihyun.text.html.ServletUtil;
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.HttpVCMCCMC2016Receive")
public class HttpVCMCCMC2016Receive extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpVCMCCMC2016Receive.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");
		res.setHeader("Cache-Control","no-cache");
		res.setHeader("Pragma","no-cache");
		res.setDateHeader ("Expires", -1);
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);

                Long[] rptIds = null; //20160419 추가
                Long     docID  = MLong.parseLong(String.valueOf(req.getParameter("docID")));//20160502 추가
                
		MPersistenceManager moumiPm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = moumiPm.currentTransaction();
		MPersistenceManager eCrossPm = new MPersistenceManager(PMF.get("ECROSS").getPersistenceManager());
		Transaction eCrossTx = eCrossPm.currentTransaction();
		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem
                Long rptIdTmp = null;//20160419 추가
                
                try {
                        //20160502 IR 테이블 IS_APLIED N 인 report id 조회 추가 시작
                        Map param_tmp = new HashMap();
                        param_tmp.put("docID", docID);
                        param_tmp.put("isAplied", "N");
                        PrssReportsService rptService_tmp = new PrssReportsService(eCrossPm);
                        rptService_tmp.createIR_TOT_REPORT_ID_Srch(param_tmp);
                        
                        List list = rptService_tmp.executeQuery();
                        int cnt = 0;
                        if(list != null){
                            rptIds = new Long[list.size()];   
                            for(int i = 0; i < list.size(); i++ ) {
                                Object row = (Object) list.get(i);
                                rptIds[i] = MLong.parseLong(row.toString());
                                cnt++;
                            }//end for    
                        }//end if
                        //20160502 IR 테이블 IS_APLIED N 인  report id 조회 추가 끝
                       
                           
                        List<? extends IRemotePersistable> receivedList = null;

                        DataDupCheck dataDupChk = new DataDupCheck();//중복 데이타 체크
                        
                            for(Long rptId : rptIds){//20160419 추가
    
                                rptIdTmp =rptId;//20160419 추가
                                boolean flag = dataDupChk.getChk_MOUMI_TOT_REPORT(rptIdTmp);//중복 체크
                                TotReport totReport = null;
                            eCrossTx.begin();
                            tx.begin();

                                if(flag){
                                    totReport = moumiPm.getObjectById(TotReport.class, rptIdTmp);//moumi_tot_report 테이블 자료 조회
                                }

                                receivedList = this.loadTotReport(moumiPm, eCrossPm, totReport, docID, rptIdTmp, flag,eCrossTx,tx);//ir 테이블에서 읽어서 저장 delete, insert

                            tx.commit();
                            eCrossTx.commit();
                                
                        } //end for   
                            
                        if(receivedList != null && receivedList.size() > 0){
                            out.println(ServletUtil.alert("교육청에서 전송한 자료를 조회하였습니다"));
                        }else{
                                out.println(ServletUtil.alert("교육청에서 전송한 자료가 없습니다"));
                        }
                           
                } catch (Exception ex) {
                        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(), rptIdTmp });//20160419 수정
                        out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.saveFailAdmin")));
                        if (tx.isActive()) tx.rollback();
                        if (eCrossTx.isActive()) eCrossTx.rollback();
                } finally {
                        if (tx.isActive()) tx.rollback();
                            moumiPm.close();
                        if (eCrossTx.isActive()) eCrossTx.rollback();
                            eCrossPm.close();
                        out.println(ServletUtil.getJavaScript("parent.fn_indiClose();"));//20160421 추가
                }
	}
        
        //20160422  IR_MOUMI_TOT_REPORT 테이블에서 읽어서 MOUMI_TOT_REPORT 테이블에 저장      
       	public final List<? extends IRemotePersistable> loadTotReport(MPersistenceManager moumiPm, MPersistenceManager eCrossPm, TotReport totReport, Long docId, Long rptId,boolean flag,Transaction eCrossTx,Transaction tx) {
		List<IRemotePersistable> resultList = new ArrayList<IRemotePersistable>();

                try{

                        Query q = eCrossPm.newQuery(ECrossInterface.getReceiverClass(TotReport.class), "isAplied == false && id == p_id");
                        
                        q.setOrdering("createDate");
			q.declareParameters("Long p_id");
                        //v2. 6.SQL 삽입 : JDO형식이므로 해결책에 따른 prepare SQL 문으로 변경할 수 없음
			List<ECrossTotReport> remoteEntities = (List<ECrossTotReport>) q.execute(rptId);//IR 테이블 조회
                        //================
			List<IRemotePersistable> localEntities = new ArrayList<IRemotePersistable>();

                        int cnt  = 0;
                        int size = remoteEntities.size();
                        
			for (ECrossTotReport ec : remoteEntities) {
                                
				if(cnt == (size-1)){//가장 최근 데이타만 insert
                                    
                                    IRemotePersistable localEntity = null;
                                    if(flag){
                                         Class<TotReport> clazz = (Class<TotReport>) totReport.getClass();
                                         localEntity = ec.toMoumiEntity(moumiPm, clazz);
                                    }else{
                                    ec.setCrud(CRUD.C);
                                         localEntity = ec.toMoumiEntity(moumiPm, TotReport.class);
                                    }

                                    localEntities.add(moumiPm.makePersistent(localEntity));

                                }//end if
                                
				ec.setAplied(true);
				eCrossPm.makePersistent(ec);
                                cnt++;
			}
                        
			resultList.addAll(moumiPm.makePersistentAll(localEntities));

                }catch (Exception e){
                    e.printStackTrace();
                    if (tx.isActive()) tx.rollback();
                    if (eCrossTx.isActive()) eCrossTx.rollback();
                    moumiPm.close();
                    eCrossPm.close();
                }

		return resultList;
	}
}
