<%@ page contentType="text/html; charset=UTF-8"
        import="java.util.List"
        import="javax.jdo.PersistenceManager"
        import="javax.jdo.Transaction"
        import="kr.co.kihyun.beans.user.HttpSSOLogin"
        import="kr.co.kihyun.lang.MString"
        import="kr.co.kihyun.lang.Encoder"
        import="kr.co.kihyun.lang.MLong"
        import="kr.co.kihyun.moumi.Moumi"
        import="kr.co.kihyun.beans.entity.util.*"
        import="kr.co.kihyun.service.ShareDocService"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%
    /********** session내의 userId **********/
    String dpID = HttpSSOLogin.getDeptID(request);

//    Long docID = MLong.parseLong(request.getParameter("docID"), null);
    String docID = MString.checkNull(request.getParameter("docID"));
    String docReportType = MString.checkNull(request.getParameter("docReportType"));  //문서 구분(D:집계문서, R:제출문서)
    String userYN = MString.checkNull(request.getParameter("userYN"));
    String selfDeptYn = MString.checkNull(request.getParameter("selfDeptYn"));
    String exeFlag = MString.checkNull(request.getParameter("exeFlag"));
    String deptID = "";
    if("Y".equals(selfDeptYn)) { deptID = dpID; }
    int totCount = 0;

    //System.out.println("popup_user_multi_select.jsp ===========================");
    //System.out.println("docID = " + docID);
    //System.out.println("docReportType = " + docReportType);
    //System.out.println("deptID = " + deptID);
    //System.out.println("userYN = " + userYN);
    //System.out.println("selfDeptYn = " + selfDeptYn);
    //System.out.println("=======================================================");

    String gIds = "";
    String gTypes = "";
    String gNames = "";
    String gDeptNames = "";

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

        String[] docIDList = docID.split(",");

        //싱글인 경우에만 조회한다.
        if(docIDList.length == 1) {

            ShareDocService shareDoc = new ShareDocService(pm);
            List tmpList = shareDoc.getSearchDocIdType('N', docID, docReportType);

            for (int ii = 0; ii < tmpList.size(); ii++) {
                Object[] objData = (Object[]) tmpList.get(ii);
                //System.out.println("popup_user_multi_select.jsp=====");
                //System.out.println("ID = " + objData[0]);
                //System.out.println("USER_ID = " + objData[1]);
                //System.out.println("USER_NAME = " + objData[2]);
                //System.out.println("DPET_ID = " + objData[3]);
                //System.out.println("DPET_NAME = " + objData[4]);
                //System.out.println("================================");

                if (ii == 0) {
                    gIds = objData[1].toString();
                    gTypes = "user";
                    gNames = objData[2].toString();
                    gDeptNames = objData[4].toString();
                } else {
                    gIds = gIds + "," + objData[1].toString();
                    gTypes = gTypes + "," + "user";
                    gNames = gNames + "," + objData[2].toString();
                    gDeptNames = gDeptNames + "," + objData[4].toString();
                }

                totCount = totCount + 1;
            }
        }

        tx.rollback();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
%>

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" href="/totsys/common/css/popup.css" type="text/css">
		<link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
		<link rel="stylesheet" href="/totsys/common/css/kecttep.css" type="text/css">
		<title><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.user")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.share")%>&nbsp;<%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.select")%></title>
        <script src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script src="/totsys/common/js/jquery.cookie.js"></script>
		<script src="/totsys/common/js/jquery.hotkeys.js"></script>
		<script src="/totsys/common/js/jquery.jstree.js"></script>
        <script>
            var selid = '';     // 조직도에서 선택한 id(부서, 사용자)
            var seltype = '';
            var selname = '';
            var seldeptname = '';
            var idList = '';     // 선택되어진 부서 리스트
            var typeList = '';
            var nameList = '';
            var deptNameList = '';

            //공유된 사용자 추가
            function setShareUsers() {
                document.list.idList.value = idList = "<%=gIds%>";
                document.list.typeList.value = typeList = "<%=gTypes%>";
                document.list.nameList.value = nameList = "<%=gNames%>";
                document.list.deptNameList.value = deptNameList = "<%=gDeptNames%>";

                idList = idList + "";
                typeList = typeList + "";
                nameList = nameList + "";
                deptNameList = deptNameList + "";

                if (idList != "") {
                    document.list.submit();
                }

                /* @@@ test

                 document.getElementById('search').value = "강원도교육청";

                */
            }

            //추가 버튼 : newTreeUserShare,jsp 에서 aJax의 함수를 호출한다.
            function getUserId() {
                var $ff = $("#leftFrame");
                $ff[0].contentWindow.$("#checkbtn").click();
            }

            //newTreeUserShare.jsp 에서 호출 : 오른쪽의 사용자 리스트에 표시된다.
            function putSelId(sid, sName, sDeptName) {
                selid = sid;
                seltype = "user";
                selname = sName;
                seldeptname = sDeptName;

                var id = selid;
                var type = seltype;
                var name = selname;
                var deptname = seldeptname;

                if (idList == '') {
                    document.list.idList.value = idList = id;
                    document.list.typeList.value = typeList = type;
                    document.list.nameList.value = nameList = name;
                    document.list.deptNameList.value = deptNameList = deptname;
                    idList = idList + "";
                    typeList = typeList + "";
                    nameList = nameList + "";
                    deptNameList = deptNameList + "";
                } else {
                    var isAdd = listAdd(idList, id, typeList, type, nameList, deptNameList);
                    document.list.idList.value = idList;
                    document.list.typeList.value = typeList;
                    if (isAdd) {
                        listAddn(nameList, name);
                        listAddDept(deptNameList, deptname);
                    }
                    document.list.nameList.value = nameList;
                    document.list.deptNameList.value = deptNameList;
                }
            }

            //사용자의 아이디와 타입(user)을 더한다.
            function listAdd(idList1, idList2, tList, tItem, nameList1, deptNameList1) {
                var arrayID1 = idList1.split(",");
                var arrayType = tList.split(",");
                var arrayName = nameList1.split(",");
                var arrayDeptName = deptNameList1.split(",");

                var isEquals = true;

                if (idList1 == '') {
                    idList = idList1;
                    typeList = tList;
                    return false;
                }
                for (var i = 0; i < arrayID1.length; i++) {
                    if (idList2 == arrayID1[i] && tItem == arrayType[i]) {
                        //동일 ID가 존재합니다.\\n\\n다시 시도해 주세요.
                        alert(arrayDeptName[i] + " / " + arrayName[i] + "(" + arrayID1[i] + ")의 " + "<%=Moumi.getMessageBundle().getString("moumi.message.popup.sameID")%>"+"\n\n선택하신 사용자를 확인하여 주십시오")
                        isEquals = false;
                        break;
                    }
                }
                if (isEquals) {
                    idList1 += "," + idList2;
                    tList += "," + tItem;
                }
                idList = idList1;
                typeList = tList;
                return isEquals;
            }

            //사용자명을 더한다.
            function listAddn(nameList1, nameList2) {
                //var arrayName1 = nameList1.split(",");

                if (nameList1 == '') {
                    nameList = nameList1;
                    return;
                }

                nameList1 += "," + nameList2;
                nameList = nameList1;
                return;
            }

            //부서명을 더한다.
            function listAddDept(deptNameList1, dpetNameList2) {
                //var arrayName1 = deptNameList1.split(",");

                if (deptNameList1 == '') {
                    deptNameList = deptNameList1;
                    return;
                }

                deptNameList1 += "," + dpetNameList2;
                deptNameList = deptNameList1;
                return;
            }

            //선택된 사용자 리스트에서 삭제한다
            function userDelete() {
                if (idList != '') {
                    userShareFrame.movelist();
                    document.list.submit();
                }
            }

            //선택된 사용자 리스트 아이프레임 안에 있는 movelist() 함수에서 호출된다
            function leftFrameDel(name, id, type, deptname) {
                id = lastStrDel(id, ",");
                type = lastStrDel(type, ",");
                name = lastStrDel(name, ",");
                deptname = lastStrDel(deptname, ",");

                if (idList == '' && nameList == '') {
                    document.list.idList.value = idList = id;
                    document.list.typeList.value = typeList = type;
                    document.list.nameList.value = nameList = name;
                    document.list.deptNameList.value = deptNameList = deptname;
                } else {
                    delList(id, name, type, deptname);
                    document.list.idList.value = idList;
                    document.list.typeList.value = typeList;
                    document.list.nameList.value = nameList;
                    document.list.deptNameList.value = deptNameList;
                }
                document.list.submit();
            }

            function lastStrDel(str, delStr) {
                var lastStr = str.lastIndexOf(delStr);
                return str.substring(0, lastStr);
            }

            function delList(idList1, naList1, tyList1, dnList1) {
                idList = idList1;
                typeList = tyList1;
                nameList = naList1;
                deptNameList = dnList1;
            }

            //검색버튼
            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 btnConfirm() {
                if (<%=totCount%>==0 && document.list.idList.value == "") {
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.selectUser")%>');        //사용자를 선택하세요!
                    return false;

                } else {
                    //전체 삭제를 한 경우에 확인메세지를 띄운다.
                    if (document.list.idList.value == "") {
                        //정말로 삭제 하시겠습니까?
                        if (!confirm('<%=Moumi.getMessageBundle().getString("moumi.message.popup.deletion")%>')) {
                            return false;
                        }
                    }

                    document.userShareSet.userIDs.value = document.list.idList.value;
                    document.userShareSet.types.value = document.list.typeList.value;

                    //폼에서 호출된 경우에만
                    if ("<%=exeFlag%>"=="form") {
                        var userShareTemp = '';
                        var userShareCount = 0;
                        if (document.list.idList.value != null && document.list.idList.value != "") {
                            userShareTemp = document.list.idList.value.split(",");
                        }

                        if (userShareTemp != null && userShareTemp != '') {
                            userShareCount = userShareTemp.length;
                        }

                        if(userShareCount <= 0) {
                            opener.document.getElementById("userShareCountText").innerHTML = '';
                        } else {
                            opener.document.getElementById("userShareCountText").innerHTML = userShareCount + '<%=Moumi.getMessageBundle().getString("moumi.message.popup.userShareCounter")%>';
                        }
                    }

                    //DB에 저장된다.
                    document.userShareSet.submit();
                }
            }

            //취소 버튼
            function btnCancel() {
                window.close();
            }
        </script>

        
    </head>

    <body onload="setShareUsers();">

        <!-- 오른쪽의 사용자 리스트에 표시된다. -->
        <form name="list" method="post"	action="/servlet/kr.co.kihyun.beans.user.HttpUserShareList" target="userShareFrame">
            <input type="hidden" name="idList">
            <input type="hidden" name="typeList">
            <input type="hidden" name="nameList">
            <input type="hidden" name="deptNameList">
        </form>
        <!-- 확인 버튼 클릭하면 DB에 저장된다 -->
        <form name="userShareSet" method="post" action="/servlet/kr.co.kihyun.beans.totsys.doc.HttpShareDocSet" target="_self">
            <input type="hidden" name="docID"    value="<%=docID%>">
            <input type="hidden" name="docReportType" value="<%=docReportType%>">
            <input type="hidden" name="userIDs">
            <input type="hidden" name="types">
            <input type="hidden" name="exeFlag"      value="<%=exeFlag%>">
            <input type="hidden" name="callbackFunc" value="fn_reload()">
        </form>

        <!--타이틀 //-->
        <div class="title">
        	<div><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.user")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.share")%>&nbsp;<%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.select")%></div>
        </div>
        <!--타이틀 //-->
        
        <table>
            <!-- 조직도/../사용자 -->
            <tr>
                <td colspan="3">
                    <table style="padding-top:10px; padding-bottom:10px; width: 100%; height: 26px;">
                        <tr>
                            <td style="width: 300px;" ><img alt="글머리" src="/totsys/common/images/ico_3.gif">&nbsp;<b><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.deptMap")%></b></td>
                            <td></td>
                            <td style="width: 470px; text-align: left;"><img src="/totsys/common/images/ico_3.gif">&nbsp;<b><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.user")%></b></td>
                        </tr>
                    </table>
                </td>
            </tr>

            <!-- 분류, 사용자 선택/추가,삭제 버튼/선택된 사용자 리스트 -->
            <tr>
                <!-- 사용자 선택 아이프레임 -->
                <td style="width: 300px;">
                    <table>
                        <tr>
                            <td>
                                <iframe id="leftFrame" name="leftFrame" src="./iframe/newTreeUserShare.jsp?rootID=<%=deptID%>&userYN=<%=userYN%>&selfDeptYn=<%=selfDeptYn%>" width="300" height="425" frameborder="0" style="border: 1px solid #728ab5;"></iframe>                            </td>
                        </tr>
                    </table>
                </td>

                <!-- 추가,삭제 버튼 아이프레임 -->
                <td style="text-align: center; width: 100px;">
                    <table>
                        <!--추가-->
                        <tr>
                            <td style="padding-left: 10px; padding-right: 10px; height: 35px;"><a href="javascript:getUserId();"><img alt="추가" src="./images/new_dept_add.gif"></a></td>
                        </tr>
                        <!--삭제-->
                        <tr>
                            <td style="padding-left: 10px; padding-right: 10px; height: 35px;"><a href="javascript:userDelete();"><img alt="삭제" src="./images/new_dept_del.gif"></a></td>
                        </tr>
                    </table>
                </td>

                <!-- 선택된 사용자 리스트 아이프레임 -->
                <td style="padding-top: 1px; width: 470px;">
                    <table>
                        <tr>
                            <td><iframe name="userShareFrame" src="./iframe/selected_list.jsp" width="470" height="425" frameborder="0" style="border: 1px solid #728ab5;"></iframe></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        <!-- 검색 / 조회 버튼 -->        
        <div class="mt_10">
	        <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 style="padding-left: 5px;"><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 style="padding-left: 10px;">[모든 설정은 확인을 실행해야 적용됩니다]</td>
		        </tr>
		    </table>
	    </div>
        
        <!-- 확인, 취소 버튼 -->
        <div class="center mt_15" style="border-top: 1px solid #8ea6d6">
            <div class="mt_15">
                <a href="#" onclick="btnConfirm();"><img alt="확인" src="/totsys/common/images/bt_ok.gif"></a>
                <a href="#" onClick="btnCancel();"><img class="ml_5" alt="취소" src="/totsys/common/images/bt_cancle.gif"></a>
                
            </div>
        </div>
    </BODY>
</HTML>
