<%@page import="kr.co.kihyun.moumi.MoumiConfig"%>
<%@ page contentType="text/html; charset=UTF-8"
         import="java.net.URLEncoder"
         import="java.util.List"
         import="java.util.Map"
         import="java.util.HashMap"
         import="kr.co.kihyun.beans.user.HttpSSOLogin"
         import="kr.co.kihyun.text.html.ServletUtil"
         import="kr.co.kihyun.lang.MString"
         import="kr.co.kihyun.moumi.Moumi"
         import="kr.co.kihyun.lang.MLong"
         import="javax.jdo.PersistenceManager"
         import="javax.jdo.Transaction"
         import="kr.co.kihyun.beans.entity.util.*"
         import="kr.co.kihyun.beans.entity.*"
         import="java.util.StringTokenizer"
         import="kr.co.kihyun.beans.user.MultiCheck"%>
<%@page import="kr.co.kihyun.service.*, kr.co.kihyun.service.vo.*, kr.co.kihyun.service.util.*"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%    PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
    Transaction tx = pm.currentTransaction();
    try {
        /**
         * ********* User HttpSSOLogin check **********
         */
        if (!HttpSSOLogin.isLogin(request)) {
            String connURL = "opener.location='/totsys/login/login.jsp';";
            out.println(ServletUtil.getJavaScript(connURL));
            out.println(ServletUtil.getJavaScript("window.close();"));
            return;
        }

        /**
         * ******** session내의 userId *********
         */
        String usID = HttpSSOLogin.getLoginID(request);
        String dtID = HttpSSOLogin.getDeptID(request);
        int sysAuth = HttpSSOLogin.getSysAuth(request);

        /**
         * **** Parameter *****
         */
        String docReportType = MString.checkNull(request.getParameter("docReportType"));  //문서 구분(D:집계문서, R:제출문서) A:인사이동 후 담당자 일괄변경
        String exeFlag = MString.checkNull(request.getParameter("exeFlag"));              //list, form
        Long docID = MLong.parseLong(request.getParameter("docID"), null);
        Long reportID = MLong.parseLong(request.getParameter("reportID"), null);
        String rptDocID = request.getParameter("rptDocID");
        String rptReportID = request.getParameter("rptReportID");
        String boxName = clearXSS(request.getParameter("boxName"), "");

//        System.out.println("rptDocID = "+rptDocID);
//        System.out.println("rptReportID = "+rptReportID);

        String callbackFunc = MString.checkNull(request.getParameter("callbackFunc"));
        String procMode = MString.checkNull(request.getParameter("proc_mode"));
        boolean hideUser = MString.isNull(request.getParameter("hideUser")) ? true : new Boolean(request.getParameter("hideUser"));
        String userYN = "N";
        if (hideUser == false) {
            userYN = "Y";
        } else {
            userYN = "N";
        }
        String reportType = clearXSS(request.getParameter("reportType"), "");

        if (MString.isNull(procMode)) {
            tx.begin();

            //TotReport totReport = (TotReport)pm.getObjectById(TotReport.class, reportID);
            String titleName = Moumi.getMessageBundle().getString("moumi.message.tot_doc.docList") + Moumi.getMessageBundle().getString("moumi.message.tot_doc.name");
            MDept dept = (MDept) pm.getObjectById(MDept.class, dtID);

            String deptID = dtID;

            //while(!dept.isDocUnit()) dept=dept.getUpperDept(pm);
            //deptID = dept.getId();
            dept = dept.getRootDept(pm);
            deptID = dept.getId();
System.out.println("deptID before=======   " + deptID );
            //2014.09.29 Add by KWON,HAN
        if("A".equals(docReportType)) {
            deptID = "";
        }
        System.out.println("deptID after=======   " + deptID );
            tx.rollback();
%>

<!DOCTYPE html>
	<html lang="ko">
        <meta charset="UTF-8">
        <script type="text/javascript" src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="/totsys/common/js/jquery.cookie.js"></script>
		<script type="text/javascript" src="/totsys/common/js/jquery.hotkeys.js"></script>
		<script type="text/javascript" src="/totsys/common/js/jquery.jstree.js"></script>

        <title><%=Moumi.getTitle()%></title>
        <link rel="stylesheet" href="/totsys/common/css/text.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/kecttep.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/SquareButtons.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/popup.css" type="text/css">
		<link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
        <script src="/totsys/common/js/rollover.js"></script>
        <script>
            var nodeType;
            var deptName;
            var userName;
            var userID;

            function fnInit() {
                /* @@@ test
                 document.getElementById('search').value = "손기영";
                */
            }

            function searchWord() {
                var type = $('#findOption').val();
                type = type.toUpperCase();
                //alert("type = " + type);
                var word = $('#search').val();
                word = $.trim(word);
                $('#search').val(word);
                if (word.length < 2) {
                    alert("검색어는 2글자 이상이어야 합니다.");
                    return;
                }
                var $ff = $("#leftFrame");
                $ff[0].contentWindow.$("#searchType").text(type);  //검색유형
                $ff[0].contentWindow.$("#searchWord").text(word);  //검색값
                $ff[0].contentWindow.$("#search").click();
            }

            //조직도에서 검색된 노드로 포커스를 이동시킨다.  strType : down, up
            function focusMove(strType) {
                //alert("strType = " + strType);
                var $ff = $("#leftFrame");
                $ff[0].contentWindow.$("#moveType").text(strType);      //포커스이동타입
                $ff[0].contentWindow.$("#focusMove").click();
            }

            function userList(id, deptname, name, type) {
                if (type == 'user')
                    id = id.split('/')[0];
                nodeType = type;
                deptName = deptname;
                userName = name;
                userID = id;
            }

            //function putNodeType(type, id, name) {
            function putNodeType(type, id, deptname,  name) {
                nodeType = type.toLowerCase();
                userID = id;
                deptName = deptname;
                userName = name;
            }

            function onOk() {
                if (nodeType !== 'user') {
                    //사용자를 선택하세요!
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.selectUser")%>');

                    //deptName / userName 으로 담당자를 변경하시겠습니까?
                } else if (confirm("'" + deptName + " / " + userName + "' \n\n으로 담당자를 변경하시겠습니까?")) {
                    document.transfer.userID.value = userID;
                    document.transfer.submit();
                }
            }

        </script>
    </head>
    <body class="over_hidden" onload="//fnInit();" >
        <FORM name="transfer" method="post">
            <INPUT type="hidden" name="proc_mode"     value="change_owner">
            <input type="hidden" name="docReportType" value="<%=docReportType%>">
            <input type="hidden" name="exeFlag"       value="<%=exeFlag%>">
            <INPUT type="hidden" name="docID"         value="<%=docID%>">
            <INPUT type="hidden" name="rptDocID"      value="<%=rptDocID%>">
            <INPUT type="hidden" name="reportID"      value="<%=reportID%>">
            <INPUT type="hidden" name="rptReportID"   value="<%=rptReportID%>">
            <INPUT type="hidden" name="userID"        value="">
            <INPUT type="hidden" name="reportType"    value="<%=reportType%>">
            <input type="hidden" name="callbackFunc"  value="<%=callbackFunc%>">
        </FORM>

        <table>
<!--            <tr>
                <td>
                    <table width="100%" height="29" border="0" cellpadding="0" cellspacing="0" bgcolor="728ab5">
                        <tr>
                            <td class="kecttep_title" style="padding-left:15px"><font color="#FFFFFF"><strong>담당변경</strong></font></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <table width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top:10px">-->
            <tr>
                <td>
                    <!--타이틀 //-->
                    <div class="title">
                    	<div>담당변경</div>
                    </div>
                    <!--타이틀 //-->

                    <table>
                        <%if (sysAuth == Moumi.TOTPER  && 1==2) {  //2014.09.12 Update by KWON,HAN : && 1==2 추가하여 사용안함 %>
                        <jsp:include page="/totsys/common/inc/title/title.jsp" flush="true">
                            <jsp:param name="title" value='<%=URLEncoder.encode("담당자변경")%>' />
                            <jsp:param name="flag"	value='99' />
                        </jsp:include>
                        <%}%>
                        <tr>
<!--                            <td align="center" valign="top">
                                <div>
                                    <iframe id="leftFrame" src="/totsys/common/web/report_dept/iframe/newTree2.jsp?rootID=<%= deptID%>&userYN=<%= userYN%>" width="550" height="500" frameborder="1"></iframe>
                                </div>-->
                            <td>
                                <table>
                                    <tr>
                                        <td>
                                            <div>
                                                <iframe id="leftFrame" src="/totsys/common/web/report_dept/iframe/newTree2.jsp?rootID=<%= deptID%>&userYN=<%= userYN%>" style="margin: 10px 0 0 0; border: 1px solid #728ab5;" width="554" height="530"></iframe>
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                                <div class="mt_5">
                                    <table>
				                        <tr>
				                            <td> 검 색 &nbsp;</td>
				                            <td style="text-align: left;">
                                                <span style="width: 70px;">
                                                    <select id="findOption" name="findOption" class="inputtxt" onchange="$('#search').val('');
                                                        showMSG(this.options[this.selectedIndex].value, msg)">
                                                        <option value="user" selected><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.user")%></option>
                                                        <option value="dept"><%=Moumi.getMessageBundle().getString("moumi.message.doc.Devision")%><%=Moumi.getMessageBundle().getString("moumi.message.doc.Name")%></option>
                                                    </select>
                                                </span>
                                            </td>
				                            <td><input id="search" name="search" type="text" class="inputtxt" value="" size="35" onkeyDown="if(event.keyCode === 13) { searchWord(); }" style="ime-mode:active;">&nbsp;</td>
				                            <td><a href="#" onclick="searchWord();"><img alt="찾기" src="/totsys/common/images/bt_search_inquiry2.gif"></a>&nbsp;</td>
				                            <td><a href="#" onclick="focusMove('down');"><img alt="다음" src="/totsys/common/images/bt_down.jpg"></a>&nbsp;</td>
				                            <td><a href="#" onclick="focusMove('up');"><img alt="이전" src="/totsys/common/images/bt_up.jpg"></a></td>
				                            <td></td>
				                        </tr>
				                    </table>
                                    <!-- 확인, 취소 버튼 -->
					                <div class="center mt_10" style="border-top: 1px solid #8ea6d6">
					                    <div class="mt_15">
					                        <a href="#" onclick="javascript:onOk();"><img alt="확인" src="/totsys/common/images/bt_ok.gif"></a>
					                        <a href="#" onClick="javascript:window.close();"><img class="ml_5" alt="취소" src="/totsys/common/images/bt_cancle.gif"></a>
					                    </div>
					                </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </body>
</html>
<%
        } else {
            String userID = MString.checkNull(request.getParameter("userID"));  //to user

            tx.begin();

            //집계자료
            if( "D".equals(docReportType) || "A".equals(docReportType) ) {
                TotDocService docService = new TotDocService(pm);

                if("form".equals(exeFlag)) {  //single
                    if(!"".equals(docID) && !"null".equals(docID)) {
                        docService.procChangeOwnerForDoc(docID, usID, userID);
                    }
                } else if("list".equals(exeFlag)) {  //multi
                     if( !"".equals(rptDocID) && !"null".equals(rptDocID)) {
                        docService.procChangeOwnerForDoc(rptDocID.split(","), usID, userID);
                    }
                }
            }
            //제출자료
            if( "R".equals(docReportType) || "A".equals(docReportType) ) {
                TotReportService reportService = new TotReportService(pm);

                if("form".equals(exeFlag)) {  //single
                    if(!"".equals(docID) && !"null".equals(docID)) {
                        reportService.procChangeOwnerForReport(reportID, usID, userID);
                    }
                } else if("list".equals(exeFlag)) {  //multi
                    if( !"".equals(rptReportID) && !"null".equals(rptReportID) )  {
                        reportService.procChangeOwnerForReport(rptReportID.split(","), usID, userID);
                    }
                }
            }

            //1. 자료이관 후 최종적으로 남은 건수를 확인한다.
            //2. 사용자정보의 인사이동 후  이관 여부를 재설정한다.
            int tmpCount = 1;
            String tmpError = "N";

            if("A".equals(docReportType)) {
                String dpID = dtID;
                String findOption = "";
                String findWord = "";
                String docType = "ALL";
                String exeType = "A";
                int count = 0;

                //1. 자료이관 후 최종적으로 남은 건수를 확인한다.
                Map params = new HashMap();
                params.put("userId",        usID);
                params.put("deptId",        dpID);
                params.put("findOption",    findOption);
                params.put("filterValue",   findWord);

                TotDocReportService docReport = new TotDocReportService(pm);

                //검색메인쿼리와 레코드갯수조회쿼리를 생성 후 멤버변수로 저장
                docReport.createDocReportListSearchQuery(params, docType, exeType);

                List<TotDocReportVO> list = null;

                //만족하는 레코드가 존재하면 조회
                list = docReport.executeQuery(TotDocReportVO.class);

                count = list.size();

                //2. 사용자정보의 인사이동 후  이관 여부를 재설정한다.
                if(count <= 0) {
                    MultiCheck mc = new MultiCheck();
                    tmpCount = mc.updateModYnOfMuser(usID, "N");
                }
            }

            if(tmpCount != 1) {
%>
            <script>
                //인사이동 후 이관여부를 변경하는 도중에 오류가 발생하였습니다.\\n\\n 관리자에게 문의 하십시오.
                alert("<%= MoumiConfig.getMessageBundle().getString("moumi.message.popup.errorModYnAdmin")%>");
            </script>
<%
                tmpError = "Y";
                tx.rollback();
            } else {
                tx.commit();
            }

            String funcName = Util.getFuncNameFromSignature(callbackFunc);
%>
<html>
    <head>
        <script>
    /*
    * 윈도우 로딩 후 호출되는 함수
    * @returns {undefined}
    */
    function fn_onLoad() {
        var tmpError = "<%=tmpError%>";   //인사이동 후 이관여부 변경시에 에러 여부
        if(tmpError == 'N') {
             alert("<%= MoumiConfig.getMessageBundle().getString("moumi.message.popup.chargeTrans")%>");
        }

        <% if( !callbackFunc.equals("") ) {%>
        if( typeof(opener.<%= funcName %>) != "undefined" ) {
            opener.<%= callbackFunc %>;
        }else if( typeof(parent.opener.<%= funcName %>) != "undefined" ) {
            parent.opener.<%= callbackFunc %>;
        }
        <%}%>
        self.close();
    }

    window.onload = fn_onLoad;
        </script>
    </head>
</html>
<%
        } //procMode

    } catch (Exception ex) {
        ex.printStackTrace();
        out.println(kr.co.kihyun.text.html.ServletUtil.getJavaScript("location='/servlet/kr.co.kihyun.beans.user.HttpSSOLogin?mode=logout';"));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
%>
