<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	$Id: ,v1 10:39 2008-9-19 Lay $
*/

require '../../include/loader.php';

html_start("广告位排期 - VeryIDE");
?>

<!--body start-->
<?php

	//module
	require 'naver.php';
	
	Cached :: loader($appid,"table.adsarea");
	
	//连接数据库
	System :: connect();

	//***********************
	$sel = getgpc("sel");
	
	$q = getgpc('q');
	$s = getgpc("s");
	$e = getgpc("e");
	if(!$e){
		$e="none";
	}
	$parent = getgpc("parent");
	
	$action = getgpc('action');
	
	$a_list = getgpc('list');
	
	if ($action){
		
		switch($action){
			case "all":
				Adsview :: create("SELECT * FROM `mod:adsarea` WHERE parent>0 ORDER BY id");
				$_G['project']['message']="已更新所有文件！";
			break;
			
			case "create":
				Adsview :: create("SELECT * FROM `mod:adsarea` WHERE id in(".$a_list.")");
				$_G['project']['message']="已生成所选广告！";
			break;
			
			case "delete":
				
				//检查权限
				System :: check_func("mod-adsarea-del", false );
				System :: check_func("mod-adsview-del", false );
			
				ad_delete("SELECT * FROM `mod:adsarea` WHERE id in(".$a_list.")");
				$_G['project']['message']="成功删除广告分类！";
			break;
			
			case "cache":

			break;
		}
		
		//更新分类数组缓存
		Cached :: table( $appid, 'mod:adsarea',array( 'jsonde' => array('config') ));		
		
		//更新分类脚本缓存
		Cached :: script( $appid,"SELECT id,name,parent FROM `mod:adsarea` WHERE parent>0","ADSAREA","mod.adsarea",array( 'record'=>' #var[{table:id}] = new Array({table:id},{table:parent},"{table:name}");'.chr(13) ) );
		
		//转到
		if( $jump ){
			System :: redirect($jump,"成功能更新缓存!");
		}
	}
?>

	
    <!--div id="board">
        <p><b>排序显示说明</b>  
        <br>以下列表按 <b class="text-key">频道</b> 进行分类并（依据添加先后进行倒序，ID从大到小）排序显示管理 
        </p>
    </div-->
	
    <div id="search">
        <!--用于动作处理_开始-->
		<form name="formPost" id="formPost" method="post" action="?">
		   <input name="list" id="list" type="hidden" value="">
			<input name="action" id="action" type="hidden" value="" />
			<input name="url" id="url" type="hidden" value="" />
        </form>
         <!--用于动作处理_结束-->
        
	    <form name="formSeacrh" id="formSeacrh" method="get" action="">
            <span class="action">
                <select name="parent" id="parent" onchange="Mo('#formSeacrh').submit();" ignore="true">
                    <optgroup label="筛选分类.." />
                    <option value="0">全部分类..</option>
                    <?php
                        foreach($_CACHE['adsview']['adsarea'] as $key){
                            if($key["parent"]=="0"){
                                echo '<option value="'.$key["id"].'">'.$key["name"].'</option>';
                            }
                        }
                    ?>
                </select>
              <input type="button" value="更新缓存" onclick="if(confirm('确定现在更新广告缓存吗？')){location.href='?action=all';}" class='button'>
            </span>
            
            <select name="s" id="s">
                <option value="key">位置标识</option>
                <option value="name" checked>广告位</option>
                <option value="account">添加人</option>
                <option value="link">所在页面</option>
            </select>
            含有
            <input name="q" type="text" class="text" id="q" value="<?php echo $q;?>">
            <button class="go" type="submit"></button>
	    </form>
        <script type="text/javascript">
			Mo("#s").value("<?php echo $s;?>");
			Mo("#parent").value("<?php echo $parent;?>");
					
			Mo.reader(
				function(){
					
					/*滚动表头*/
					window.setInterval(function(){
						Mo.Thead("thead");
					},100);
					
					/*筛选表格*/
					Mo.Table($T("table")[0],
						[
							'mousedown',function(o,event){
								var target=(event.srcElement ? event.srcElement : event.target);
								var pid = o.getAttribute("pid");
								var obj = $('id-'+pid);
								
								if(!pid || target==obj){return false;};
								
								obj.click(); if(obj.checked){o.style.background='#eee';}else{o.style.background='#fff';}
								
							},
							'dblclick',function(o,event){
								var pid = o.getAttribute("pid");
								location.href='adsarea.edit.php?action=edit&id='+pid+'&jump='+encodeURIComponent(location.href);
							}
						]
					);
					
				}
			);
        </script>
	</div>
    
		<!--up-->
		<?php
		
		$sql="SELECT * FROM `mod:adsarea` WHERE 1=1 ";
		if ($s && $q){
			$sql.=" and  `".$s."` like '%".$q."%'";
		}
		
		if ($parent){
			$sql.=" and  parent ='".$parent."'";
		}else{
			$sql.=" and  parent >0";
		}
		
		$sql.=" {$sel} order BY parent desc";
		
		//广告筛选
		switch($sel){
			//全部
			case "":
			
			break;
			
			//空闲
			case "free":
				$sql = str_replace("{$sel}"," and (`mod:adsarea`.number-(SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`>0 and `mod:adsview`.type=`mod:adsarea`.id and `mod:adsview`.expire>".time()."))>0",$sql);
			break;
			
			//被预定
			case "engage":
				$sql = str_replace("{$sel}"," and ((SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`=3 and `mod:adsview`.type=`mod:adsarea`.id and `mod:adsview`.expire>".time()." ORDER BY `mod:adsview`.sort asc,`mod:adsview`.id desc))>0",$sql);
			break;
			
			//空广告位
			case "space":
				$sql = str_replace("{$sel}"," and ((SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`>0 and `mod:adsview`.type=`mod:adsarea`.id and `mod:adsview`.expire>".time()." ORDER BY `mod:adsview`.sort asc,`mod:adsview`.id desc)=0)",$sql);
			break;
			
			//零预定
			case "zero":
				$sql = str_replace("{$sel}"," and ((SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`=3 and `mod:adsview`.type=`mod:adsarea`.id and `mod:adsview`.expire>".time()." ORDER BY `mod:adsview`.sort asc,`mod:adsview`.id desc)=0)",$sql);
			break;
			
			//已满
			case "full":
				$sql = str_replace("{$sel}"," and (`mod:adsarea`.number-(SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`>0 and `mod:adsview`.type=`mod:adsarea`.id and `mod:adsview`.expire>".time()." ORDER BY `mod:adsview`.sort asc,`mod:adsview`.id desc))=0",$sql);
			break;
			
			//快到期
			case "expire":
				$sql = str_replace("{$sel}"," and ((SELECT count(`mod:adsview`.id) FROM `mod:adsview` WHERE `mod:adsview`.`state`>0 and `mod:adsview`.type=`mod:adsarea`.id and `state`>0 and spare=0 and `mod:adsview`.expire<". (time() + (3600*24*$_G['setting'][$appid]["expire"]) ) ." and `mod:adsview`.expire>".mktime()." ORDER BY `mod:adsview`.sort asc,`mod:adsview`.id desc))>0",$sql);
			break;
		}

		//查询数据库_总记录数
		$row_count = System :: $db -> getCount( $sql );

		//分页参数
		$page=getpage("page");
		$page_start=$_G['setting']['global']['pagesize']*($page-1);
		$sql=$sql." limit $page_start,".$_G['setting']['global']['pagesize'];		
		
		//分页链接
		$url="?s=".$s."&q=$q&e=$e&parent=$parent&id=$id&sel=$sel&page=";

		?>
            <table id="table" width="100%" border="0" cellpadding="1" cellspacing="1" class="table">
              <tr class="title" id="thead">
                <td width="30"></td>
                <td>预览</td>
                <td>所在频道</td>
                <td>广告位名称</td>
                <td>标识<script type="text/javascript">Mo.Tools("Tip","每个频道与广告位都有一个唯一标识，它们不会重名");</script></td>
                <td>价格</td>
                <td>最多</td>
                <td>现有</td>
                <td>空闲</td>
                <td>快到期</td>
                <td>已预定</td>
                <td>尺寸</td>
                <td>类型</td>
                <td>扩展</td>
                <td width="50">操作</td>
              </tr>
            <?php
            
            $result = System :: $db -> getAll( $sql );
			
			
            
            $i=0;
            
            foreach( $result as $row ){
                
                //已有广告数
                $sql="SELECT * FROM `mod:adsview` WHERE `state`>0 and type=".$row['id']." and expire>".time()." ORDER BY sort asc,id desc ";
                
                $ad_count = System :: $db -> getCount( $sql );
                
                //找到最近到期的广告
                $sql="SELECT expire FROM `mod:adsview` WHERE `state`>0 and type=".$row['id']." and expire>".time()." ORDER BY expire asc limit 0,1 ";
				
                $a_firsexpire = System :: $db -> getCount( $sql );
                
                //统计快要到期的广告
                $sql="SELECT count(id) as a_count FROM `mod:adsview` WHERE `state`>0 and spare=0 and id=".$row['id']." and expire<". (time() + (3600 * 24 * $_G['setting'][$appid]["expire"]) ) ." and expire>". time() ." ";
                
                $a_counexpire = System :: $db -> getCount( $sql );
                
                //现有预定
                $sql="SELECT * FROM `mod:adsview` WHERE `state`=3 and type=".$row['id']." and expire>".time()." ORDER BY sort asc,id desc ";
                
                $ad_engage = System :: $db -> getCount( $sql );
				
                echo '
                <tr class="line" pid="'.$row['id'].'">
					<td>
						<input name="id" type="checkbox" class="checkbox" id="id-'.$row['id'].'" value="'.$row['id'].'">
					</td>
					<td>';
					
					if( $row["preview"] ){
						echo '<a href="'.$row["preview"].'" target="_blank">[查看]</a>';
					}else{
						echo '无';
					}
					
					echo '</td>
					<td><a href="?parent='.$row["parent"].'">'.$_CACHE['adsview']['adsarea'][$row["parent"]]["name"].'</a></td>
					<td>
						<a href="adsview.list.php?parent='.$row["parent"].'&type='.$row['id'].'" title="'.$row["key"].'">'.$row['name'].'</a> [<a href="'.$row['link'].'" target="_blank" title="'.$row["key"].'">定位</a>]
					</td>
					<td>'.$row["key"].'</td>
					<td align="right"><span class="text-yes">'.number_format($row["price"]).'/'.$row["unit"].'</span></td>
					<td>'.($row["number"] ? $row["number"] : '<span class="text-no">'.$row["number"].'</span>').'</td>
					<td>'.($ad_count ? $ad_count : '<span class="text-yes">'.$ad_count.'</span>').'</td>
					<td>'.(($number- $ad_count) ? '<span class="text-no">'.($row["number"]- $ad_count).'</span>' : ($row["number"]- $ad_count)).'</td>
					<td>'.($a_counexpire ? '<span class="text-no">'.$a_counexpire.'</span>' : $a_counexpire).'</td>
					<td>'.($ad_engage ? '<span class="text-no">'.$ad_engage.'</span>' : $ad_engage).'</td>
					<td>'.$row["width"].'*'.$row["height"].'</td>
					<td>'.$_G['module']['adsview']["type"][$row["show"]].'</td>
					<td>
						<a href="adsarea.code.php?id='.$row['id'].'&key='.$row["key"].'" onclick="parent.Mo.Window(\'window\',\'引用广告代码\' ,this.href ,\'900\',\'500\',{}); return false;">代码</a>
						/
						<a href="adsview.preview.php?action=channel&key='.$row["key"].'&show='.$row["show"].'" onclick="parent.Mo.Window(\'window\',\'广告位预览\' ,this.href ,\'900\',\'500\',{}); return false;">预览</a>						
					</td>
					<td>
						<script type="text/javascript">
						Mo.Tools("RsEdit","adsarea.edit.php?action=edit&id='.$row['id'].'","");
						Mo.Tools("RsDelete","?action=delete&list='.$row['id'].',","");
						</script>
					</td>
				</tr>
				';

                $i++;
            }
            ?>
          <tr class="line">
            <td colspan="15"><a href="javascript:$('list').value = setAll('#table tbody tr input',true); void(0);">全选</a> / <a href="javascript:$('list').value = setAll('#table tbody tr input',false); void(0);">全不选</a> / <a href="javascript:$('list').value = setAll('#table tbody tr input','anti'); void(0);">反选</a> - <a href="javascript:if(confirm('确定要删除所选吗?')){formPost('formPost','delete');}void(0);">删除所选</a> / <a href="javascript:formPost('formPost','create');void(0);">生成所选</a></td>
          </tr>
            
	</table>
	<?php
	//关闭数据库
	System :: connect();
    ?>
    
    <div id="saving">
		<?php
            echo multipage($page,$row_count,$_G['setting']['global']['pagesize'],$url,"page");
        ?>
    </div>

<!--body end-->

<?php html_close();?>