<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<script type="text/javascript">

$(document).ready(function(){
	$("input:text[numberOnly]").on("keyup", function() {
	    $(this).val($(this).val().replace(/[^0-9]/g,""));
	});
	
	$("input:text[numberOnly2]").on("keyup", function() {
		if($('#biddPer').val()*1 > 100){ //퍼센트
			alert("낙찰하한율은 100%를 넘을수 없습니다.");
			$('#biddPer').val("");	
		}else{
			$(this).val($(this).val().replace(/[^0-9.]/g,""));
		}
	    
	});	
	
	$('#biddNum').trigger("keypress") ;
	
	$('#biddNum').trigger("onkeyup") ;
	
	$.ajaxSetup({
	    beforeSend : function () { showLodingBar() },
	    complete   : function () { deleteLodingBar() }
	});
	
});



//금액에 , 찍기
function numchk(num) {
	num = new String(num);
	num = num.replace(/,/gi,"");
	return numchk1(num);
}

function numchk1(num) {
	var sign="";

	if(isNaN(num)) {
		alert("숫자만 입력할 수 있습니다.");
		return 0;
	}

	if(num == 0) {
		return num;
	}

	if(num < 0) {
		num = num * (-1);
		sign = "-";
	} else {
		num = num * 1;
	}

	num = new String(num)
	var temp = "";
	var pos = 3;
	num_len = num.length;

	while(num_len > 0) {
		num_len = num_len - pos;

		if(num_len < 0) {
			pos = num_len + pos;
			num_len = 0;
		}

		temp = ","+num.substr(num_len,pos) + temp;
	}

	return sign + temp.substr(1);
}

// 금액 숫자를 한글로
function num_han(num) {
	if(num == "1") return "일";
	else if(num == "2") return "이";
	else if(num == "3") return "삼";
	else if(num == "4") return "사";
	else if(num == "5") return "오";
	else if(num == "6") return "육";
	else if(num == "7") return "칠";
	else if(num == "8") return "팔";
	else if(num == "9") return "구";
	else if(num == "십") return "십";
	else if(num == "백") return "백";
	else if(num == "천") return "천";
	else if(num == "만") return "만 ";
	else if(num == "억") return "억 ";
	else if(num == "조") return "조 ";
	else if(num == "0") return "";
}

function NUM_HAN(num, mode, return_input) {
	if(num == "" || num == "0") {
		if(mode == "3") {
			return_input.value = "";
		}

		return;
	}

	num = new String(num);
	num = num.replace(/,/gi,"");
	var len = num.length;
	var temp1 = "";
	var temp2 = "";

	if(len/4> 3 && len/4 <= 4) {
		if(len%4 == 0) {
			temp1 = ciphers_han(num.substring(0,4)) + "조" + ciphers_han(num.substring(4,8)) + "억" + ciphers_han(num.substring(8,12)) + "만" + ciphers_han(num.substring(12,16));
		} else {
			temp1 = ciphers_han(num.substring(0,len%4)) + "조" + ciphers_han(num.substring(len%4,len%4+4)) + "억" + ciphers_han(num.substring(len%4+4,len%4+8)) + "만" + ciphers_han(num.substring(len%4+8,len%4+12));
		}
	} else if(len/4 > 2 && len/4 <= 3) {
		if(len%4 == 0) {
			temp1 = ciphers_han(num.substring(0,4)) + "억" + ciphers_han(num.substring(4,8)) + "만" + ciphers_han(num.substring(8,12));
		} else {
			temp1 = ciphers_han(num.substring(0,len%4)) + "억" + ciphers_han(num.substring(len%4,len%4+4)) + "만" + ciphers_han(num.substring(len%4+4,len%4+8));
		}
	} else if(len/4 > 1 && len/4 <= 2) {
		if(len%4 == 0) {
			temp1 = ciphers_han(num.substring(0,4)) + "만" + ciphers_han(num.substring(4,len));
		} else {
			temp1 = ciphers_han(num.substring(0,len%4)) + "만" + ciphers_han(num.substring(len%4,len));
		}
	} else if(len/4 <= 1) {
		temp1 = ciphers_han(num.substring(0,len));
	}

	for(var i=0; i<temp1.length; i++) {
		temp2 = temp2 + num_han(temp1.substring(i, i+1));
	}

	temp3 = new String(temp2);
	temp3 = temp3.replace(/억 만/gi,"억 ");
	temp3 = temp3.replace(/조 억/gi,"조 ");

	if(mode == 1) {
		alert(temp3 + " 원");
	} else if(mode == 2) {
		return temp3;
	} else if(mode == 3) {
		return_input.value = "( " + temp3 + " 원 )";
	}
}

function ciphers_han(num) {
	var len = num.length;
	var temp = "";

	if(len == 1) {
		temp = num;
	} else if(len == 2) {
		temp = num.substring(0,1) + "십" + num.substring(1,2);
	} else if(len == 3) {
		temp = num.substring(0,1) + "백" + num.substring(1,2) + "십" + num.substring(2,3);
	} else if(len == 4) {
		temp = num.substring(0,1) + "천" + num.substring(1,2) + "백" + num.substring(2,3) + "십" + num.substring(3,4);
	}

	num = new String(temp);
	num = num.replace(/0십/gi,"");
	num = num.replace(/0백/gi,"");
	num = num.replace(/0천/gi,"");

	return num;
}

function moncom(mon) {
	var factor = mon.length % 3;
	var su = (mon.length - factor) / 3;
	var com = mon.substring(0,factor);

	for(var i=0; i < su ; i++) {
		if((factor == 0) && (i == 0)) {
			com += mon.substring(factor+(3*i), factor+3+(3*i));
		} else {
			com += "," ;
			com += mon.substring(factor+(3*i), factor+3+(3*i));
		}
	}
	document.write(com);
}

function handleClick(cb) {
	if($('input:checkbox[name=biddCheckBox]:checked').length > 2){ //체크박스 3개 선택하면
		$(cb).prop("checked", false);
		alert("두개만 체크 가능합니다.");
		return;
	}
}


function setButton(){
	var biddNum =$('#biddNum').val();
	if(biddNum == ''){
	   	alert("기초금액을 입력해 주세요"); return;
	}
	
	var params={
		"biddNum" : biddNum
	}
	$.ajax({
		type:"POST"
		, url:"<c:url value='/itn/web/user/biddSetButtonAjax.do'/>"
		, data:params
		, dataType:'json'
		, timeout:(1000*900)
		, success:function(data){
			if(data.biddList.length > 0 ){
				$('#biddCheckList').val(""); //초기화
				var tempButton = "";
				var biddCheckList = new Array();
				for(var i=0; i < data.biddList.length ; i++){
					if(i==7) tempButton  = tempButton + '</br>';
					tempButton = tempButton + '<input class="biddCheckBox" onclick="handleClick(this);" style="margin-left: 10px;zoom:1.8;" name="biddCheckBox" type="checkbox" value="'+data.biddList[i].biddNum+'" >' ;
					biddCheckList.push(data.biddList[i].biddNum)
				}
				$('.binButton').html(tempButton);
				$('#biddCheckList').val(biddCheckList);
				$('#tr_num_choice').show()
			}else{ 
				return;
			} 
		},
		error:function(request , status, error){
			alert("중복확인이 실패되었습니다.");
			//alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
		}
	});
}


var action_num = 1;
function setResult(){
	var biddNum =$('#biddNum').val();
	if(biddNum == ''){
	   	alert("기초금액을 입력해 주세요"); return;
	}
	
	if($('.biddCheckBox').length == 0){
		alert("금액결정을 눌러주세요."); return;
	}
	
	
	if($('input:checkbox[name=biddCheckBox]:checked').length !=2){
		alert("가격버튼 두개를 선택해 주세요."); return;
	}
	
	if($('#comNum').val()==""){
		alert("경쟁업체수 값을 넣어주세요."); return;
	}
	if($('#biddPer').val()==""){
		alert("낙찰하한율을 넣어주세요."); return;
	}
	
	var frm = document.form;
   	var data = new FormData(frm);
   	
	$.ajax({
       type: "POST",
       url: "/itn/web/user/biddSetResultAjax.do",
       data: data,
       dataType:'json',
       processData: false,
       contentType: false,
       cache: false,
       timeout: 600000,
       success: function (returnData, status) {
           if(status == 'success'){
        	   $('#result_bid').text("");
        	   $('#result_com').text("");
        	    for(var i=0 ; i<returnData.biddList.length; i++){
        	    	if(i< returnData.divideNum ){
        	    		$('#result_bid').append("<span style=\"color:blue;font-weight:bold;\">"+returnData.biddList[i].biddChoice+"건 > "+ numberWithCommas(returnData.biddList[i].biddNum)+"원</span></br>");	
        	    	}else{
        	    		$('#result_bid').append(returnData.biddList[i].biddChoice+"건 > "+ returnData.biddList[i].biddNum+"</br>");
        	    	}
        	    }
        	    
        	    for(var i=0 ; i<returnData.comAllCompany.length; i++){
        	    	//console.log(i + "//" + returnData.comAllCompany[i].biddChoice+"건 > "+ returnData.biddList[i].biddNum);
        	    	if(i==0){
        	    		$('#result_com').append("<span style=\"color:blue;font-weight:bold;\">"+returnData.comAllCompany[i].comName +" , 선택값: "+ 
        	    		numberWithCommas( returnData.comAllCompany[i].biddCheckBox.split(",")[0] )+"원 / " + 
        	    		numberWithCommas( returnData.comAllCompany[i].biddCheckBox.split(",")[1] )+"원 </span></br>");	
        	    	}/* else{
        	    		$('#result_com').append(returnData.comAllCompany[i].comName +" , 선택값: "+ returnData.comAllCompany[i].biddCheckBox+"</br>");
        	    	} */
        	    }
        	    
        	    $('#result_num').append("<span style=\"color:blue;font-weight:bold;\">"
        	    	+action_num+". 상위 4개 예비가격 평균가 : <span class=\"result_num_each\">" + numberWithCommas(returnData.avg)+"원"
					+ "</span> / 하한율("+returnData.biddingVO.biddPer+"%) 적용가 : <span class=\"result_lgAvg_each\">" + numberWithCommas(returnData.lgAvg)+"원"		        	     
        	    	/* +"</span></span>"+"<input type=\"hidden\" class=\"hidden_avg\" value=\""+returnData.avg+"\" ><input type=\"hidden\" class=\"hidden_lgAvg\" value=\""+returnData.lgAvg+"\" ></br>" */
        	    	+"</span></span>"+"<span  class=\"hidden_avg\" value=\""+returnData.avg+"\" /><span class=\"hidden_lgAvg\" value=\""+returnData.lgAvg+"\" /></br>"
        	    );
        	    
	           	$(".tr_hidden").show() ;
	           	
	           	//누적 평균 구하기
	           	var result_num_each = 0;
	           	$('.hidden_avg').each(function(index, item){
	           		result_num_each += $(this).attr('value')*1 ;
	           	});
	           	$('#result_total_num').text( numberWithCommas( Math.floor(result_num_each / action_num))+"원" ) ;
	           	
	           	var result_lgAvg_each = 0;
	           	$('.hidden_lgAvg').each(function(index, item){
	           		result_lgAvg_each += $(this).attr('value')*1 ;
	           	});
	           	$('#result_total_lgAvg').text(  numberWithCommas( Math.floor(result_lgAvg_each / action_num))+"원" ) ;
	           	action_num++;
	           	
           }else{
           	alert("등록에 실패하였습니다.");
           }
       },
       error: function (e) {
           console.log("ERROR : ", e);
           alert("등록에 실패하였습니다.");
       }
   	});
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}


function showLodingBar(){
	var width = 0;
    var height = 0;
    var left = 0;
    var top = 0;

    width = 30;
    height = 30;
    top = ( $(window).height() - height ) / 2 + $(window).scrollTop();
    left = ( $(window).width() - width ) / 2 + $(window).scrollLeft();

    if($("#div_ajax_load_image").length != 0) {
           $("#div_ajax_load_image").css({
                  "top": top+"px",
                  "left": left+"px"
           });
           $("#div_ajax_load_image").show();
    }else{
    	  $('body').append('<div id="div_ajax_load_image" style="position:absolute; top:' + top + 'px; left:' + left + 'px; width:' + width + 'px; height:' + height + 'px; z-index:9999; background:#f0f0f0; filter:alpha(opacity=0); opacity:alpha*0.5; margin:auto; padding:0; "><img src="/direct/img/lodingBar.gif"></div>');
    }
}

function deleteLodingBar(){
    if($("#div_ajax_load_image").length != 0) {
    	$("#div_ajax_load_image").remove() ;
    }    
}


</script>
<form name="form" id="form" action=# method=get>
	<input type="hidden" name="biddCheckList" id="biddCheckList" value="">
	<div class="member_pw">입찰 시뮬레이션</div>
	<div class="table_area">
		<table class="write">
			<caption>모의 입찰</caption>
			<colgroup>
				<col style="width: 120px;" />
				<col style="width: *;" />
			</colgroup>
			<tbody>
				<tr>
					<th scope="row">기초금액</th>
					<td>
						<input type="text" name="biddNum" value="0" id="biddNum" size=10 maxLength=15 style="text-align:right" onkeypress="NUM_HAN(this.value, 3, document.form.EMONEY_HAN)" onkeyup="this.value=numchk(this.value);NUM_HAN(this.value, 3, document.form.EMONEY_HAN)"> 원&nbsp;
						<input type="text" name="EMONEY_HAN" readonly style="border:0;" size="30">
						<a class="btn save" id="createButton"  href="javascript:setButton();" title="찾기"><span>금액결정</span></a>
					</td>
				</tr>
				<tr id="tr_num_choice" style="display: none;">
					<th scope="row">가격버튼</th>
					<td class="binButton">
					</td>
				</tr>
				<tr>
					<th scope="row">경쟁업체수</th>
					<td><input numberOnly style="text-align:right"  size=10 id="comNum" name="comNum" type="text" value="0" />개</td>
				</tr>
				<tr>
					<th scope="row">낙찰하한율</th>
					<td><input numberOnly2 style="text-align:right"  size=10 id="biddPer" name="biddPer" type="text" value="0" />%
					<a class="btn save" id="createButton"  href="javascript:setResult();" title="찾기"><span>결과보기</span></a>
					</td>
				</tr>
				<tr class="tr_hidden" style="display: none;">
					<th scope="row">결과</th>
					<td style="line-height: 1.4em;">
						<span id="result_num">						
						</span>
						<span id="result_total" style="color:red;font-weight:bold;">
							(누적평균)상위 4개 예비가격 평균가 : <span id="result_total_num">원</span>	/ (누적평균)하한율 적용가 : <span id="result_total_lgAvg">원</span>			
						</span>
					</td>
				</tr>
				
				<tr class="tr_hidden" style="display: none;">
					<th scope="row">결과(금액순위)</th>
					<td id="result_bid" style="line-height: 1.4em;">
					</td>
				</tr>
				<tr class="tr_hidden" style="display: none;">
					<th scope="row">결과(업체선택)</th>
					<td id="result_com" style="line-height: 1.4em;">
						
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</form>
<form name="temp_form">
</form>
