<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="com.udapsoft.waf.system.HandlerStorage" %>
<%@ page import="com.udapsoft.waf.common.ui.*" %>
<%@ page import="kr.co.hsnc.common.util.*"%>
<%@ page import="kr.co.hsnc.common.sql.*" %>
<%@ include file="/jsp/work/taglib.jsp" %>

<jsp:useBean id="ctx" class="com.udapsoft.waf.system.context.SessionContext" scope="session" />
<%
	ctx.init(request, response);
	ValueObject user = ctx.getUser();
	String USER_ID = user.get("USER_ID");

	HandlerStorage storage = ctx.getHandlerStorage();
	ValueObject params = storage.getParams();
	String systemSelectTag = (String) storage.getObject("SystemSelectTag");
	
	String sect_id = (String) storage.getObject("sect_id");
	String level = (String) storage.getObject("level");
	
	String code = (String) storage.getObject("code");
	String kind_big =  (String) params.get("kind_big");
	String kind_mid =  (String) params.get("kind_mid");
	String kind_small = (String) params.get("kind_small");
	
	String specCode =  (String) storage.getObject("specCode");
	String materialGroupName = (String) storage.getObject("materialGroupName");
	String calTpCode = (String) storage.getObject("calTpCode");
	
	String spec1 = (String) storage.getObject("spec1");
	String spec2 = (String) storage.getObject("spec2");
	String spec3 = (String) storage.getObject("spec3");
	String spec4 = (String) storage.getObject("spec4");
	
	if(spec1 == null) spec1 = "SPEC1";
	if(spec2 == null) spec2 = "SPEC2";
	if(spec3 == null) spec3 = "SPEC3";
	if(spec4 == null) spec4 = "SPEC4";
	
	//사용여부
	String is_use_yn = "사용|미사용";
	String is_use_yn_code = "Y|N";
	
	String pay_div_yn = "납품정산|계획분할";
	String pay_div_yn_code = "1|2";
	
%>
<script type="text/javascript">

/*예약함수*/
var sheet1 = new ibsheetObject();
var sheet1Row;
var sheet1PageNo = 1;
var pageLastRowIndex = 1;
var validationResult = false;
var filterShow = false;


$(function(){
    
    $.gridInit = function(sheetName)
	{
	    var init_sheet = {};
		
		init_sheet.Cfg = {SearchMode:2, Page:30, MergeSheet:msHeaderOnly};
		init_sheet.Cols = [
									{Header:"Status",					Type:"Status", 		SaveName:"STATUS", 					Width:0, 	Align:"Center",  Hidden:"True"},
									{Header:"삭제",					Type:"DelCheck", 		SaveName:"DEL_CHECK", 				Width:50, 	Align:"Center",  Hidden:"True"},
									{Header:"No.",						Type:"Seq", 			SaveName:"NO",							Width:20, 	Align:"Center"},
									{Header:"자재코드",				Type:"Text", 			SaveName:"MATERIAL_CD",			Width:140, 	Align:"Center", InsertEdit:"False", UpdateEdit:"False"},
									{Header:"자재명",					Type:"Text", 			SaveName:"MATERIAL_NAME",		Width:140, 	Align:"Left"},
									{Header:"<%=spec1%>",		Type:"Text", 			SaveName:"SPEC1", 						Width:100, 	Align:"Left", KeyField:"True"},
									{Header:"<%=spec2%>",		Type:"Text", 			SaveName:"SPEC2", 						Width:100, 	Align:"Left", KeyField:"True"},
									{Header:"<%=spec3%>",		Type:"Text", 			SaveName:"SPEC3", 						Width:100, 	Align:"Center", KeyField:"True"},
									{Header:"<%=spec4%>",		Type:"Text", 			SaveName:"SPEC4", 						Width:80, 	Align:"Center", KeyField:"True"},
									{Header:"사용여부",				Type:"Combo", 		SaveName:"IS_USE", 					Width:80, 	Align:"Center", ComboText:"<%=is_use_yn%>", ComboCode:"<%=is_use_yn_code%>"},
									{Header:"지급구분",				Type:"Combo", 		SaveName:"PAY_DIV", 					Width:80, 	Align:"Center", ComboText:"<%=pay_div_yn%>", ComboCode:"<%=pay_div_yn_code%>"},
									{Header:"지급구분이름",				Type:"Text", 		SaveName:"PAY_DIV_NAME", 					Width:80, 	Align:"Center", Hidden:"True"},
									{Header:"규격",					Type:"Text", 			SaveName:"MATERIAL_SPEC", 		Width:0, 	Align:"Center",	Hidden:"True"}
		                   		];
		
		
		init_sheet.HeaderMode = {Sort:1};
		IBS_InitSheet(sheetName, init_sheet);
		sheetName.SetDataAutoTrim(0);
		sheetName.SetEditable(true);
		sheetName.FitColWidth();
	}
    
	$(document).on("keyup", "input:text", function(e) {
	    
	    if (e.keyCode == 13)
        {
	        $.searchList();
        }
	    
	});
    
    
    
    $.searchList = function()
	{
		$("#fevent").val("GET_CODE_LIST");
		
		var url = Modular.model.PageContext.CONTEXT_ROOT + "/common/CommMatlCodeTagList_sheet.screen";
		Modular.view.IBSheet7.doSearch(sheet1, url, $("#form1"), 30, "");
	}
    
    $("#btn_search").click(function(){
        $.searchList();
    });
    
    $("#btn_add").click(function(){
        var level = "<%=level%>";
		var kind_small = "<%=kind_small%>";
		var material_cd = "";
		var material_cd1 = "";
		var seq = "";
		
		if(level == "3")
		{
		    if (sheet1.SearchRows() == 0 &&  (sheet1.RowCount("I") == 0)) 
			{
		        sheet1.SetDataAutoTrim(0);
				var rowIndex = sheet1.DataInsert(-1);
				sheet1.SetCellValue(rowIndex, "MATERIAL_CD", kind_small + leadingZeros("0001",4));
			}
			else
			{
			    sheet1.SetDataAutoTrim(0);
				var rowIndex = sheet1.DataInsert(-1);
				material_cd = sheet1.GetCellValue(rowIndex -1, "MATERIAL_CD");
			    if (material_cd.length == 13 ){ 
					material_cd1 = material_cd.substring(0, material_cd.length -7);
				}else{ 
					material_cd1 = material_cd.substring(0, material_cd.length -4);
				}
				seq = Number(material_cd.substring(material_cd.length -4, material_cd.length)) + 1;
				sheet1.SetCellValue(rowIndex, "MATERIAL_CD", kind_small + leadingZeros(seq,4)); //material_cd1->kind_small로 변경 
			}
		}else{
			alert("소분류를 선택하세요.");
		}
		
    });
    
    
    $("#btn_save").click(function(){
        
        $("#fevent").val("SAVE_CODE_LIST");
        
        var url = Modular.model.PageContext.CONTEXT_ROOT + "/common/CommMatlCodeTagList_sheet.screen";
		var result = Modular.view.IBSheet7.doSave(sheet1, url, $("#form1"), false);
		
    });
    
    
    $("#btn_category_reg").click(function(){
        var level = "<%=level%>";
		var kind_big = "<%=kind_big%>";
		var kind_mid = "<%=kind_mid%>";
		var kind_small = "<%=kind_small%>";
		var materialGroupName = "<%=materialGroupName%>";
		var calTpCode = "<%=calTpCode%>";
		
	    var win_id = "_categoryReg";
	    var url = "/common/MatlCategoryTagAddPopup.screen?cate_gubun=L&level="+level+"&kind_big="+kind_big+"&kind_mid="+kind_mid+"&kind_small="+kind_small+"&materialGroupName=" + materialGroupName+"&calTpCode=" + calTpCode+"&pop_win_id="+win_id;
		

		fLayerPop(win_id, url, 550, 120, '', '', 'NO');
			
    });
   
    $("#btn_category_del").click(function(){
        var level = "<%=level%>";
		var kind_big = "<%=kind_big%>";
		var kind_mid = "<%=kind_mid%>";
		var kind_small = "<%=kind_small%>";
		
		var f	= document.form1;
		if(level != "")
	    {
		    if (confirm("삭제 하시겠습니까?") ) 
			{
				submitXmlRequest( "/common/CommMatlCodeDelete_form.screen", "DELETE_CODE_LIST", f, "ROWSET" ); //xmlhttp.js
			}		    
	    }
		else
	    {
		    alert("분류코드가 선택되지 않았습니다.");
	    }
		
    });
    
    
    $("#btn_reset").click(function(){
        $("input:text").val("");
    });
    
    $("#btn_excel").click(function(){
    	if(sheet1.RowCount() == 0) {
			alert("내역이 없습니다.");
			return;
		}
    	
		var params = { FileName : "CommMatlCodeTagList.xls",  SheetName : "CommMatlCodeTagList", SheetDesign:0, Merge:1, DownCols:"2|3|4|5|6|7|8|9|10", TitleText:"플랜트 자재 코드", UserMerge:"0,0,1,9", AutoSizeColumn:1  };

		sheet1.Down2Excel(params);
    });
    
    
});

function doResult(resultObj) {
	try {
		if( resultObj.getRequestEvent() == "DELETE_CODE_LIST" ) {
			if( resultObj.getSuccess() ) {
				alert("삭제성공");
			}
			else {
				dlgErrorMsg(resultObj);
			}
		}
	}
	catch(errorObject) {
        showErrorDlg("doResult()", errorObject);
	}
}


	$(document).ready(function(){
		
	    $.gridInit(sheet1);
		$.searchList();
		
		autoResize();
		
	});
    
    
    
	function autoResize(){
		var t1_height = document.getElementById("search-table").scrollHeight + document.getElementById("title").scrollHeight + 24;
		var iframeHeight= document.body.scrollHeight - t1_height;   
		var iframeWidth= document.body.scrollWidth;   
		
		
		sheet1.SetSheetHeight(iframeHeight); 
	}	   
	    
	    
	
	function leadingZeros(n, digits) {
	  var zero = '';
	  n = n.toString();
	
	  if (n.length < digits) {
	    for (var i = 0; i < digits - n.length; i++)
	      zero += '0';
	  }
	  return zero + n;
	}
	
	function sheet1_OnSearchEnd(code, message)
	{
	    sheet1.FitColWidth();
	}
	
	
	function sheet1_OnSaveEnd(code, msg)
	{
	    var event = $("#fevent").val();
		var f = document.form1;
		
// 		alert(event);
		
		
		document.form1.isSubmit = false;
		
	    try {
	        if(event == "SAVE_CODE_LIST")
			{
	            if(code >= "0")
				{
	                alert("저장되었습니다.");
// 	                $.searchList();
				}
	            else
	            {
	                alert(msg);
	            }
			}
	    }
	    catch(errorObject) {
	        showErrorDlg("doResult()", errorObject);
		}
	}
	
	
</script>


<modular:search id="form1">
	<modular:key id="fevent" />
</modular:search>
<form id="form1" name="form1" method="post" modular:type="search">
	<input type="hidden" name="fevent" id="fevent" value="">

	<input type="hidden" name="USER_ID" value="<%=USER_ID%>"/>
	<input type="hidden" name="sect_id" value = "<%=sect_id %>" />
	<input type="hidden" name="level" value = "<%=level %>" />
	
	
	<input type="hidden" name="code" value = "<%=code %>" />
	<input type="hidden" name="kind_big" value = "<%=kind_big %>" />
	<input type="hidden" name="kind_mid" value = "<%=kind_mid %>" />
	<input type="hidden" name="kind_small" value = "<%=kind_small %>" />
	
	<input type="hidden" name="specCode" value = "<%=specCode %>" />
	<input type="hidden" name="materialGroupName" value = "<%=materialGroupName %>" />


<div align="left" id="title">
	<ul>
    	<li>플랜트자재코드</li>
   	</ul>
</div> 
 
 
<table border="0" cellspacing="0" cellpadding="0" width="98%" id="search-table">
	<!-- 검색조건 영역 : 시작 -->
	<tr>
		<td height="1">
			<table cellspacing="1" cellpadding="0" class="search-form-table">
				<col width="10%">
				<col width="30%">
				<col width="60%">

				<tr height="25"> 
    			<!-- 검색조건 타이틀 1 -->
    				<th>
    					자재코드/명
    				</th>
   					<td>
  						<input type='text' name="pgm_name2" class="input" style="width:90%" />
					</td>
				    <td rowspan="2" class="search_button" align="right"> 
				    	<span class="btnSearch center"><a href="javascript:void(0);" id="btn_search">검색</a></span>
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_add">추가</a></span>
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_save">저장</a></span>
       					<!-- ADMIN과 구매팀 사용자만(디폴트권한은 제외)  분류체계 생성가능  -->
       					<% if ((user.get("acct_type_id").equals("10") && user.get("right_name").equals("PURCHASE")) || user.get("right_name").equals("ADMIN NEW")) { %>  
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_category_reg">분류코드</a></span>
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_category_del">분류코드 삭제</a></span>
       					<% } %>
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_reset">초기화</a></span>
       					<span class="btnSearch center"><a href="javascript:void(0);" id="btn_excel">엑셀다운</a></span>
    				</td>
  				</tr>
			</table>
		</td>
	</tr>
	<!-- 검색조건 영역 : 종료 -->

	<!-- 검색조건 영역, 테이터 영역 구분 여백 : 시작 -->
	<tr>
		<td height="1">
		</td>
	</tr>
	<!-- 검색조건 영역, 테이터 영역 구분 여백 : 종료 -->
</table>

<div id="sheet1_div" style="padding-top:5px; width:98%; height: 500px">
	<script>createIBSheet("sheet1","100%", "100%");</script>
</div>

</form>
