<?php
	//이 페이지는 2가지 상황에서 사용됨
	//입찰중, 거래중
	$cd_sale 		= $_REQUEST["cd_sale"];

	$PageNo 		= $_REQUEST['pageno'];
	$PageSize 		= $_REQUEST['PageSize'];
	if (empty($PageNo)) {$PageNo=1;}else{$PageNo=$PageNo;}
	if (empty($PageSize)) {
		$PageSize=10; //목록개수설정
	}else{$PageSize=$PageSize;}

	$pagestartpoint=($PageNo-1)*$PageSize;

	$OrderBy = $_REQUEST['OrderBy'];
	if ($OrderBy == "") $OrderBy = "cast(t.nm_price as unsigned) desc, t.cd_tender desc ";

	$sOrderBy = "ORDER BY ".$OrderBy;

	$add_sql = " WHERE d.ds_delind='N' ";

	//매물 상태별 처리
	$tender_list_title = "";
	switch($ds_status_sale) {
		//입찰중
		case 'F0':
			$tender_list_title = "입찰업체";
			$add_sql.= "  ";

			break;
		//거래중
		case 'Z0':
			//낙찰한 상태이면
			if(empty($ds_status_contract_step1)) {
				$tender_list_title = "입찰업체";
				$add_sql.= "  ";
			}else {
				$tender_list_title = "낙찰업체";
				$add_sql.= " AND t.ds_status = 'Z0' ";
			}


			break;
	}

	$sql = "SELECT count(*)
				FROM aap_master d
				inner join tender_master t on ( d.cd_dealer = t.cd_dealer_p and t.cd_sale = '$cd_sale' and t.ds_delind='N' )
				inner join sale_master s on t.cd_sale = s.cd_sale and s.cd_sale = $cd_sale AND s.ds_delind='N'
				$add_sql
	";
	// echo $sql;

	// echo "select count(*) FROM ucaro_master d inner join tender_master t on (d.cd_dealer = t.cd_dealer_p and t.cd_sale = $cd_sale and t.ds_delind='N' $sql)";

	$totalrows = @mysql_result(mysql_query($sql),0,0);
?>
	<!-- 업체 리스트 -->
	<section>
		<div class="data--table--wrap mt-5">
			<div class="col-12 title--wrapper d-flex align-items-center justify-content-between">
				<h2><a name="tender_list"><?=$tender_list_title?> 리스트</a></h2>
				<div class="col-md-6 d-flex justify-content-end">
					<div>
						<select id="inputState" class="form-select" style="width:100px;">
							<option selected="">최근순</option>
							<option></option>
						</select>
					</div>
				</div>
			</div>
			<table class="table table-bordered mt-3">
				<colgroup>
					<col style="width:10%;">
					<col style="width:90%;">
				</colgroup>
				<thead>
					<tr>
						<th>
							<div class="d-flex justify-content-center">NO</div>
						</th>
						<th>
							<div class="d-flex justify-content-center">입찰금액</div>
						</th>
					</tr>
				</thead>
				<tbody>
				<?php
					if($totalrows>0) {
						$sql = "SELECT t.*, d.nm_name nm_name_dealer, d.nm_name nm_name_dealer, s.ds_status ds_status_sale
												, getRemainTimeByPhase(s.ds_auction_time, ".LIMIT_TIME_SELL.", s.dt_approve, now()) as time_limit_sell
												, d1.nm_name nm_name_dealer1
												, d1.nm_hp nm_hp_dealer1
												, s.nm_price_final
												FROM  aap_master d
												inner join tender_master t on (d.cd_dealer = t.cd_dealer_p and t.cd_sale = '$cd_sale' and t.ds_delind='N')
												inner join aap_master d1 on (t.cd_dealer = d1.cd_dealer)
												inner join sale_master s on (t.cd_sale = s.cd_sale)
												 $add_sql
											$sOrderBy
											LIMIT $pagestartpoint,$PageSize";
						// echo $sql;
						// exit;
						$r = mysql_query($sql);


						$i=1;

						$status_bid_success = array('Z0', 'ZS', 'ZE');
						$status_bid_fail = array('E0', 'F0');

						while($col = mysql_fetch_array($r)) {
							$tmpNum =$totalrows-($PageSize*($PageNo-1));
							$aapNum = ($tmpNum - $i)+1;
				?>
				<tr>
					<td>
						<div class="d-flex justify-content-center"><?=$aapNum?></div>
					</td>
					<td>
						<div class="d-flex align-items-center justify-content-center">
							<input type="text" class="form-control" style="max-width:200px" value="<?=number_format($col['nm_ex_vat_price'])?>" />
							<label class="ms-3">만원</label>

							<?php
								$btn_bid_proc = "";
								//낙찰이후 상태
								if(in_array($col['ds_status_sale'], $status_bid_success)) {
									if($col['ds_status_sale'] == "ZE"){
										$status_text = '거래실수';
									}else {
										if($col['ds_status'] == "Z0") {
											$status_text = '낙찰';
										}else {
											$status_text = '낙첨';
										}
									}
								}else {
									if(in_array($col['ds_status_sale'], $status_bid_fail)) {
										if($col['time_limit_sell']=="0분"){
											$status_text = '낙첨';
										}
										else {
											$status_text = '입찰중';
											$btn_bid_proc = "<button type='button' class='btn btn-primary ms-3 btn_bid_proc' cd_tender='{$col['cd_tender']}' nm_name_dealer='{$col['nm_name_dealer']}' nm_price='{$col['nm_price']}' value='{$col['cd_tender']}' >낙찰하기</button>";

											//<button class="button button_s_rnd ty2" type='button' onclick="selectTender('{$col['cd_tender']}','{$col['nm_name_dealer1'}','{$col['nm_price'}')" >판매완료</button>
										}
									}
								}
							?>
							<?//$status_text?>
							<?=$btn_bid_proc?>
							<?/*<button class="button button_s_rnd ty2" type='button' onclick="selectTender('<?=$col[cd_tender]?>','<?=$col[nm_name_dealer1]?>','<?=$col[nm_price]?>')" >판매완료</button>*/?>
						</div>
					</td>
				</tr>
				<?php
								$i++;
							}
						}else{
				?>
							<tr>
								<td colspan="6" align="center">데이터가 존재 하지 않습니다.</td>
							</tr>
				<?php
						}
				?>
				</tbody>
			</table>
		</div>
		<div class="col-12 d-flex justify-content-center pagination--wrapper">
			<?php
				$url = "./$list_url?searchtype=$searchtype&searchword=$searchword&ds_status=$ds_status&ds_usertype=$ds_usertype&PageSort=$PageSort";
				ListPg($url ,$PageNo,$PageSize,10,$totalrows,$leftboard[1],$rootpath);
			?>
		</div>
		<!-- <div class="btn--wrapper col-12 d-flex justify-content-center mt-5">
			<button type="button" class="btn btn-secondary list--btn" style="width:190px; height:65px;">목록</button>
		</div> -->
	</section>


	<form name="frmTenderForm" id="frmTenderForm" method="post" action="sale_proc.php">
		<input type="hidden" name="mode" value="TenderSuccessAAP">
		<input type="hidden" name="cd_sale" value="<?=$cd_sale?>">
		<input type="hidden" name="cd_tender" >
		<input type="hidden" name="nm_price" >
	</form>

<script>
$(function() {
	$(".btn_bid_proc").on("click", function() {
		var custom_opts = {
			title : '',
			btn_close_show : false,
		}
		var cd_tender = $(this).val();
		var nm_price = $(this).attr("nm_price");
		var nm_name_dealer = $(this).attr("nm_name_dealer");

		custom_opts.title = '입찰업체를 낙찰하시겠습니까?';
		custom_modal_confirm(custom_opts, function(confirm) {
			if(confirm) {

				$("#frmTenderForm input[name=cd_tender]").val(cd_tender);
				$("#frmTenderForm input[name=nm_price]").val(nm_price);

				$("#btn_bid_proc").hide();
				var data = $("#frmTenderForm").serialize();
				$.ajax({
					url : 'sale_proc.php',
					type: 'POST',
					dataType : 'json',
					data: data,
					success: function(res) {
						custom_modal_confirm_close();

						$("#btn_bid_proc").show();

						//세션 종료시 로그인 페이지로 이동
						if(res.CODE != "0000") {
							custom_opts.title = res.MSG;

							if(res.CODE == "4444") {
								window.location.href = res.DATAS.URL;
							}
							custom_modal_alert(custom_opts);
							return false;
						}

						custom_opts.title = '낙찰되었습니다.';
						custom_opts.event_esc_key = false;

						custom_modal_alert(custom_opts, function() {
							reload();
						});
					},
					error:function(request,status,error){
						$("#btn_bid_proc").show();

						custom_modal_confirm_close();

						alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
					}
				});

			}else {
				$("#btn_bid_proc").show();
				return false;
			}
		});

	});
})
</script>
