/**
 * ***********************************************************************************************
 * 프로그램명 : HttpAssign.java 프로그램설명 : 보고자 이관 요청에 대한 정보 작성자 : 작성일 : 변경일 :
 *************************************************************************************************
 */
package kr.co.kihyun.beans.totsys.repoper;

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

import javax.jdo.PersistenceManager;
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 kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.ShareDoc;
import kr.co.kihyun.service.ShareDocService;
import kr.co.kihyun.beans.entity.TotDoc;
//import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.UserHistory;
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.Encoder;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.text.html.ServletUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.repoper.HttpTransfer2")
public class HttpTransfer2 extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private static final Logger LOG = LoggerFactory.getLogger(HttpTransfer2.class);
    String assignInfo = "";

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

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

        /**
         * ******** parameter value *********
         */
//xxx        Long docID = MLong.parseLong(req.getParameter("docID"));
        String docID = MString.checkNull(req.getParameter("docID"));
        String sDocReportType = MString.checkNull(req.getParameter("docReportType"));   //문서 구분(D:집계문서, R:제출문서)
        String userID = Encoder.toJava(req.getParameter("userID"));                     //변경된 담당자
        String exeFlag = Encoder.toJava(req.getParameter("exeFlag"));
        String callbackFunc = Encoder.toJava(req.getParameter("callbackFunc"));

        String docType = MString.checkNull(req.getParameter("docType"));
        String strPage = (String) Encoder.toJava(req.getParameter("strPage"));
        String findOption = MString.checkNull(Encoder.toJava(req.getParameter("findOption")));
        String findWord = MString.checkNull(Encoder.toJava(req.getParameter("findWord")));

//System.out.println("HttpTransfer2.doPost ======================================");
//System.out.println("docID          = "+docID);
//System.out.println("sDocReportType = "+sDocReportType);
//System.out.println("userID         = "+userID);
//System.out.println("exeFlag        = "+exeFlag);
//System.out.println("callbackFunc   = "+callbackFunc);
//System.out.println("===========================================================");

        /**
         * ******** regist *********
         */
        String user = HttpSSOLogin.getLoginID(req);  //처리자

        PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
        Transaction tx = pm.currentTransaction();
        try {
            tx.begin();

            MUser fromUser = pm.getObjectById(MUser.class, user);
            MUser toUser = pm.getObjectById(MUser.class, userID);
//            TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
//            totDoc.setUser(toUser);
//            totDoc.setDept(toUser.getUpperDept(pm));
//
//            pm.makePersistent(totDoc);
//
//            UserHistory userHistory = null;
//            userHistory = new UserHistory(totDoc, fromUser, toUser, toUser.getUpperDept(pm));
//            pm.makePersistent(userHistory);

            docID = docID.trim();
            if (docID != null && !"".equals(docID)) {
                String[] docIDList = docID.split(",");

                for (int x = 0; x < docIDList.length; x++) {
//                    System.out.println("HttpTransfer2.doPost============");
//                    System.out.println("docIDList = " + docIDList[x]);
//                    System.out.println("================================");

                    TotDoc totDoc = pm.getObjectById(TotDoc.class, MLong.parseLong(docIDList[x]) );
                    totDoc.setUser(toUser);
                    if(Long.parseLong(docIDList[x]) < 1700000000){
                    	totDoc.setDept(toUser.getUpperDept(pm));
                    }

                    pm.makePersistent(totDoc);

                    UserHistory userHistory = null;
                    if(Long.parseLong(docIDList[x]) > 1700000000){
                    	userHistory = new UserHistory(totDoc, fromUser, toUser,  totDoc.getDept(pm));
                    }else{
                    	userHistory = new UserHistory(totDoc, fromUser, toUser, toUser.getUpperDept(pm));
                    }
                    pm.makePersistent(userHistory);

                    //2014.09.05  Add by KWON,HAN : 사용자공유의 등록자를 변경한다.
                    //1.문서 ID(DOC_ID), 문서 구분(DOC_REPORT_TYPE)에 해당하는 모든 데이터를 조회한다.
                    ShareDocService shareDocSearch = new ShareDocService(pm);
                    List tmpList  = shareDocSearch.getSearchDocIdType("", docIDList[x], sDocReportType);

                    //2.모든 데이터의 등록자를 변경된 담당자로 변경한다.
                    if(tmpList != null) {
                        for(int ii=0; ii<tmpList.size(); ii++) {
                            Object[] objData = (Object[])tmpList.get(ii);

//                            System.out.println("HttpTransfer2.doPost() tmpList = " + ii);
//                            System.out.println("ID = " + objData[0]);
//                            System.out.println("USER_ID = " + objData[1]);
//                            System.out.println("==================================");

                            ShareDoc shareDocUpd = pm.getObjectById(ShareDoc.class, (Long) objData[0]);   //0.ID

                            shareDocUpd.setRegId(userID);
                            pm.makePersistent(shareDocUpd);
                        }
                    }
                    //++++++++++++++++++++++++++++++++++++++++++++++++++++++
                } //for
            } //if

            tx.commit();

            out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.chargeTrans")));
            LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.chargeCh") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") + " {}, {}, {}", new Object[]{userID, req.getRemoteAddr(), docID});
//              	out.println(ServletUtil.getJavaScript("parent.opener.location='/totsys/totper/main.jsp';"));
            //out.println(ServletUtil.getJavaScript("parent.opener.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=TEMP';"));
            out.println(ServletUtil.getJavaScript("parent.opener.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));
            out.println(ServletUtil.getJavaScript("parent.close();"));
        } catch (Exception ex) {
            ex.printStackTrace();
            out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.reConfirmation")));
            //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//            out.println(ServletUtil.getJavaScript("parent.close();"));

            // 수정 : 외부 입력값 필터링
            String callbackFunc2 = "parent.close();";
            String filtered_callbackFunc2 = callbackFunc2.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
            LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpTransfer2.doPost() filtered_callbackFunc2={}, Not Test", filtered_callbackFunc2);
            out.println(ServletUtil.getJavaScript(filtered_callbackFunc2));
            //========================================

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