<%
    /*
     * ***********************************************************
     * @@ Program Name	: edit_dept_list2.jsp
     * @@ Description	: 제출기관지정
     * @@ Author	:
     * @@ Create Date	:
     * @@ History       : 2014.09.18 Update by KWON,HAN
     * **********************************************************
     */
%>

<%@ page contentType="text/html; charset=UTF-8"
         import="kr.co.kihyun.lang.MString"
         import="java.net.URLDecoder"
         import="kr.co.kihyun.lang.Encoder"
         import="kr.co.kihyun.lang.MLong"
         import="kr.co.kihyun.moumi.Moumi"
         import="kr.co.kihyun.beans.totsys.report.ReportList"
         import="kr.co.kihyun.beans.user.Dept"
         import="kr.co.kihyun.beans.user.User"
         import="kr.co.kihyun.moumi.report.MReport"%>
<%@page import="kr.co.kihyun.beans.entity.Repoadm"%>
<%@page import="javax.jdo.PersistenceManager"%>
<%@page import="javax.jdo.Transaction"%>
<%@page import="kr.co.kihyun.beans.entity.util.*"%>
<%@page import="kr.co.kihyun.beans.entity.TotReport"%>

<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%    Long docID = MLong.parseLong(request.getParameter("docID"), null);
    Long reportID = MLong.parseLong(request.getParameter("reportID"), null);
    String usedType = MString.checkNull(request.getParameter("usedType"));
    String totCount = clearXSS(Encoder.toJava(MString.checkNull(request.getParameter("totCount"))), "");

    System.out.println("usedType :::: " +usedType);
    int deptCount = 0;
    String deptIDs = "";
    String deptNames = "";
    String deptTypes = "";
    Integer[] docTypeList = null;
    String[] deptIDList = null;
    String[] userIDList = null;
    String[] deptNameList = null;
    String[] organNameList = null;
    String[] upperNameList = null;
    String sAutoExpanded = "N";

    if (!"RECOG".equals(usedType)) {
        ReportList reportList = new ReportList();
        //v2. 13.SQL 삽입 : JDO형식이므로 해결책에 따른 prepare SQL 문으로 변경할 수 없음
        reportList.executeQuery(docID, MReport.ALL);
        //=================
        deptCount = reportList.getCount();

        User user = new User();

        if (deptCount > 0) {
            deptIDList = new String[deptCount];
            deptNameList = new String[deptCount];
            organNameList = new String[deptCount];
            upperNameList = new String[deptCount];

            deptIDList = reportList.getDeptIDList();
            userIDList = reportList.getUserIDList();
            deptNameList = reportList.getDeptNameList();
            organNameList = reportList.getOrganNameOfUpperDept();
            upperNameList = reportList.getUpperNameList();

            docTypeList = reportList.getDocTypeList();

            if (docTypeList[0] == 1) {
                deptIDs = userIDList[0] + "/" + deptIDList[0];
                deptNames = user.getName(userIDList[0]);
                deptTypes = "user";
            } else {
                deptIDs = deptIDList[0];
              //deptNames = deptNameList[0];
//                Dept dept = new Dept();
//                deptNames = dept.getOrganNameOfUpperDept(deptIDList[0]) + "|" + dept.getUpperDeptName(deptIDList[0]) + "|" + dept.getName(deptIDList[0]);
                deptNames =  organNameList[0] + "|" + MString.checkNull(upperNameList[0]) + "|" + deptNameList[0];
                deptTypes = "dept";
            }

            for (int d = 1; d < deptCount; d++) {
                if (docTypeList[d] == 1) {
                    deptIDs = deptIDs + "," + userIDList[d] + "/" + deptIDList[d];
                    deptNames = deptNames + "," + user.getName(userIDList[d]);
                    deptTypes = deptTypes + "," + "user";
                } else {
                    deptIDs = deptIDs + "," + deptIDList[d];
                  //deptNames = deptNames + "," + deptNameList[d];
//                    Dept dept = new Dept();
//                    deptNames = deptNames + "," + dept.getOrganNameOfUpperDept(deptIDList[d]) + "|" + dept.getUpperDeptName(deptIDList[d]) + "|" + dept.getName(deptIDList[d]);
                    deptNames =  deptNames + "," + organNameList[d] + "|" + MString.checkNull(upperNameList[d]) + "|" + deptNameList[d];
                    deptTypes = deptTypes + "," + "dept";
                }
            }
        }
    } else{
        System.out.println("수신처를 추가 할 수 없습니다.");
    }
//    else {
//        PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
//        Transaction tx = pm.currentTransaction();
//        TotReport totReport = null;
//        try {
//            tx.begin();
//
//            totReport = (TotReport) pm.getObjectById(TotReport.class, reportID);
//            for (int i = 0; i < totReport.getRepoadms().size(); i++) {
//                if (i == 0) {
//                    deptIDs = totReport.getRepoadms().get(i).getRecogUser(pm).getId() + "/" + totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getId();
//                  //deptNames = totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getName() + "-" + totReport.getRepoadms().get(i).getRecogUser(pm).getName();
//                    deptNames = totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getName() + "|" + totReport.getRepoadms().get(i).getRecogUser(pm).getName();
//                    deptTypes = "user";
//                } else {
//                    deptIDs = deptIDs + "," + totReport.getRepoadms().get(i).getRecogUser(pm).getId() + "/" + totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getId();
//                  //deptNames = deptNames + "," + totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getName() + "-" + totReport.getRepoadms().get(i).getRecogUser(pm).getName();
//                    deptNames = deptNames + "," + totReport.getRepoadms().get(i).getRecogUser(pm).getUpperDept(pm).getName() + "|" + totReport.getRepoadms().get(i).getRecogUser(pm).getName();
//                    deptTypes = deptTypes + "," + "user";
//                }
//            }
//
//            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">
        <title>제출부서 선택</title>
        <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>
        <script type="text/javascript" src="/totsys/common/js/jquery.custom.indicator.js"></script>
        
        <link rel="stylesheet" href="/totsys/common/css/kecttep.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/org_search.js"></script>
        <script>
            var delstate = false;
            var userGroup = false; // 사용자정의 그룹인지 여부지정 변수

            var selid = ''; // 지금 선택한 부서
            var selname = '';
            var seltype = '';
            var idList = ''; // 선택되어진 부서 리스트
            var nameList = '';
            var typeList = '';

            // 부서 추가
            function setDepts() {
                document.list.idList.value = idList = "<%=deptIDs%>";
                document.list.typeList.value = typeList = "<%=deptTypes%>";
                document.list.nameList.value = nameList = "<%=deptNames%>";

                idList = idList + "";
                typeList = typeList + "";
                nameList = nameList + "";
                if (idList != "")
                    document.list.submit();
            }


            //추가 버튼
            function getDeptId() {
                var $ff = $("#leftFrame");
                $ff[0].contentWindow.$("#checkbtn").click();
            }

            function putSelId(id) {
                selid = id;
                deptConfirm2();
            }

            function putSelId2(sId, sDeptName, sOrganDeptName, sUpperDeptName) {
                //alert("id = " + sId + ", deptName = " + sDeptName + ", OrganDeptName = " + sOrganDeptName + ", UpperDeptName = " + sUpperDeptName)

                selid = sId;
                //selname = sOrganDeptName;
                //if(!sOrganDeptName.equals(sUpperDeptName)) {
                //    selname = selname + "-" + sUpperDeptName;
                //}
                //selname = selname + "-" + sDeptName;
                selname = sOrganDeptName + "|" + sUpperDeptName + "|" + sDeptName;
                deptConfirm2();
            }

            function deptConfirm() {
                if (selid == '') {
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.deptConfirm")%>');
                } else if (seltype == "group") {
                    modSelect();
                } else {
                    id = selid;
                    name = selname;
                    type = seltype;

                    if (idList == '') {
            <%if ("RECOG".equals(usedType)) {%>
                        if (type == "user") {
            <%}%>
                            document.list.idList.value = idList = id;
                            document.list.nameList.value = nameList = name;
                            document.list.typeList.value = typeList = type;
                            idList = idList + "";
                            nameList = nameList + "";
                            typeList = typeList + "";
            <%if ("RECOG".equals(usedType)) {%>
                        }
            <%}%>
                    } else {
            <%if ("RECOG".equals(usedType)) {%>
                        if (type == "user") {
            <%}%>
                            var isAdd = listAdd(idList, id, typeList, type);
                            document.list.idList.value = idList;
                            document.list.typeList.value = typeList;
                            if (isAdd) {
                                listAddn(nameList, name);
                            }
                            document.list.nameList.value = nameList;
            <%if ("RECOG".equals(usedType)) {%>
                        }
            <%}%>
                    }
                    document.list.submit();
                }
            }

            // 부서 추가
            function deptConfirm2() {
                if (selid == '') {
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.deptConfirm")%>');
                } else if (seltype == "group") {
                    modSelect();
                } else {
                    var id = selid;
                    var type = 'dept';
                    var name = selname;

                    if (idList == '') {
            <%if ("RECOG".equals(usedType)) {%>
                        if (type == "user") {
            <%}%>
                            document.list.idList.value = idList = id;
                            document.list.typeList.value = typeList = type;
                            document.list.nameList.value = nameList = name;
                            idList = idList + "";
                            typeList = typeList + "";
                            nameList = nameList + "";
            <%if ("RECOG".equals(usedType)) {%>
                        }
            <%}%>
                    } else {
            <%if ("RECOG".equals(usedType)) {%>
                        if (type == "user") {
            <%}%>
                            var isAdd = listAdd(idList, id, typeList, type);
                            document.list.idList.value = idList;
                            document.list.typeList.value = typeList;
                            if (isAdd) {
                                listAddn(nameList, name);
                            }
                            document.list.nameList.value = nameList;
            <%if ("RECOG".equals(usedType)) {%>
                        }
            <%}%>
                    }
                    //document.list.submit();
                }
            }

            function openerdeptConfirm() { //구성원으로 추가
                var gid = document.list.openeridList.value;
                var gname = document.list.openernameList.value;
                var gtype = document.list.openertypeList.value;

                var arrayID = gid.split(",");
                var arrayName = gname.split(",");
                var arrayType = gtype.split(",");

                var isChange = false;

                for (var i = 0; i < arrayID.length; i++) {
                    selid = arrayID[i];
                    selname = arrayName[i];
                    seltype = arrayType[i];

                    if (selid == '') {
                        alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.deptConfirm")%>');
                    } else {
                        id = selid;
                        name = selname;
                        type = seltype;

                        if (idList == '') {
                            document.list.idList.value = idList = id;
                            document.list.nameList.value = nameList = name;
                            document.list.typeList.value = typeList = type;

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

                        isChange = true;
                    }
                }

                if (isChange) {
                    document.list.submit();
                }
            }

            function modSelect() {
                var height = screen.height;
                var width = screen.width;
                var leftpos = width / 2 - 235;
                var toppos = height / 2 - 235;

                if (seltype != "group") {
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.groupSelect")%>');
                    return;
                }

                var urlname = "/totsys/common/web/report_dept/modifier.jsp?groupID=" + selid;
                post2 = window.open(urlname, "post2", "width=450, height=435, toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,left=" + leftpos + ",top=" + toppos);
                post2.focus();
            }


            function listAdd(idList1, idList2, tList, tItem) {
                var arrayID1 = idList1.split(",");
                var arrayType = tList.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]) {
                        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 deptDelete() {
                if (idList != '') {
                    deptFrame.movelist();
                    document.list.submit();
                }
            }

            function leftFrameDel(name, id, type) {
                name = lastStrDel(name, ",");
                id = lastStrDel(id, ",");
                type = lastStrDel(type, ",");
                if (nameList == '' && idList == '') {
                    document.list.idList.value = idList = id;
                    document.list.typeList.value = typeList = type;
                    document.list.nameList.value = nameList = name;
                } else {
                    delList(id, type, name);
                    document.list.idList.value = idList;
                    document.list.typeList.value = typeList;
                    document.list.nameList.value = nameList;
                }

                document.list.submit();
                return;
            }

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

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

            // 부서 선택 시 유저 뽑아내기.
            function userList(id, name, type) {
                if (type != '') {
                    idAll = id;
                    selid = id;
                    selname = name;
                } else {
                    idAll = '';
                    selid = '';
                    selname = '';
                }
                seltype = type;
                idUpper = false;
                userGroup = false;
                /*
                 document.userlist.id.value = id;
                 document.userlist.target="rightFrame";
                 document.userlist.selectType.value="right";
                 document.userlist.didList.value = idList;

                 document.userlist.submit();
                 */
            }

            function groupList(id, name, type) {
                idAll = id;
                selid = id;
                selname = name;
                seltype = type;
                idUpper = false;
                userGroup = false;
                /*
                 document.userlist.id.value = id;
                 document.userlist.target="rightFrame";
                 document.userlist.selectType.value="right";
                 document.userlist.didList.value = idList;

                 document.userlist.submit();
                 */
            }

            function searchWord() {
                var word = $('#search').val();
                word = $.trim(word);
                $('#search').val(word);
                if (word.length < 2) {
                    alert("검색어는 2글자 이상이어야 합니다.");
                    return;
                }
                var $ff = $("#leftFrame");
                $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 deptComp() {
                if (document.list.idList.value == "") {
            <%if ("RECOG".equals(usedType)) {%>
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.approvalSelect")%>');  //승인자를 선택 해주세요. 승인받지 않고 제출하시려면 제출완료를 눌러주세요
            <%} else {%>
                    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.deptComp")%>');        //제출요청 부서를 추가 해 주세요
            <%}%>
                    return;
                } else {
                        $.customIndicator.show(window.self);  /* indicator 추가 */
                    document.deptSet.deptIDs.value = document.list.idList.value;
                    document.deptSet.types.value = document.list.typeList.value;

                    var deptTemp = document.list.idList.value.split(",");
                    var deptCounter = deptTemp.length;

                    if(deptCounter <= 0) {
                        opener.dform.deptCountText.value = '<%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.submitDevision")%>';           //제출기관을 선택해주세요.
                    } else {
                    opener.dform.deptCountText.value = deptCounter + '<%=Moumi.getMessageBundle().getString("moumi.message.popup.deptCounter")%>';  //개의 부서를 선택하였습니다.
                    }
                    opener.dform.deptChange.value = "1";

                    deptSet.submit();
                }
            }

            //취소 버튼
            function deptCancel() {
                window.close();
            }

        </script>
    </HEAD>

    <BODY <%if (totCount == null || totCount.equals("")) {%> onload="setDepts();" <%}%>>
        <form name="deptSet" method="post" action="/servlet/kr.co.kihyun.beans.totsys.doc.HttpDeptSetMerge" target="_self">
            <input type="hidden" name="docID" value="<%=docID%>">
            <input type="hidden" name="reportID" value="<%=reportID%>">
            <input type="hidden" name="usedType" value="<%=usedType%>">
            <input type="hidden" name="deptIDs">
            <input type="hidden" name="types">
        </form>
        <form name="list" method="post"	action="/servlet/kr.co.kihyun.beans.user.HttpDeptList" target="deptFrame">
            <input type="hidden" name="idList">
            <input type="hidden" name="nameList">
            <input type="hidden" name="typeList">
            <input type="hidden" name="openeridList">
            <input type="hidden" name="openernameList">
            <input type="hidden" name="openertypeList">
        </form>

        <!--타이틀 //-->
        <div class="title">
            <div>제출기관지정</div>
            </div>
        <!--타이틀 //-->
        <div class="disFlex lv1">
            <div class="deptListSide">
                <img alt="말머리" src="/totsys/common/images/ico_3.gif">
                <b><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.deptMap")%></b>
            </div>
            <div class="deptListCenter"></div>
            <div class="deptListSide"><img alt="말머리" src="/totsys/common/images/ico_3.gif"><b>제출기관(부서)<!--%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.submitDept")%--></b></div>
        </div>
        <%if (!"RECOG".equals(usedType)) {%>
        <div class="disFlex ml_5">
            <!-- 분류 선택 아이프레임 -->
            
            <iframe src="iframe/new_section_list3.html" width="300" height="21"></iframe>
        </div>
        <%}%>
        <div class="disFlex">
            <div class="deptListSide">
                <!-- 부서 선택 아이프레임 -->
                <%if (!"RECOG".equals(usedType)) {%>
                    <iframe id="leftFrame" name="leftFrame" src="./iframe/groupCommon.jsp" width="300" height="360" frameborder="0"></iframe>
                <%} else {%>
                    <iframe id="leftFrame" name="leftFrame" src="./iframe/newTree.jsp" width="300" height="360" frameborder="0"></iframe>
                <%}%>
            </div>
            <div class="deptListCenter center deptPt">
                <div>
                <!--추가-->
                <a href="javascript:getDeptId();"><img alt="추가" src="./images/new_dept_add.gif"/></a>
                </div>
                <div class="mt_5">
                    <!--삭제-->
                    <a href="javascript:deptDelete();"><img alt="삭제" src="./images/new_dept_del.gif"/></a>
                </div>
                <!--구성원-->
                <%if (!"RECOG".equals(usedType)) {%>
                <div>
                </div>
                <%}%>
                
            </div>
                <div class="deptListSide">
                <!-- 선택된 부서 리스트 아이프레임 -->
                <iframe name="deptFrame" src="./iframe/selected_list.jsp"></iframe>
                </div>
            </div>
            <table>
                <tr>
                    <td> 검 색 &nbsp;&nbsp;</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_10">
                        <a href="#" onclick="deptComp()"><img alt="확인" src="/totsys/common/images/bt_ok.gif"></a>
                        <a href="#" onClick="deptCancel()"><img alt="취소" src="/totsys/common/images/bt_cancle.gif"></a>
                    </div>
                </div>
    </body>
</HTML>
