<%--
  - FileName   : suppTaxList.jsp
  - Author(s)  : ok
  - Date       : 2014.06.30
  - Copyright  : Copyright (c) 2013 www.udapsoft.co.kr, Inc.
  - Description: 협력업체포탈 외주_세금계산서 발행현황
--%>

<%@ 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.*" %>
<%@ page import="kr.co.hsnc.common.util.Formatter"%>
<%@ page import="com.udapsoft.waf.common.util.DateUtil"%>
<%@ include file="/jsp/work/taglib.jsp" %>
<jsp:useBean id="ctx" class="com.udapsoft.waf.system.context.SessionContext" scope="session" />
<%
    ctx.init(request, response);
    HandlerStorage storage = ctx.getHandlerStorage();
    ValueObject params = storage.getParams();
    ValueObject user = storage.getUser();
    String event = storage.getEvent();

    String signDt_from = params.get("signDt_from");
	String signDt_to = params.get("signDt_to");
	
	ValueObject defaultDate = DateUtil.getDefaultPeriod();
	if("".equals(signDt_from)){
		signDt_from = defaultDate.get("START_DATE");
	}
	if("".equals(signDt_to)){
		signDt_to = defaultDate.get("END_DATE");
	}
	
%>
<SCRIPT language="JavaScript">
	/*예약함수*/
	var sheet1;
	var sheet1Row;
	var sheet1PageNo = 1;
	var pageLastRowIndex = 1;
	var validationResult = false;
	var filterShow = false;
	
	function _onReady(){
		/**
		 *	IBSheet object initialize
		 */
		gridInit(sheet1);
		
	
		/**
		 *	Application Initialize
		 */
		jQuery("#btnSearch").click(function() {
			
 			jQuery("#fevent").val("GET_LIST");
			var url = Modular.model.PageContext.CONTEXT_ROOT + "/portal/payment/BuyTaxList_sheet.screen";
			Modular.view.IBSheet7.doSearch(sheet1, url, jQuery("#form1"), 10, "");
			
		});

		//역발행요청
		jQuery("#btnApProcess").click(function() {
			
			if(sheet1.RowCount("U") > 0) {
				if (confirm("역발행요청하시겠습니까?")) {
			
					jQuery("#fevent").val("AP_PROCESS");
					var url = Modular.model.PageContext.CONTEXT_ROOT + "/portal/payment/BuyTaxList_sheet.screen";
					var result = Modular.view.IBSheet7.doSave(sheet1, url, jQuery("#form1"), false);
				}
			}else{
				alert("대상을 선택해주세요.");
			}
		});
		
		
		autoResize();
		
		pageinit();
		
	}
	
/* 	function doResult(resultObj) {
		
		try {

			if (resultObj.getRequestEvent() == "AP_PROCESS") {
				alert();
				if (resultObj.getSuccess()) {

					document.form1.isSubmit = false;
					alert("역발행요청하였습니다.");
					jQuery("#btnSearch").click();
					
				} else {
					dlgErrorMsg(resultObj);
				}
				document.form1.isSubmit = false;
			}

		} catch (errorObject) {
			showErrorDlg("doResult()", errorObject);
		}
	} */
	
	function pageinit(){
		
		//setSearchDate();
		
		jQuery("#btnSearch").click();
	}
	
	/**
	 *	IBSheet object initialize
	 */
	function gridInit(sheetName){
		var init_sheet = {};
		init_sheet.Cfg = {SearchMode:2, Page:30, MergeSheet:msHeaderOnly};
		init_sheet.Cols = [
		    			{Header:'상태|상태',						Type:"Status", 			SaveName:"STATUS", 				Width:0, 	Align:"Center", Hidden:"True"},
						{Header:'선택2|선택2',						Type:"CheckBox",		SaveName:"CHECK",		 		Width:50, 	Align:"Center", HeaderCheck:0},
		    			{Header:'구분|구분',						Type:"Combo", 			SaveName:"PAY_DIV",				Width:100, 	Align:"Center",	Edit:"false", ComboText:"선급금|대금지급(납품정산)|대금지급(계획분할)", ComboCode:"0|1|2"},
		    			{Header:'현장명|현장명',					Type:"Text", 			SaveName:"DEPT_NAME",			Width:150, 	Align:"Left",	Edit:"false"},
		    			{Header:'계약명|계약명',					Type:"Text", 			SaveName:"CST_DOC_NAME",		Width:150, 	Align:"Left",	Edit:"false"},
		    			{Header:'공급일자|공급일자',				Type:"Text", 			SaveName:"DTI_WDATE",			Width:70, 	Align:"Center",	Edit:"false"},
		    			{Header:'계산서종류|계산서종류',			Type:"Text", 			SaveName:"DTI_TYPE_NM",			Width:70, 	Align:"Center",	Edit:"false"},
		    			{Header:'공급자|사업자번호',				Type:"Text", 			SaveName:"SUP_COM_REGNO_BAR",	Width:100, 	Align:"Center",	Edit:"false"},
		    			{Header:'공급자|업체명',					Type:"Text", 			SaveName:"SUP_COM_NAME",		Width:150, 	Align:"Left",	Edit:"false"},
		    			{Header:'합계금액|합계금액',				Type:"Int", 			SaveName:"TOTAL_AMOUNT",		Width:100, 	Align:"Right",	Edit:"false", Format:"#,##0"},
		    			{Header:'상태|상태',						Type:"Combo", 			SaveName:"DTI_STATUS",			Width:70, 	Align:"Center",	Edit:"false", ComboText:"역발행|역발행요청|정매출발행|수신미승인|수신승인|수신거부|역발행요청 취소|역발행요청 거부|공급자발행 취소요청|공급받는자 발행취소요청|취소완료", ComboCode:"A|V|S|I|C|R|W|T|N|M|O"},
		    			{Header:'국세청\n전송결과|국세청\n전송결과',			Type:"Text", 		SaveName:"SEND_REQUEST_DESC",	Width:50, 	Align:"Center",	Edit:"false"},
		    			{Header:'국세청\n전송결과코드|국세청\n전송결과코드',	Type:"Text", 		SaveName:"SEND_REQUEST",		Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'발행\n주체|발행\n주체',			Type:"Text", 			SaveName:"DIRECTION_NM",		Width:50, 	Align:"Center",	Edit:"false"},
		    			{Header:'☞계산서\n보기|☞계산서\n보기',	Type:"Image", 			SaveName:"BILL",				Width:50, 	Align:"Center", Edit:"false", Cursor:'pointer'},
		    			{Header:'SUB_CONT_MOD_ID',				Type:"Text", 			SaveName:"PUR_CONT_MOD_ID", 	Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'CONVERSATION_ID',				Type:"Text", 			SaveName:"CONVERSATION_ID", 	Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'공급자스마트빌ID',				Type:"Text", 			SaveName:"SUP_COM_ID", 			Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'공급받는자스마트빌ID',			Type:"Text", 			SaveName:"BYR_COM_ID", 			Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'INTER_BATCHID',				Type:"Text", 			SaveName:"INTERFACE_BATCH_ID",	Width:50, 	Align:"Center", Hidden:"True"},
		    			{Header:'return_code|return_code',				Type:"Text", 			SaveName:"RETURN_CODE",	Width:50, 	Align:"Center", Hidden:"True"}
		];

		init_sheet.HeaderMode = {Sort:1};
		IBS_InitSheet(sheetName, init_sheet);
		sheetName.SetImageList(1,"/img/buyer/button/btn_view.gif");
		sheetName.SetDataAutoTrim(0);
		//sheetName.SetEditable(false);
		//sheetName.SetDataLinkMouse("BUILD_NAME", 1);

		setGridSize();
	}

	
	/**
	 *	IBSheet Event: Search End(IBSheet 데이터 조회 CallBack)
	 */
	function sheet1_OnSearchEnd(code, message) {
	    if(code == 0) {
	    	if(sheet1.RowCount() > 0)
	    	{
	    		for(var i=1; i <= sheet1.RowCount(); i++)
	    		{
	    			if(sheet1.GetCellValue(i+1,"RETURN_CODE") != null && sheet1.GetCellValue(i+1,"RETURN_CODE") != "" && sheet1.GetCellValue(i+1,"RETURN_CODE") != "30000")
	    			{
	    				sheet1.SetRowBackColor(i+1,"#FFDCDC");
	    			}	    			
	    		}
	    	}
	    	
	    	setGridSize();
	    	//sheet1.SetColFontColor("BUILD_NAME", "#0000ff");
		} else {
			//조회 에러 수행
			//alert(message);
			alert("조회 실패");
		}
	}
	
	function sheet1_OnSaveEnd(code, msg) {
	    if(code >= 0) {
	    	
	    	if(jQuery("#fevent").val() == "AP_PROCESS"){
	    		
	    		//역발행요청처리
	    		sendApProc();
	    	}
	    	
	    } else {
	    	alert(msg);
        }
	    jQuery("#btnSearch").click();
	}
	
	/**
	 *	IBSheet Event: Click
	 */
	function sheet1_OnClick(Row, Col, Value, CellX, CellY, CellW, CellH) {
		 
		if (sheet1.ColSaveName(Col) == "CHECK" && Row > 0) {	//세금계산서
			jQuery("#convId").val(sheet1.GetCellValue(Row, "CONVERSATION_ID")); 
		}
		
	}
	
	/**
	 *	IBSheet size setting
	 */
	function setGridSize() {
		sheet1.FitColWidth();
	}
	
	/**
	 *	IBSheet Event: DBLCLICK
	 */
	function sheet1_OnDblClick(Row, Col, Value, CellX, CellY, CellW, CellH) {

		if (sheet1.ColSaveName(Col) == "BILL") {	//세금계산서
			var conversationId = sheet1.GetCellValue(Row, "CONVERSATION_ID"); 				
			var popUrl	=	"/payment/purchase/taxInfoPop.screen?CONVERSATION_ID="+conversationId	
			var popOption = "width=750, height=500, resizable=no, scrollbars=no, status=no;";    //팝업창 옵션(optoin)
			window.open(popUrl,"",popOption);
		}
		
		if(sheet1.GetCellValue(Row,"RETURN_CODE") != null && sheet1.GetCellValue(Row,"RETURN_CODE") != "" && sheet1.GetCellValue(Row,"RETURN_CODE") != "30000")
		{
			var conversationId = sheet1.GetCellValue(Row, "CONVERSATION_ID");
			if(	sheet1.ColSaveName(Col) == "PAY_DIV"	||
				sheet1.ColSaveName(Col) == "DEPT_NAME"	||										
				sheet1.ColSaveName(Col) == "CST_DOC_NAME"	||										
				sheet1.ColSaveName(Col) == "DTI_WDATE"	||										
				sheet1.ColSaveName(Col) == "DTI_TYPE_NM"	||										
				sheet1.ColSaveName(Col) == "SUP_COM_REGNO_BAR"	||										
				sheet1.ColSaveName(Col) == "SUP_COM_NAME"	||										
				sheet1.ColSaveName(Col) == "TOTAL_AMOUNT"	||										
				sheet1.ColSaveName(Col) == "DTI_STATUS"	||										
				sheet1.ColSaveName(Col) == "DIRECTION_NM"								
			)
			{
				var win_id = "TaxErrorPop";
				var popUrl = "/payment/outside/TaxErrorPop.screen?pop_win_id="+win_id+"&ref_id="+conversationId;
				fLayerPop(win_id, popUrl, 780, 265, '', '', 'NO');
				
				document.form1.isSubmit = false;
			}
		}
		
	}
	
	function doKeyPress() {
	    if( event.keyCode == 13 ) {
	    	//jQuery("#btnSearch").click();
	    }
	}	

	function sheet1_OnSmartResize(Width, Height) { 
		sheet1.FitColWidth();
		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); 
	}	
	document.body.onresize = addEvent( document.body.onresize, "autoResize()");
	
	//달력팝업	
	function calendar(thisDayObj){
		dlgCalendar(thisDayObj);
	}	

	//검색 조건에 작성일 일자 설정
	function setSearchDate(){
		    
		//검색조건 시작일 
		var startDate = get_year() +'-'+ get_month()  +'-'+ '01';
	    if(jQuery('#searchDateStart').val() == ""){
	    	jQuery('#searchDateStart').val(startDate);	
	    }
			
		//검색조건 종료일
		var nowYearMonth = new Date( get_year(), get_month(), "");
	    var lastDay = nowYearMonth.getDate();
		var endDate = get_year() +'-'+ get_month()  +'-'+ lastDay;
	    if(jQuery('#searchDateEnd').val() == ""){
	    	jQuery('#searchDateEnd').val(endDate);	
	    }
	}
	
	function billStatus(){
		
		//alert(jQuery("#selectBillStatus option:selected").val());
		var selectBillStatusVal = jQuery("#selectBillStatus option:selected").val();
		//상태값에 따른 버튼 컨트롤
		if(selectBillStatusVal == ""){	//전체
			
			jQuery("#spanApProcess").hide();	//역발행 요청 버튼 숨김
			
		}else if(selectBillStatusVal == "A"){	//역발행요청상태(최초등록상태)
			
			jQuery("#spanApProcess").hide();	//역발행 요청 버튼 표시
			
		}else if(selectBillStatusVal == "V"){	//업체에 역발행 요청한

			jQuery("#spanApProcess").hide();	//역발행 요청 버튼 표시
			
		}else if(selectBillStatusVal == "I"){	//수신미승인상태
			
			jQuery("#spanApProcess").hide();	//역발행 요청 버튼 표시
		
			
		//}else if(selectBillStatusVal == "A"){
			
		}
		
		jQuery("#btnSearch").click();
	}
	
	
	function sendApProc() {
		jQuery("#fevent").val("RUN_AP_PROCESS");
		var f = document.form1;
		submitXmlRequest("/portal/payment/BuyTaxList_form.screen", "RUN_AP_PROCESS", f, "VALUEOBJECT");
	}
    
	function doResult(resultObj) {
		try {
			
			if( resultObj.getRequestEvent() == "RUN_AP_PROCESS" ) {
				jQuery("#btnSearch").click();
			
				var vo 		= resultObj.getValueObject();
    			var sParam 	= vo.get('result');
    			
    			var win_id = "TaxRequestResultPop";
    			var link = "/payment/outside/TaxResultPop.screen";
    			    link += "?pop_win_id="+win_id;
    			    link += sParam;
    			    
				fLayerPop(win_id, link, 780, 360, '', '', 'NO');
    			    
				document.form1.isSubmit = false;
			}
		}
		catch(errorObject) {
	        showErrorDlg("doResult()", errorObject);
		}
	}
	
	function viewhtml(){
		
	} 
	
	/*function test(){
		
		//var conversationId = sheet1.GetCellValue(Row, "CONVERSATION_ID"); 				
		//var popUrl = "http://211.38.140.131:10000/DTI/DTI_ERROR_DISPLAY.asp?CONVERSATION_ID="+conversationId+"&SBTYPE=AP";
		var popUrl = "http://211.38.140.131:10000/DTI/DTI_ERROR_DISPLAY.asp?ref_id=12345678912148189369201410074976103";
		var popOption = "width=750, height=500, resizable=no, scrollbars=no, status=no;";    //팝업창 옵션(optoin)
		window.open(popUrl,"",popOption);
		
	}*/
	
	function sheet1_OnMouseMove(Button, Shift, X, Y) { 

		//마우스 위치가 2컬럼 일때만 마우스 손가락 모양
		var Row = sheet1.MouseRow();
		
		if(sheet1.GetCellValue(Row,"RETURN_CODE") != null && sheet1.GetCellValue(Row,"RETURN_CODE") != "" && sheet1.GetCellValue(Row,"RETURN_CODE") != "30000")
		{
			 sheet1.SetMousePointer("Hand");
		}else{
			 sheet1.SetMousePointer("Default");
		}
	}	
</SCRIPT>


<modular:search id="form1">
	<modular:key id="fevent" />
</modular:search>
<BODY onresize="autoResize()" >
<form id="form1" name="form1" method="post" modular:type="search">

	<INPUT type="hidden" name="fevent" id="fevent" value="">
	<INPUT type="hidden" name="batchId" id="batchId" value="">
	<INPUT type="hidden" name="convId" id="convId" value="">
	<INPUT type="hidden" name="userCorpId" id="userCorpId" value="<%=user.get("CORP_ID")%>">
			
	<!-- 프로그램 제목 -->
	<div align="left" id="title">
		<ul>
			<li>구매_세금계산서 발행현황</li>
		</ul>
	</div> 

	<!-- 검색조건 시작 -->
	<table id="search-table" class="search-form-table">
		<colgroup>
			<col width="100px" />
			<col/>
			<col width="100px" />
			<col/>
			<col width="200px" />
		</colgroup>
		<tr>
			<th>구분</th>
			<td><%-- <INPUT type="text" id="searchBuildName" name="searchBuildName" value="<%=returnBuildName %>" maxlength="50" class="input" style="IME-MODE : active; width:80%;"  desc='계약명' onKeyPress="doKeyPress();"> --%>	
				<SELECT name="selectDiv">
					<OPTION value="">전체</OPTION>
	                <OPTION value="1">선급금</OPTION>
	                <OPTION value="2">대금지급(계획분할)</OPTION>
	                <OPTION value="3">대금지급(납품정산)</OPTION>
	            </SELECT>
			</td>
			<th>공급일자</th>
			<td>
				<%= InputText.get("searchDateStart", signDt_from, 15, 10, "Center, date, PerSize, readonly", "date", "") %>
				<IMG name="start_img" src="/img/buyer/button/bt_calender.gif" border="0" align="absmiddle" style="cursor:pointer;" onClick="JavaScript:dlgCalendar('searchDateStart');">
				&nbsp;~&nbsp;
				<%= InputText.get("searchDateEnd", signDt_to, 15, 10, "Center, date, PerSize, readonly", "date", "") %>
				<IMG name="start_img" src="/img/buyer/button/bt_calender.gif" border="0" align="absmiddle" style="cursor:pointer;" onClick="JavaScript:dlgCalendar('searchDateEnd');">
			</td>
			<td class="button" rowspan="4">
				<span class="btnSearch center"><a href="javascript:void(0);" id="btnSearch">검색</a></span>
				<span id="spanApProcess" class="btnSearch center" style="display: none"><a href="javascript:void(0);" id="btnApProcess">역발행요청</a></span>
				<!-- span id="TEST" class="btnSearch center"><a href="javascript:test();" id="test">test</a></span -->
			</td>
		</tr>
		<tr>
			<th>현장</th>
			<td>
				<%--<%=InputText.getSiteCode("searchDeptCd", "searchDeptNm", "", user, "", "")%> --%>
				<%=InputText.getSiteCodeNew("searchDeptCd", "searchDeptNm", "", user, "", "")%>
			</td>
			<th>계약명</th>
			<td><INPUT type="text" id="searchBuildName" name="searchBuildName" value="" maxlength="50" class="input" style="IME-MODE : active;width:95%;"   desc='계약명' onKeyPress="doKeyPress();"></td>
		</tr>
		<tr>
			<th>사업자번호</th>
			<td><INPUT type="text" id="searchRegNo" name="searchRegNo" value="" maxlength="50" class="input" style="IME-MODE : active;width:95%;"   desc='사업자번호' onKeyPress="doKeyPress();"></td>
			<th>업체명</th>
			<td><INPUT type="text" id="searchCorpNm" name="searchCorpNm" value="" maxlength="50" class="input" style="IME-MODE : active;width:95%;"   desc='업체명' onKeyPress="doKeyPress();"></td>
		</tr>
		<tr>
			<th>상태</th>
			<td colspan="3">
				<SELECT name="selectBillStatus" onchange="billStatus();">
					<OPTION value="">전체</OPTION>
	                <OPTION value="A">역발행</OPTION>
	                <OPTION value="V">역발행요청</OPTION>
	                <!-- <OPTION value="S">정매출발행</OPTION> -->	
	                <OPTION value="I">수신미승인</OPTION>	
	                <OPTION value="C">수신승인</OPTION>
	                <OPTION value="R">수신거부</OPTION>
	                <OPTION value="W">역발행요청 취소</OPTION>
	                <OPTION value="T">역발행요청 거부</OPTION>
	                <OPTION value="N">공급자발행 취소요청</OPTION>
	                <OPTION value="M">공급받는자 발행취소요청</OPTION>
	                <OPTION value="O">취소완료</OPTION>
	            </SELECT>
			</td>
		</tr>
		
	</table>
	<!-- 검색조건 종료 -->
	<div id="sheet1_div" style="padding-top:5px; height: auto; min-height: 450px; overflow: auto;">
		<script>createIBSheet('sheet1','100%', '450px');</script>
	</div>
</FORM>
</body>