/*************************************************************************************************
 * 프로그램명 : 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.HttpTransfer6")
public class HttpTransfer6 extends HttpServlet {
	/**
	 * 
	 **/
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpTransfer6.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 **********/
		Long reportID = MLong.parseLong(req.getParameter("reportID"));
                String sDocReportType = MString.checkNull(req.getParameter("docReportType"));   //문서 구분(D:집계문서, R:제출문서)                
		String userID = Encoder.toJava(req.getParameter("userID"));
                String reportType = Encoder.toJava(req.getParameter("reportType"));
                String exeFlag = Encoder.toJava(req.getParameter("exeFlag"));
                String callbackFunc = Encoder.toJava(req.getParameter("callbackFunc"));                

//System.out.println("HttpTransfer6.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);
			TotReport totReport = pm.getObjectById(TotReport.class, reportID);
			totReport.setUser(toUser);
			totReport.setDept(toUser.getUpperDept(pm));

                        if (totReport.getSlaveTotDoc() != null) {
                            TotDoc totDoc = pm.getObjectById(TotDoc.class, totReport.getSlaveTotDoc().getId());
                            totDoc.setUser(toUser);
                            pm.makePersistent(totDoc);
			}

                        pm.makePersistent(totReport);

			UserHistory userHistory = null;
			userHistory = new UserHistory(totReport.getTotDoc(), 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("", reportID, sDocReportType);

                        //2.모든 데이터의 등록자를 변경된 담당자로 변경한다.
                        if(tmpList != null) {
                            for(int ii=0; ii<tmpList.size(); ii++) {
                                Object[] objData = (Object[])tmpList.get(ii);
//System.out.println("HttpTransfer6.doPost() tmpList ==========");
//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);
                            }
                        }            
                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++
            
			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(), reportID });

            
            if(reportType.equals("TEMP"))
                out.println(ServletUtil.getJavaScript("parent.opener.location='/totsys/repoper/mydocbox/tempbox/report_list.jsp?reportType=TEMP';"));
            else
                out.println(ServletUtil.getJavaScript("parent.opener.location='/totsys/repoper/mydocbox/returnbox/report_list.jsp';"));
           
			out.println(ServletUtil.getJavaScript("parent.close();"));
		} catch (Exception ex) {
			ex.printStackTrace();
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.reConfirmation")));
			out.println(ServletUtil.getJavaScript("parent.close();"));
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
	}
}
