<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
   response.setHeader("Pragma", "No-cache");
   response.setHeader("Cache-Control", "no-cache");
   response.setHeader("Expires", "0");
%>
<html>
<head>
   <title></title>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <jsp:include page="/jsp/common/include/css.jsp"/>
   <jsp:include page="/jsp/common/include/script.jsp"/>
   <script language="javascript" src="<c:url value="/js/jexcel.js"/>"></script>
   <script language="javascript" src="<c:url value="/js/jsuites.js"/>"></script>
   <script language="javascript" src="<c:url value="/js/jsuites.webcomponents.js"/>"></script>
   <link rel="stylesheet" type="text/css" media="screen" href="<c:url value="/css/jexcel.css"/>" ></link>
   <link rel="stylesheet" type="text/css" media="screen" href="<c:url value="/css/jsuites.css"/>" ></link>
   <style>
      .jexcel tbody {
         font-size: 13px;
      }
   </style>
   <script>

      var url      ='<c:url value="/common/acl/user/userRegistUtil.json" />';
      var url_view ='<c:url value="/common/acl/user/userRegistUtil.view" />';

      var grid;
      var columns;
      var columnNames;
      var dataType;
      var toolbarHtml;

      var customUpdateTable = function(instance, cell, col, row, val, label, cellName) {
         if(col == 0 && val != null && val != ''){
            //cell.style.backgroundColor = '#f46e42';
            cell.style.textAlign = 'left';
            var rowData = grid.getRowData(Number(row));
            if(rowData.length > 1){
               const itemLenIndex = columnNames.indexOf('LOUTITEMDEPTH');
               const depth = Number(rowData[itemLenIndex]);
               cell.style.textAlign = 'left';
               const padding = depth == 1 ? 5 : (depth*10);
            }
         }
      }

      //JEXCEL 관련 함수 시작
      function getCellValue(columnName, rowNum){
         const index = columnNames.indexOf(columnName);
         //var cell = grid.records[rowNum][index];
         //return cell.innerText;
         const cellId = String.fromCharCode(65+index) + rowNum;
         return grid.getValue(cellId)
      }
      function migCellValue(columnName, dataKey, dataArray, targetArray){
         const index = columnNames.indexOf(columnName);
         var value = dataArray[dataKey];
         if(columnName === 'LOUTITEMTYPE'){
            switch(value){
               case('GROUP'):
                  if(dataArray['LOUTITEMOCCURPTRNDSTCD'] == '*'){
                     value = 'Grid'; break;
                  }
                  value = 'Group'; break;
               default:
                  value = 'Field'; break;
            }
         }
         if(columnName === 'LOUTITEMOCCCNT'){
            if(dataArray['LOUTITEMNODEPTRNIDDESC'] != 'GROUP'
                  || dataArray['LOUTITEMOCCURPTRNDSTCD'] != '*'
                  || dataArray['LOUTITEMREFINFO2'].trim().length > 0
                  || value === -1 ){
               value = '';
            }
         }
         if(columnName === 'LOUTITEMDEPTH'){
            value = value - 1;
         }
         if(columnName === 'LOUTITEMDATATYPE'){
            switch(value){
               case('Integer'):
                  value = 'Int'; break;
            }
         }
         if(columnName === 'LOUTITEMMASK'){
            value = value == 'Y' ? 'true' : 'false';
         }

         targetArray[index] = value;
      }

      const beforePaste = function (instance, data){

         const selectedCell = grid.selectedCell;
         const obj = grid;


         var ax = Number(selectedCell[0]),
               ay = Number(selectedCell[1]),
               bx = Number(selectedCell[2]),
               by = Number(selectedCell[3]);

         // Paste filter
         var x = ax,
               y = ay,
               w = bx-x+1,
               h = by-y+1;

         // change paste range if select is from right to left
         if (bx < ax){
            x = bx;
            w = ax-x+1;
         }
         // change paste range if select is from down to up
         if (by < ay){
            y = by;
            h = ay-y+1;
         }

         // Controls
         var hash = obj.hash(data);
         var style = (hash == obj.hashString) ? obj.style : null;

         // Depending on the behavior
         if (obj.options.copyCompatibility == true && hash == obj.hashString) {
            var data = obj.data;
         }

         // Split new line
         var data = obj.parseCSV(data, "\t");

         //modify data to allow wor extending paste range in multiples of input range
         if (w>1 & Number.isInteger(w/data[0].length )){
            style = null;
            repeats = w/data[0].length;

            var arrayB = data.map(function(row,i){
               var arrayC = Array.apply(null, {length: repeats * row.length})
                     .map(function(e,i){return row[i % row.length]});
               return arrayC
            });
            data = arrayB;

         }
         if (h>1 & Number.isInteger(h/data.length )){
            style = null;
            var repeats = h/data.length;
            var arrayB = Array.apply(null, {length: repeats * data.length})
                  .map(function(e,i){return data[i % data.length]});
            data = arrayB;
         }

         if (x != null && y != null && data) {
            // Records
            var i = 0;
            var j = 0;
            var records = [];
            var newStyle = {};
            var oldStyle = {};
            var styleIndex = 0;

            // Index
            var colIndex = parseInt(x);
            var rowIndex = parseInt(y);
            var row = null;

            // Go through the columns to get the data
            while (row = data[j]) {
               i = 0;
               var colIndex = parseInt(x);

               while (row[i] != null) {
                  // Update and keep history
                  var record = obj.updateCell(colIndex, rowIndex, row[i]);
                  // Keep history
                  records.push(record);
                  // Style
                  if (style) {
                     var columnName = jexcel.getColumnNameFromId([colIndex, rowIndex]);
                     newStyle[columnName] = style[styleIndex];
                     oldStyle[columnName] = obj.getStyle(columnName);
                     obj.records[rowIndex][colIndex].setAttribute('style', style[styleIndex]);
                     styleIndex++
                  }
                  i++;
                  if (row[i] != null) {
                     if (colIndex >= obj.headers.length - 1) {
                        obj.insertColumn();
                     }
                     colIndex = obj.right.get(colIndex, rowIndex);
                  }
               }

               j++;
               if (data[j]) {
                  if (rowIndex >= obj.rows.length - 1) {
                     obj.insertRow();
                  }
                  var rowIndex = obj.down.get(x, rowIndex);
               }
            }

            // Select the new cells
            obj.updateSelectionFromCoords(x, y, colIndex, rowIndex);

            // Update history
            obj.setHistory({
               action: 'setValue',
               records: records,
               selection: obj.selectedCell,
               newStyle: newStyle,
               oldStyle: oldStyle,
            });

            // Update table
            obj.updateTable();
         }
         return false;
      };

      function moveSelectionRow(up){
         const selectedCell = grid.selectedCell;

         const correction = up ? -1 : 1 ;
         const selectionCorrection = up ? 0 : 2 ;

         if(selectedCell != null) {
            const x1 = Number(selectedCell[0]) ;
            const y1 = Number(selectedCell[1]) ;
            const x2 = Number(selectedCell[2]);
            const y2 = Number(selectedCell[3]);
            if(up){
               if(y1 === 0)
                  return;
               grid.moveRow(y1 + correction, y2);
            }else{
               const rowSize = grid.getData().length;
               if(y2 + 1 === rowSize)
                  return;
               grid.moveRow(y2 + correction, y1);
            }

            const CODE_A = 65;
            const x1Code = String.fromCharCode(CODE_A+x1);
            const x2Code = String.fromCharCode(CODE_A+x2);
            const startCellCode = x1Code + (y1+selectionCorrection);
            const endCellCode = x2Code + (y2+selectionCorrection);

            grid.updateSelection(grid.getCell(startCellCode), grid.getCell(endCellCode));
            //
            // const cells = [];
            // for (let i = 0; i < gap; i++) {
            //    const cellNum = 'C'+(top+i+1);
            //    let value = Number(grid.getValue(cellNum));
            //    value = increse ? value + 1 : (value === 1 ? 1 : value - 1);
            //    values[i] = String(value);
            // }
         }
      }

      function updateSelectedDepth(increse){
         const selectedCell = grid.selectedCell;
         const depthColumn = 2;

         if(selectedCell != null) {
            const y1 = Number(selectedCell[1]);
            const y2 = Number(selectedCell[3]);
            const top = y1 < y2 ? y1 : y2;
            const gap = (y1 < y2 ? y2 - y1 : y1 - y2) + 1;

            const values = [];
            for (let i = 0; i < gap; i++) {
               const cellNum = 'C'+(top+i+1);
               let value = Number(grid.getValue(cellNum));
               value = increse ? value + 1 : (value === 1 ? 1 : value - 1);
               values[i] = String(value);
            }
            updateValues(top, depthColumn, values);
         }
      }

      function updateSelectedColumn(colIndex, value){
         const selectedCell = grid.selectedCell;
         if(selectedCell != null) {
            const y1 = Number(selectedCell[1]);
            const y2 = Number(selectedCell[3]);
            const top = y1 < y2 ? y1 : y2;
            const gap = (y1 < y2 ? y2 - y1 : y1 - y2) + 1;

            const values = [];
            for (let i = 0; i < gap; i++) {
               values[i] = value;
            }
            updateValues(top, colIndex, values);
         }
      }

      function updateValues(x, y, values){
         var records = [];
         for (let i = 0; i < values.length; i++) {
            const rowIndex = x + i;
            // Update and keep history
            var record = grid.updateCell(y, rowIndex, values[i]);
            // Keep history
            records.push(record);
         }

         // Update history
         grid.setHistory({
            action: 'setValue',
            records: records,
            selection: grid.selectedCell,
         });

         // Update table
         grid.updateTable();
      }

      function itemDel(){
         const selectionRows = grid.getSelectedRows();
         if(selectionRows){
            const idx = selectionRows[0].rowIndex - 1;
            const len = selectionRows.length;
            grid.deleteRow(idx, len);
         }
      }

      function onTabKey(event){
         const selectedCell = grid.selectedCell;
         const x = Number(selectedCell[0]) + 1;
         const y = Number(selectedCell[1]) + 1;
         const rowSize = grid.getData().length;
         const colSize = columnNames.length;

         if(x === colSize){
            if(y === rowSize){
               grid.insertRow();
            }
            const cellNum = 'A'+(y+1);
            grid.updateSelection(grid.getCell(cellNum));
            event.preventDefault();
            event.stopPropagation();
         }
         //console.log(x+','+y+','+rowSize+','+colSize);
      }

      function onEnterKey(event) {
         const selectedCell = grid.selectedCell;
         const y = Number(selectedCell[1]) + 1;
         const rowSize = grid.getData().length;
         if(y === rowSize){
            grid.insertRow();
         }
      }

      function initializeEditGrid(layoutData){
         const itemTypes = ['Field', 'Grid', 'Group'];
         const dataTypes = ['BigDecimal','Int','Long','String'];
         columns = [ // for columnData prop
            {
               title: '사용자ID',
               name: 'LOUTITEMNAME',
               type: 'text',
               width: 400
            },
            {
               title: '도메인',
               name: 'LOUTITEMID',
               type: 'text',
               width: 400
            },
            {
               title: '이름',
               name: 'LOUTITEMDEPTH',
               type: 'text',
               width: 400
            },
            {
               title: '담당 어플리케이션 코드',
               name: 'LOUTITEMTYPE',
               type: 'text',
               width: 400
            }
         ];
         columnNames = [];

         for (let i = 0; i < columns.length; i++) {
            columnNames[i] = columns[i].name;
         }

         grid = jexcel(document.getElementById('editGrid'), {
            data: [[]],
            columns: columns,
            rowResize: false,
            rowDrag: true,
            columnResize: false,
            columnDrag: false,
            columnSorting: false,
            autoIncrement: false,
            allowInsertColumn: false,
            allowInsertOnTab: true,
            tableOverflow:true,
            allowManualInsertRow: false,
            tableHeight: 2500,
            onbeforepaste: beforePaste,
            allowDeletingAllRows:true,
            contextMenu: function(obj, x, y, e) {
               var items = [];

               if (y == null) {
                  // Insert a new column
                  if (obj.options.allowInsertColumn == true) {
                     items.push({
                        title:obj.options.text.insertANewColumnBefore,
                        onclick:function() {
                           obj.insertColumn(1, parseInt(x), 1);
                        }
                     });
                  }

                  if (obj.options.allowInsertColumn == true) {
                     items.push({
                        title:obj.options.text.insertANewColumnAfter,
                        onclick:function() {
                           obj.insertColumn(1, parseInt(x), 0);
                        }
                     });
                  }

                  // Delete a column
                  if (obj.options.allowDeleteColumn == true) {
                     items.push({
                        title:obj.options.text.deleteSelectedColumns,
                        onclick:function() {
                           obj.deleteColumn(obj.getSelectedColumns().length ? undefined : parseInt(x));
                        }
                     });
                  }

                  // Rename column
                  if (obj.options.allowRenameColumn == true) {
                     items.push({
                        title:obj.options.text.renameThisColumn,
                        onclick:function() {
                           obj.setHeader(x);
                        }
                     });
                  }

                  // Sorting
                  if (obj.options.columnSorting == true) {
                     // Line
                     items.push({ type:'line' });

                     items.push({
                        title:obj.options.text.orderAscending,
                        onclick:function() {
                           obj.orderBy(x, 0);
                        }
                     });
                     items.push({
                        title:obj.options.text.orderDescending,
                        onclick:function() {
                           obj.orderBy(x, 1);
                        }
                     });
                  }
               } else {
                  // Insert new row
                  if (obj.options.allowInsertRow == true) {
                     items.push({
                        title: '행 삽입',
                        onclick:function() {
                           const selectedCell = obj.selectedCell;
                           if(selectedCell == null){
                              obj.insertRow(1, parseInt(y), 1);
                           }else{
                              const y1 = Number(selectedCell[1]);
                              const y2 = Number(selectedCell[3]);
                              const top = y1 < y2 ? y1 : y2;
                              const gap = (y1 < y2 ? y2 - y1 : y1 - y2) + 1;
                              obj.insertRow(gap, top, 1);
                           }
                        }
                     });

                     items.push({
                        title: '행 추가',
                        onclick:function() {
                           const selectedCell = obj.selectedCell;
                           if(selectedCell == null){
                              obj.insertRow(1, parseInt(y), 1);
                           }else{
                              const y1 = Number(selectedCell[1]);
                              const y2 = Number(selectedCell[3]);
                              const bottom = y1 > y2 ? y1 : y2;
                              const gap = (y1 < y2 ? y2 - y1 : y1 - y2) + 1;
                              obj.insertRow(gap, bottom);
                           }
                        }
                     });
                  }

                  if (obj.options.allowDeleteRow == true) {
                     items.push({
                        title:'행 삭제',
                        onclick:function() {
                           obj.deleteRow(obj.getSelectedRows().length ? undefined : parseInt(y));
                        }
                     });
                  }
               }

               // Line
               items.push({ type:'line' });

               // Copy
               items.push({
                  title: obj.options.text.copy,
                  shortcut: 'Ctrl + C',
                  onclick: function () {
                     obj.copy();
                  }
               });
               // Paste
               items.push({
                  title: obj.options.text.paste,
                  shortcut: 'Ctrl + V',
                  onclick: function () {
                     obj.paste();
                  }
               });
               // Line
               items.push({ type:'line' });

               items.push({
                  title: '항목유형',
                  submenu: [
                     {
                        title: 'Field',
                        onclick: function() {
                           updateSelectedColumn(3, 'Field');
                        }
                     },
                     {
                        title: 'Group',
                        onclick: function() {
                           updateSelectedColumn(3, 'Group');
                        }
                     },
                     {
                        title: 'Column',
                        onclick: function() {
                           updateSelectedColumn(3, 'Column');
                        }
                     },
                     {
                        title: 'Grid',
                        onclick: function() {
                           updateSelectedColumn(3, 'Grid');
                        }
                     },
                  ]
               });
               items.push({
                  title: '깊이',
                  submenu: [
                     {
                        title: '깊이증가',
                        shortcut: 'Alt + →',
                        onclick: function() {
                           updateSelectedDepth(true);
                        }
                     },
                     {
                        title: '깊이감소',
                        shortcut: 'Alt + ←',
                        onclick: function() {
                           updateSelectedDepth(false);
                        }
                     },
                  ]
               });
               items.push({
                  title: '행 이동',
                  submenu: [
                     {
                        title: '위로이동',
                        shortcut: 'Alt + ↑',
                        onclick: function() {
                           moveSelectionRow(true);
                        }
                     },
                     {
                        title: '아래로이동',
                        shortcut: 'Alt + ↓',
                        onclick: function() {
                           moveSelectionRow(false);
                        }
                     },
                  ]
               });

               return items;
            }
         });

         $('#editGrid').on("keydown", function(e){
            if(e.altKey){
               if(e.keyCode == 39){
                  updateSelectedDepth(true);
                  return false;
               }
               if(e.keyCode == 37){
                  updateSelectedDepth(false);
                  return false;
               }
               if(e.keyCode == 38){
                  moveSelectionRow(true);
                  return false;
               }
               if(e.keyCode == 40){
                  moveSelectionRow(false);
                  return false;
               }
            }
            if(!e.shiftKey && e.keyCode == 9){
               onTabKey(e);
            }
            if(!e.shiftKey && e.keyCode == 13) {
               onEnterKey(e);
            }
         });

         resizeGrid();
         initDialog();
      }

      function closeAddRowDialog(){
         $( '#add_row_dialog' ).dialog("close");
      }

      function addNewRow(){
         var cnt = $("input[name=add_row_count]").val();
         if(cnt == "" || cnt == undefined) return;
         const ncnt = Number(cnt);

         if (grid.getJson().length == 0){
            const ncnt = Number(cnt) -1;
            grid.setData([{}]);
            if (ncnt !=0){
               grid.insertRow(ncnt);
            }
         }else{
            const ncnt = Number(cnt);
            grid.insertRow(ncnt);
         }

         $( '#add_row_dialog' ).dialog("close");
         closeAddRowDialog();
      }

      function initDialog(){
         $( '#add_row_dialog' ).dialog({
            resizable: false,
            autoOpen: false,
            height: "auto",
            width: 400,
            modal: true,
            buttons: {
               "Add": function() {
                  addNewRow();
               },
               Cancel: function() {
                  closeAddRowDialog();
               }
            }
         });

         $("input[name=add_row_count]").keydown(function(key){
            if (key.keyCode == 13){
               addNewRow();
            }
         });
      }

      function itemAdd(){
         grid.resetSelection();
         $("input[name=add_row_count]").val("");
         $( '#add_row_dialog' ).dialog("open");
      }

      var resizing = false;

      function resizeGrid(){
         var screenWidth = $(window).width() - 113;
         var columnWidth = 0;
         columns.forEach( function (element){
            columnWidth += element.width;
         } );
         var gap = screenWidth - columnWidth;
         var halfGap = gap / 2;
         grid.setWidth(0, Number(columns[0].width) + halfGap);
         grid.setWidth(1, Number(columns[1].width) + halfGap);
         resizing = false;
      }

      $( window ).resize( function() {
         if(!resizing){
            resizing = true;
            setTimeout(resizeGrid, 10);
         }
      })
      //JEXCEL 관련 함수 종료

      function init() {
         $.ajax({
            type : "POST",
            url:url,
            dataType:"json",
            data:{cmd: 'DATASOURCE'},
            success:function(json){
               let dataSource = json.dataSourceList;
               let appendHtml = "";

               dataSource.forEach(function(i,v) {
                  if( i.DATASOURCE != "FGW" ) {
                     let strSource = i.DATASOURCE;

                     appendHtml = " <input id='check" + strSource + "' class='datasource' name='" + strSource + "' type='checkbox' checked='checked' value='" + strSource + "'/>"
                     appendHtml += " <label htmlFor='check" + strSource + "'>" + strSource + "</label>"

                     $("#checkAll").parent().append(appendHtml);
                     appendHtml = "";
                  }
               });
            },
            error: function (e) {
               alert(e.responseText);
            }
         });
      }

      $(document).ready(function () {

         initializeEditGrid();

         $('body').css("overflow-x", "hidden");

         $("#btn_regist").click(function () {
            var postData = getSearchForJqgrid("cmd", "INSERT"); //jqgrid에서는 object로
            var data = grid.getData();

            /* datasourceList */
            var datasourceList = new Array();
            $(".datasource:checked").each(function (index, item) {
               datasourceList.push(item.value);
            });
            /* datasourceListEnd */

            /* userList */
            var userList = new Array();
            for (var i = 0; i < data.length; i++) {
               var item = data[i];
               let user = {};
               for (var j = 0; j < item.length; j++) {
                  if (j == 0) {
                     user['userId'] = item[j];
                  } else if (j == 1) {
                     user['teamName'] = item[j];
                  } else if (j == 2) {
                     user['userName'] = item[j];
                  } else if (j == 3) {
                     user['bzwkCdList'] = item[j];
                  } else {
                     alert(' ');
                  }
               }
               userList.push(user);
            }
            /* userListEnd */

            postData['userList'] = JSON.stringify(userList);
            postData['datasourceList'] = JSON.stringify(datasourceList);

            $.ajax({
               url: url,
               data: postData,
               dataType: "json",
               type: "POST",
               success: function (result) {
                  document.getElementById('resultText').innerHTML = "";
                  var responseMessageList = result.responseMessageList;
                  for (var i = 0; i < responseMessageList.length; i++) {
                     var pElement = document.createElement('p');
                     pElement.innerHTML = responseMessageList[i]['message'];
                     $("#resultText").append(pElement);
                  }
                  alert("일괄등록 작업이 완료되었습니다.");
               },
               error: function (e) {
                  alert(e.repsonseText);
               }
            })// ajax end
         });

         $("#checkAll").click(function () {
            $('input:checkbox').not(this).prop('checked', this.checked);
         });

         init();
      });
   </script>
<body>
<div class="right_box">
   <div class="content_top">
      <ul class="path">
         <li><a href="#">${rmsMenuPath}</a></li>
      </ul>
   </div><!-- end content_top -->
   <div id="content_middle" class="content_middle">
      <div class="search_wrap">
         <img src="<c:url value="/img/btn_regist.png"/>" alt="" id="btn_regist" level="W" status="DETAIL" />
      </div>
      <div class="title">사용자 일괄 등록</div>
      <table class="search_condition" cellspacing=0;>
         <tbody>
         <tr>
            <th>적용 Datasource</th>
            <td>
               <input id="checkAll" type="checkbox" checked="checked" > <label>전체</label> |
               <%--               <input id="checkMCI" class="datasource" name="MCI" type="checkbox" checked="checked" value="MCI"> <label for="checkMCI">MCI대면</label>--%>
               <%--               <input id="checkEAI" class="datasource" name="EAI" type="checkbox" checked="checked" value="EAI"> <label for="checkEAI">EAI</label>--%>
               <%--               <input id="checkBAT" class="datasource" name="BAT" type="checkbox" checked="checked" value="BAT"> <label for="checkBAT">배치</label> |--%>
               <%--               <input id="checkFEP" class="datasource" name="FEP" type="checkbox" checked="checked" value="FEP"> <label for="checkFEP">FEP</label>--%>
               <%--               <input id="checkBAP" class="datasource" name="BAP" type="checkbox" checked="checked" value="BAP"> <label for="checkBAP">일괄</label>--%>
            </td>
         </tr>
         </tbody>
      </table>
      <div id="editGrid"></div>
      <table class="search_condition" cellspacing=0; style="margin-top: 30px">
         <tr>
            <th width="100px">등록 완료 메세지</th>
            <td id="resultText">
            </td>
         </tr>
      </table>
   </div><!-- end content_middle -->
</div>
</body>
</html>