<?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');
	
	$list = getgpc('list');
	$list = is_array($list) ? implode(",", $list) : $list;
	
	if ($action){
		
		switch($action){
			
			case "all":
			
				System :: $db -> execute( "UPDATE `mod:adsarea` SET config='{}' WHERE config = ''" );
				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(".$list.")");
				$_G['project']['message']="已生成所选广告！";
				
			break;
			
			case "delete":
				
				//检查权限
				System :: check_func("mod-adsarea-del", false );
				System :: check_func("mod-adsview-del", false );
				
				//直接删除不经过回收站
				if( System :: check_func('sys-system-recycle') ){
					
					Adsview :: delete("SELECT * FROM `mod:adsarea` WHERE id in(".$list.")",$mysql);
				
					//清空统计
					Module :: loader( 'analytic' );
					Analytic :: clear( $appid, $list );
					
				}else{
				
					$sql="UPDATE `mod:adsarea` SET `state`=-1 WHERE id in(".$list.")";
					System :: $db -> execute( $sql );				
					
				}				
				
				$_G['project']['message']="成功删除广告分类！";
				
			break;
			
			case "cache":

			break;
		}
		
		//更新分类数组缓存
		Cached :: table( $appid, 'mod:adsarea', array( 'jsonde' => array('config') ) );		
		
		//更新分类脚本缓存
		Cached :: script( $appid,"SELECT id,parent,name,`show`,width,height,number,`key`,config FROM `mod:adsarea` WHERE parent>0","ADSAREA","mod.adsarea",array( 'record'=>' #var[{table:id}] = {"id":{table:id},"parent":{table:parent},"name":"{table:name}","show":{table:show},"size":"{table:width}×{table:height}","number":{table:number},"key":"{table:key}","config":{table:config}};'.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="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>
                
                <select name="sel" id="sel" onchange="Mo('#formSeacrh').submit();" ignore="true">
                    <optgroup label="筛选状态.." />
                    <option value="">全部位置</option>
                    <option value="free">空闲位置</option>
                    <option value="full">已满位置</option>
                    <option value="space">零广告位置</option>
                    <option value="zero">零预定位置</option>
                    <option value="engage">被预定位置</option>
                    <option value="expire">快到期位置</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>
                <option value="show">广告类型</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("#sel").value("<?php echo $sel;?>");
			Mo("#parent").value("<?php echo $parent;?>");
        </script>
	</div>
    
    
    <!--用于动作处理_开始-->
    <form name="formPost" id="formPost" method="post">
        <input name="action" id="action" type="hidden" value="" />        
        <input name="state" id="state" type="hidden" value="" />
        
        <input name="jump" type="hidden" value="" />
        <script>Mo('#formPost input[name=jump]').value( location.href );</script>
    
	<?php
    
    $sql="SELECT * FROM `mod:adsarea` WHERE 1=1 ";

    if ($q && $s){
        
        if( strpos($s,"id") !== false ){
            $sql.=" and  `".$s."` = ".$q;
        }else{
            $sql.=" and  `".$s."` like '%".$q."%'";
        }     
        
    }

    //显示回收站
    if( System :: check_func('sys-system-recycle') == false ) $sql.=" and state > -1 ";    
    
    if ($parent){
        $sql.=" and  parent ='".$parent."'";
    }else{
        $sql.=" and  parent >0";
    }
    
    $sql.=" {$sel} order BY parent desc, name";
    
    //广告筛选
    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="70">操作</td>
          </tr>
        <?php
        
        $result = System :: $db -> getAll( $sql );
        
        $i=0;
        
        foreach( $result as $row ){
            
            //已有广告数
            $sql="SELECT count(id) FROM `mod:adsview` WHERE `state`>0 and type=".$row['id']." and expire>".time();
            $count_adsview = System :: $db -> getValue($sql);
            
            //现有预定
            $sql="SELECT count(id) FROM `mod:adsview` WHERE `state`=3 and engage=1 and type=".$row['id']." and expire>".time();
            $count_engage = System :: $db -> getValue($sql);
            
            //找到最近到期的广告
            //$sql="SELECT expire FROM `mod:adsview` WHERE `state`>0 and type=".$row['id']." ORDER BY expire asc";
			//$first_expire= System :: $db -> getValue($sql);
            
            //统计快要到期的广告
            $sql="SELECT count(id) FROM `mod:adsview` WHERE `state`>0 and spare=0 and type=".$row['id']." and expire<". (time() + (3600*24*$_G['setting'][$appid]["expire"]) ) ." and expire>". time() ." ";			
            $count_expire = System :: $db -> getValue($sql);
            
            echo '
            <tr class="'.zebra( $i, array( "line" , "band" ) ).'" edit="adsarea.edit.php?action=edit&id='.$row['id'].'&jump={jump}">
                <td>
                    <input name="list[]" type="checkbox" class="checkbox" 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>
                    ';
                    
                    if( $row["quote"] ){
                        echo ' <a href="'.$row["quote"].'#vad_'.$row["key"].'" target="_blank" title="'.$row["key"].'">'.loader_image("link.gif","定位").'</a>';
                    }
                    
                    if($row['state']==-1){
                        echo '<sup class="text-yes">[回收站]</sup>';
                    }
                    
                echo '
                </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>'.($count_adsview ? $count_adsview : '<span class="text-yes">'.$count_adsview.'</span>').'</td>
                <td>'.(($row["number"]- $count_adsview) ? '<span class="text-no">'.($row["number"]- $count_adsview).'</span>' : ($row["number"]- $count_adsview)).'</td>
                <td>'.($count_expire ? '<span class="text-no">'.$count_expire.'</span>' : $count_expire).'</td>
                <td>'.($count_engage ? '<span class="text-no">'.$count_engage.'</span>' : $count_engage).'</td>
                <td>'.$row["width"].'×'.$row["height"].'</td>
                <td><a href="?s=show&q='.$row["show"].'">'.$_G['module']['adsview']["type"][$row["show"]].'</a></td>
                <td>
                    <a href="adsarea.code.php?id='.$row['id'].'&key='.$row["key"].'" onclick="parent.Serv.Dialog( \'dialog\',\'广告代码\', \'<iframe src=\'+this.href+\' frameborder=0></iframe>\' ,\'90%\',\'510\',{ \'remove\' : true, \'draged\' : true, \'create\' : true }); return false;">代码</a>
                    /
                    <a href="adsview.preview.php?action=channel&key='.$row["key"].'&show='.$row["show"].'" onclick="parent.Serv.Dialog( \'dialog\',\'广告代码\', \'<iframe src=\'+this.href+\' frameborder=0></iframe>\' ,\'90%\',\'510\',{ \'remove\' : true, \'draged\' : true, \'create\' : true }); 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>
            ';

        }
	
	if( count( $result ) == 0 ){
		echo '<tr><td colspan="15" class="notice">没有检索到相关广告位，<a href="adsarea.edit.php?model=box">创建一个？</a></td></tr>';
	}
	
        ?>
      <tr class="line">
        <td colspan="15"><?php echo $_G['module']['adsview']['tool'];?></td>
      </tr>
            
	</table>
	<?php
	//关闭数据库
	System :: connect();
    ?>
    </form>
    <!--用于动作处理_结束-->
    
    <div id="saving">
		<?php
            echo multipage($page,$row_count,$_G['setting']['global']['pagesize'],$url,"page");
        ?>
    </div>

<!--body end-->

<?php html_close();?>