<?php

	include $_SERVER['DOCUMENT_ROOT'].'/common/lib/comm.php';
	include $_SERVER['DOCUMENT_ROOT'].ADMIN_PATH.'common/auth_chk.php';

	$list_url = "prepare_list.php";
//	$mp = "32";	//set top nav
	$mp = "31";	//set top nav	20190805


	$searchtype 	= $_REQUEST['searchtype'];
	$searchword 	= $_REQUEST['searchword'];
	$ds_usertype 	= $_REQUEST['ds_usertype'];
	$ds_status 		= $_REQUEST['ds_status'];
	$dt_start 		= $_REQUEST['dt_start'];
	$dt_end 		= $_REQUEST['dt_end'];

	$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;
	$add_sql = "where s.ds_delind='N'";
    //  $orderby = "order by s.dt_insert desc";          //2200513 등록일 날짜 기준으로 리스트 정렬하기
	//$orderby = "order by s.dt_update desc";		//20191207 디비에 업데이트 날짜 기준으로 리스트 정렬하기
	if(empty($PageSort)) {
		$orderby = "order by s.dt_update desc";
	}else {
		$sort = explode("|", $PageSort);
		$orderby = "order by $sort[0] $sort[1] ";
	}

	$ds_type = "A0";	//A0 : 매입
	$add_sql.= "	and s.ds_type = '$ds_type' ";

	if($searchword != ""){
		if($searchtype=="" || $searchtype==null){
			$add_sql.= "	and (s.nm_name like '$searchword%' or a.nm_number like '$searchword%') ";
		}else{
			$add_sql.= "	and $searchtype like '$searchword%'";
		}
	}

	if($ds_usertype != ""){
		$add_sql.= "	and s.ds_usertype = '$ds_usertype'";
	}

	if($dt_start != "" && $dt_end != ""){
		$add_sql.= "	and s.dt_insert between '$dt_start' and '$dt_end' ";
	}

	$add_sql.= "	and s.ds_status in ('E0','F0')";

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//관계사/지점 Setting
	$admin_ds_company_bp	= $_SESSION['admin_ds_company_bp'];	//관계사
	$admin_ds_branch		= $_SESSION['admin_ds_branch'];		//지점
	$admin_bp_ok			= ($admin_ds_company_bp != "" || $admin_ds_branch != "") ? true : false;	//admin_ds_company_bp 나 admin_ds_branch 값이 하나라도 있으면 관계사로 보고 권한 제한한다. $admin_bp_ok == true 이면 해당 관계사/지점 데이타만 확인 가능하다.

//관계사 일 경우 해당 관계사/지점 데이타만 확인 가능하다.
	// if($admin_bp_ok){
	// 	if($admin_ds_company_bp != "" && $admin_ds_branch != ""){
	// 		$add_sql.= "	and s.ds_company_bp = '$admin_ds_company_bp' and s.ds_branch = '$admin_ds_branch' ";
	// 	}else{	//admin_ds_company_bp 나 admin_ds_branch 값이 하나라도 없으면 데이타 확인 안되게 한다.
	// 		$add_sql.= "	and 1 = 2 ";
	// 	}
	// }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//오리지널
	$sql = "select count(*)
				from sale_master s
				inner join car_master a on ( s.cd_car = a.cd_car )
				LEFT OUTER JOIN car_model b on (a.cd_model = b.cd_model)
				LEFT OUTER JOIN car_brand d on (a.cd_brand = d.cd_brand)
				$add_sql";


//  $sql = "
//    SELECT COUNT(*)
//    FROM sale_master s
//    INNER JOIN car_master a ON s.cd_car = a.cd_car
//    LEFT OUTER JOIN car_model b ON a.cd_model = b.cd_model
//    LEFT OUTER JOIN car_brand d ON a.cd_brand = d.cd_brand
//
//    $add_sql
//  ";
	$totalrows = @mysql_result(mysql_query($sql),0,0);

?>
<? include("../inc/inc_top.php") ?>
<? include("../inc/inc_header.php") ?>

<section id="contents">
	<h2>입찰중 리스트</h2>

<form id="frmSearch" name="frmSearch" method="post">
<input type="hidden" id="PageSort" name="PageSort">
<input type="hidden" id="PageSize" name="PageSize">
<input type="hidden" id="searchtype" name="searchtype" value="<?=$searchtype?>">

	<table class="tbl_search">
		<colgroup>
			<col width="10%">
			<col width="*">
		</colgroup>
		<tr>
			<th>검색어</th>
			<td>
				<span class="select2" style="margin-right:5px;width:100px;" id="sel_searchtype">
					<select>
						<option value="">전체</option>
						<option value="s.nm_name"<? if($searchtype =="s.nm_name"){?> selected<?}?>>판매자</option>
						<option value="a.nm_number"<? if($searchtype =="a.nm_number"){?> selected<?}?>>차량번호</option>
						<option value="d.nm_brand"<? if($searchtype =="d.nm_brand"){?> selected<?}?>>제조사</option>
						<option value="b.nm_model"<? if($searchtype =="b.nm_model"){?> selected<?}?>>모델명</option>
						<option value="a.nm_color"<? if($searchtype =="a.nm_color"){?> selected<?}?>>색상</option>
					</select>
				</span>
				<input type="text" id="searchword" name="searchword" class="inp_txt" style="width:60%;" value="<?=$searchword?>">
			</td>
		</tr>
		<tr>
			<th>기간검색</th>
			<td>
				<!--span class="select2" style="margin-right:5px;width:100px;">
					<select>
						<option value=""></option>
					</select>
				</span-->
				<input type="text" class="inp_txt" style="width:30%;" id="dt_start" name="dt_start" value="<?=$dt_start?>">
				<span class="btn_cal" id="btn_cal1">달력보기</span>
				~
				<input type="text" class="inp_txt" style="width:30%;" id="dt_end" name="dt_end" value="<?=$dt_end?>">
				<span class="btn_cal" id="btn_cal2">달력보기</span>
				<div class="sel_period">
					<span onclick="setSearchDate('day',0)">오늘</span>
					<span onclick="setSearchDate('day',-7)">7일</span>
					<span onclick="setSearchDate('day',-15)">15일</span>
					<span onclick="setSearchDate('month',-1)">1개월</span>
					<span onclick="setSearchDate('month',-3)">3개월</span>
					<span onclick="setSearchDate('year',-1)">1년</span>
				</div>
				<input type="submit" class="rnd_btn ty3 gray" value="검색" title="검색">
				<div class="btn_right" style="margin-top:-28px">
					<a href="javascript:;" id="btn_download_excel" class="rnd_btn black" style='width:110px;'>엑셀 다운로드</a>
				</div>
			</td>
		</tr>
		<!-- <tr>
			<th>회원구분</th>
			<td colspan="3">
				<div class="radio_chk">
					<span class="check_wrap"><input type="radio" name="ds_usertype" id="radio1" value=""><i></i><label for="radio1">전체</label></span>
					<span class="check_wrap"><input type="radio" name="ds_usertype" id="radio2" value="A0"<?if($ds_usertype=="A0"){?> checked="checked"<?}?>><i></i><label for="radio2">개인회원</label></span>
					<span class="check_wrap"><input type="radio" name="ds_usertype" id="radio3" value="B0"<?if($ds_usertype=="B0"){?> checked="checked"<?}?>><i></i><label for="radio3">사업자회원</label></span>
					<span class="check_wrap"><input type="radio" name="ds_usertype" id="radio4" value="C0"<?if($ds_usertype=="C0"){?> checked="checked"<?}?>><i></i><label for="radio4">비회원</label></span>
				</div>
				<input type="submit" class="rnd_btn ty3 gray" value="검색" title="검색">

				<div class="btn_right" style="margin-top:-28px">
					<a href="javascript:;" id="btn_download_excel" class="rnd_btn black" style='width:110px;'>엑셀 다운로드</a>
				</div>
			</td>
		</tr> -->
	</table>
</form>
	<div class="select_view_type">
		<span class="select" style="width:160px;" id="selSort">
			<select id="page_sort">
				<option value=""<? if($PageSort==""){ ?> selected<? } ?>>정렬</option>
				<!-- <option value="s.dt_update|asc"<? if($PageSort=="s.dt_update|asc"){ ?> selected<? } ?>>수정일자 ↑</option>
				<option value="s.dt_update|desc"<? if($PageSort=="s.dt_update|desc"){ ?> selected<? } ?>>수정일자 ↓</option>
				<option value="s.dt_insert|asc"<? if($PageSort=="s.dt_insert|asc"){ ?> selected<? } ?>>등록일자 ↑</option>
				<option value="s.dt_insert|desc"<? if($PageSort=="s.dt_insert|desc"){ ?> selected<? } ?>>등록일자 ↓</option> -->
				<option value="s.dt_insert|asc"<? if($PageSort=="s.dt_insert|asc"){ ?> selected<? } ?>>등록일 높은순</option>
				<option value="s.dt_insert|desc"<? if($PageSort=="s.dt_insert|desc"){ ?> selected<? } ?>>등록일 낮은순</option>
			</select>
		</span>
	</div>

	<div class="tbl_wrap">
		<table class="tbl_list ty2">
			<colgroup>
				<col width="5%">
				<col width="8%">
				<col width="*">
				<col width="9%">
				<col width="11%">
				<col width="7%">
				<!-- <col width="7%"> -->
				<col width="9%">
				<col width="9%">
				<!-- <col width="9%">
				<col width="9%"> -->
				<col width="9%">

			</colgroup>
			<thead>
			<tr>
				<th>No</th>
				<th>판매자</th>
				<th>차종</th>
				<th>차량번호</th>
				<th>주행거리</th>
				<th>색상</th>
				<!-- <th>변속기</th> -->
				<th>판매지역</th>
            	<th>판매시간</th>
				<!-- <th>수정일</th> -->
				<th>등록일</th>
				<th>초기화</th>
                <th>내역초기화</th>

                <!-- <th>재입찰</th>
                <th>재입찰</th> -->
			</tr>
			</thead>
<?
if($totalrows>0) {

//ds_status E0의 매물 갯수가 많으면 10초 걸려서 쿼리 튜닝
// $r = mysql_query("SELECT
// 						a.*
// 						, b.nm_model
// 						, c.nm_grade
// 						, d.nm_brand
// 						, e.nm_model_sub
// 						, getCode('car_master','ds_type',a.ds_type) as nm_type
// 						, getCode('car_master','ds_open',a.ds_open) as nm_open
// 						, getCode('car_master','ds_sales',a.ds_sales) as nm_sales
// 						, getCode('car_master','ds_transmission',a.ds_transmission) as nm_transmission
// 						, getCode('member_master','ds_area',s.ds_area) as nm_area
// 						, getCode('sale_master','ds_status',s.ds_status) as nm_status
// 						, s.cd_sale
// 						, s.nm_name nm_name_sale
// 						, s.nm_recommend nm_recommend_sale
// 						, s.ds_status ds_status_sale
// 						, s.ds_status_contract ds_status_contract_sale
// 						, getRemainTimeByPhase(".LIMIT_TIME_TENDER.", ".LIMIT_TIME_SELL.", s.dt_approve, now()) as time_limit_sell
// 						, s.dt_update dt_update_sale
// 						, s.dt_insert dt_insert_sale
// 						FROM sale_master s
// 							inner join car_master a on (s.cd_car = a.cd_car)
// 							left outer join car_model b on (a.cd_model = b.cd_model)
// 							left outer join car_grade c on (a.cd_grade = c.cd_grade)
// 							left outer join car_brand d on (a.cd_brand = d.cd_brand)
// 							left outer join car_model_sub e on (a.cd_model_sub = e.cd_model_sub)
// 							$sql $orderby LIMIT $pagestartpoint,$PageSize");



$sql = "SELECT *
			, getCode('car_master','ds_type',ds_type) as nm_type
			, getCode('car_master','ds_open',ds_open) as nm_open
			, getCode('car_master','ds_sales',ds_sales) as nm_sales
			, getCode('car_master','ds_transmission',ds_transmission) as nm_transmission
			, getCode('member_master','ds_area',ds_area_sale) as nm_area
			, getCode('sale_master','ds_status',ds_status_sale) as nm_status
 			-- , getRemainTimeByPhase(".LIMIT_TIME_TENDER.", ".LIMIT_TIME_SELL.", dt_approve_sale, now()) as time_limit_sell
			-- , getRemainTimeByPhase(ds_auction_time, ".LIMIT_TIME_SELL.", dt_approve_sale, now()) as time_limit_sell
			, getRemainTimeByPhase(ds_auction_time, ds_auction_time, dt_approve_sale, now()) as time_limit_sell
			FROM (
					SELECT
						a.*
						, b.nm_model
						, d.nm_brand
						, s.cd_sale
						, s.nm_name nm_name_sale
						, s.nm_recommend nm_recommend_sale
						, s.ds_status ds_status_sale
						, s.ds_status_contract ds_status_contract_sale
						, s.ds_area ds_area_sale
						, s.dt_approve dt_approve_sale
						, s.dt_update dt_update_sale
						, s.dt_insert dt_insert_sale
						, s.ds_auction_time
						, sa.nm_name sa_nm_name
						FROM sale_master s
							inner join car_master a on (s.cd_car = a.cd_car)
							left outer join car_model b on (a.cd_model = b.cd_model)
							left outer join car_brand d on (a.cd_brand = d.cd_brand)
							left outer join sa_master sa on (s.nm_name = sa.nm_name)
							$add_sql $orderby LIMIT $pagestartpoint,$PageSize


		) as car";


if($_SERVER['REMOTE_ADDR'] == '220.86.24.199') {
	// echo $sql;
	// exit;
}
// echo $sql;
$r = mysql_query($sql);



if($_SERVER['REMOTE_ADDR'] == '106.251.80.237') {

//  $is_staff 	= $col['is_staff'];
//
//  $sa = array();
//  if($is_staff == 'Y') {
//    $sa_sql ="SELECT * FROM sa_master ";
//    $sa = mysql_fetch_array(mysql_query($sa_sql));
//  }
//  echo var_dump($sa);


}



$i=1;
while($col = mysql_fetch_array($r)) {

	$tmpNum =$totalrows-($PageSize*($PageNo-1));
	$no = ($tmpNum - $i)+1;

  if($_SERVER['REMOTE_ADDR'] == '106.251.80.237') {
   // var_dump($col);
  }
?>

			<tr cd_sale='<?=$col['cd_sale']?>' uri='./buy_view.php?list_url=<?=$list_url?>&cd_sale=<?=$col['cd_sale']?>&ds_status_sale=<?=$col['ds_status_sale']?>&ds_status_contract_sale=<?=$col['ds_status_contract_sale']?>&ListPageNo=<?=$PageNo?>' _onclick="location.href=;" style="cursor:pointer;">
				<td><?=$no?></td>
				<td><?=$col['nm_name_sale']." ".$col['sa_nm_name']?></td>
				<td><?=$col['nm_brand']." ".$col['nm_model']?></td>
				<td><?=$col['nm_number']?></td>
				<td><?=$col['nm_mileage']?>km</td>
				<td><?=$col['nm_color']?></td>
				<!-- <td><?=$col['nm_transmission']?></td> -->
				<td><?=$col['nm_area']?></td>
                <td><?=$col['time_limit_sell']?></td>

				<td><?=$col['dt_insert_sale']?></td>
				<!-- <td><?=$col['dt_update_sale']?></td> -->
            	<td class='time_reset'>입찰시간 초기화</td>
                <td class='time_history_reset'>입찰시간 및 내역 초기화</td>
			</tr>
<?
	$i++;
}
}else{
?>
			<tr>
				<td colspan="11">등록된 정보가 없습니다.</td>
			</tr>
<?
}
?>
		</table>
	</div>

	<div class="paging">
		<?php
				$url = "./$list_url?searchtype=$searchtype&searchword=$searchword&ds_status=$ds_status&ds_usertype=$ds_usertype&dt_start=$dt_start&dt_end=$dt_end&PageSort=$PageSort";
				ListPg1($url ,$PageNo,$PageSize,10,$totalrows,$leftboard[1],$rootpath);
		?>
	</div>


	<!-- layer popup1 -->
	<div class="layer_popup reset1_popup">
		<form id="frmFormResetTime" name="frmFormResetTime" method="post" enctype="multipart/form-data">
		<input type="hidden" name="cd_sale" value="">
			<div class="popup_wrap" style='width: 280px;height: 120px;'>
				<h4 style='padding:40px 0 20px 0;'>입찰시간이 초기화 됩니다</h4>
				<div class="btn_center">
					<a href="#" class="rnd_btn ty3 gray" onclick="closeLayer('reset1'); return false;">취소</a>
					<a href="#" class="rnd_btn ty3 black" id="btn_time_reset">확인</a>
				</div>
			</div>
		</form>
		<div class="close">레이어팝업 닫기</div>
	</div>
	<!-- // layer popup1 -->

	<!-- layer popup2 -->
	<div class="layer_popup reset2_popup">
		<form id="frmFormResetTimeHistory" name="frmFormResetTimeHistory" method="post" enctype="multipart/form-data">
		<input type="hidden" name="cd_sale" value="">
			<div class="popup_wrap" style='width: 280px;height: 120px;'>
				<h4 style='padding:40px 0 20px 0;'>입찰 시간 및 입찰내역이 초기화 됩니다</h4>
				<div class="btn_center">
					<a href="#" class="rnd_btn ty3 gray" onclick="closeLayer('reset2'); return false;">취소</a>
					<a href="#" class="rnd_btn ty3 black" id="btn_time_history_reset">확인</a>
				</div>
			</div>
		</form>
		<div class="close">레이어팝업 닫기</div>
	</div>
	<!-- // layer popup2 -->

</section>


<form name="excelForm" id="excelForm" method="GET">
	<input type="hidden" name="searchtype" value="<?=$searchtype?>">
	<input type="hidden" name="searchword" value="<?=$searchword?>">
	<input type="hidden" name="ds_usertype" value="<?=$ds_usertype?>">
	<input type="hidden" name="dt_start" value="<?=$dt_start?>">
	<input type="hidden" name="dt_end" value="<?=$dt_end?>">
</form>


<script language="javascript" type="text/javascript">


	$(document).ready(function() {

		$("#dt_start").datepicker({ dateFormat: 'yy-mm-dd' });
		$("#dt_end").datepicker({ dateFormat: 'yy-mm-dd' });

		$("#btn_cal1").bind("click",function(){
			$("#dt_start").datepicker('show');
		});

		$("#btn_cal2").bind("click",function(){
			$("#dt_end").datepicker('show');
		});

		$(".tbl_wrap td").on("click", function() {
			var cd_sale = $(this).closest("tr").attr("cd_sale");
			if($(this).hasClass('time_reset')) {
				var custom_opts = {
					title : '',
					btn_close_show : false,
				}
				var $parent = $(this).closest("tr");
				var cd_sale = $parent.attr("cd_sale");

				custom_opts.title = '입찰시간을 초기화 하시겠습니까?\n실행후에는 복구 할 수 없습니다';
				custom_modal_confirm(custom_opts, function(confirm) {
					if(confirm) {

						var data = { mode:"resetTime", cd_sale: cd_sale}
						$.ajax({
							url: "proc.php",
							type: 'post',
							data: data,
							dataType: 'json',
							success: function(res) {
								custom_modal_confirm_close();

								if(res.CODE != "0000") {
									custom_opts.title = res.MSG;//'실패하였습니다. 다시 시도해 주세요.';
									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){
								custom_modal_confirm_close();

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

					}else {
						return false;
					}
				});

				// $("#frmFormResetTime input[name=cd_sale]").val(cd_sale);
				// openLayer('reset1');

			}
			else if($(this).hasClass('time_history_reset')) {
				var custom_opts = {
					title : '',
					btn_close_show : false,
				}
				var $parent = $(this).closest("tr");
				var cd_sale = $parent.attr("cd_sale");

				custom_opts.title = '입찰시간 및 내역을 초기화 하시겠습니까?\n실행후에는 복구 할 수 없습니다';
				custom_modal_confirm(custom_opts, function(confirm) {
					if(confirm) {
						var data = { mode:"resetTimeHistory", cd_sale: cd_sale}
						$.ajax({
							url: "proc.php",
							type: 'post',
							data: data,
							dataType: 'json',
							success: function(res) {
								custom_modal_confirm_close();

								if(res.CODE != "0000") {
									custom_opts.title = res.MSG;//'실패하였습니다. 다시 시도해 주세요.';
									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){
								custom_modal_confirm_close();

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

					}else {
						return false;
					}
				});
				//
				// $("#frmFormResetTimeHistory input[name=cd_sale]").val(cd_sale);
				//
				// openLayer('reset2');

			}else {
				var uri = $(this).closest("tr").attr("uri");
				if(typeof uri != "undefined") {
					window.location.href = uri;
				}
			}
		});

		// $("#btn_time_reset").on("click", function() {
		//
		//
		// 	if(confirm('초기화 하시겠습니까? 실행후에는 복구 할 수 없습니다.')) {
		// 		var arg_cd_sale = $("#frmFormResetTime input[name=cd_sale]").val();
		//
		// 		$.post("proc.php", { mode:"resetTime", cd_sale: arg_cd_sale},function(data) {
		// 			if(data=="Y"){
		// 				alert("정상적으로 처리되었습니다.");
		// 				window.location.reload();
		// 				return;
		// 			}else{
		// 				alert("정상적으로 처리되지 않았습니다.");
		// 				return;
		// 			}
		// 		});
		// 	}
		// });
		$("#btn_time_history_reset").on("click", function() {
			// if(confirm('초기화 하시겠습니까? 실행후에는 복구 할 수 없습니다.')) {
			// 	var arg_cd_sale = $("#frmFormResetTimeHistory input[name=cd_sale]").val();
			//
			// 	$.post("proc.php", { mode:"resetTimeHistory", cd_sale: arg_cd_sale},function(data) {
			// 		if(data=="Y"){
			// 			alert("정상적으로 처리되었습니다.");
			// 			window.location.reload();
			// 			return;
			// 		}else if(data=="NO"){
			// 			alert("초기화는 완료 됐으나 사고보험정보를 가져오지 못해 갱신처리 되지 않았습니다.");
			// 			window.location.reload();
			// 			return;
			// 		}else{
			// 			alert("정상적으로 처리되지 않았습니다.");
			// 			return;
			// 		}
			// 	});
			// }
		});
		$("#selSort div.jq_sel ul li a").bind("click",function(){
//			alert(this.value);
//			$("#PageSort").val(this.value);
			$("#PageSort").val($("#selSort option:selected").val());

			$("#frmSearch").submit();

		});

		$("#sel_searchtype div.jq_sel ul li a").bind("click",function(){
			$("#searchtype").val($("#sel_searchtype option:selected").val());

		});

	});

	function fnSearch(){
		if($("#searchtype").val()!="" && $("#searchword").val()==""){
			alert("검색어를 입력하세요");
			return false;
		}
		$("#frmSearch").submit();
	}

	console.log($("#excelForm").serialize())

	$("#btn_download_excel").click(function(e) {
		var url = "prepare_list_excel.php?"+$("#excelForm").serialize();
		window.open(url, "excelWin");
	});

</script>

<? include("../inc/inc_footer.php") ?>
<? include("../inc/inc_bottom.php") ?>
<?
mysql_close($connect);
?>
