<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	2011/6/5 Lay
*/

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

html_start("广告管理 - VeryIDE");
?>

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

	//module
	require 'naver.php';

	//连接数据库
	System :: connect();

	//更新分类数组缓存
	if( !Cached :: loader($appid,"table.adsarea") ){
		Cached :: table( $appid, 'mod:adsarea',array( 'jsonde' => array('config') ));		
	}
	
	//***********************
	
	$sel = getgpc("sel");

	$q = getgpc('q');
	$s = getgpc("s");

	$parent = getgpc("parent");
	$type = getgpc("type");
	
	$action = getgpc('action');
	
	//批处理列表
	$list = getgpc('list');
	$list = is_array($list) ? implode(",", $list) : $list;

	//上一页
	$jump = $_POST["jump"];
	
	$full = getnum("full",-1);
	$owner = getnum("owner",0);
	
	//排序方式
	$_key = getgpc("_key");
	$_ord = getgpc("_ord");
	
	//日期筛选
	$start = getgpc('start');
	$end = getgpc('end');

	//时间
	if ($start && $end){
		$ect.=" and  expire >=".strtotime($start)." and expire <= ".strtotime($end.' 23:59:59');
	}
	
	switch($action){
		//删除
		case "delete":
		
			//检查权限
			System :: check_func("mod-adsview-del", false );
			
			//直接删除不经过回收站
			if( System :: check_func('sys-system-recycle') ){
					
				//删除本广告
				$sql="DELETE FROM `mod:adsview` WHERE id in(".$list.")";
				System :: $db -> execute( $sql );
				
				//清空统计
				Module :: loader( 'analytic' );
				Analytic :: clear( $appid, $list );
					
			}else{
			
				$sql="UPDATE `mod:adsview` SET `state`=-1,`modify`=".time().",mender='".$_SESSION['Manager']['account']."' WHERE id in(".$list.")";
				System :: $db -> execute( $sql );
				
			}
				
			//生成广告
			Adsview :: create("SELECT * FROM `mod:adsarea` WHERE parent>0");
			
			$_G['project']['message']="成功删除广告！";
			
		break;
		
		//状态
		case "state":
		
			//检查权限
			System :: check_func("mod-adsview-mod", false );		
		
			$state = getnum('state',0);
			
			$sql="UPDATE `mod:adsview` SET state=".$state.",`modify`=".time().",mender='".$_SESSION['Manager']['account']."' WHERE id in(".$list.")";
			System :: $db -> execute( $sql );
						
			//缓存广告缓存
			Cached :: rows( $appid, "SELECT * FROM `mod:adsview` WHERE id in(".$list.")", array( 'jsonde' => array('config') ) );
			
			$sql="SELECT type FROM `mod:adsview` WHERE id in(".$list.") group by type";
			
			$result = System :: $db -> getAll( $sql );

			foreach( $result as $row ){
				
				//生成广告
				Adsview :: create("SELECT * FROM `mod:adsarea` WHERE id =".$row["type"]);
			}
			
			System :: redirect($jump,"广告更新成功!");
			
		break;
		
		//延期
		case "delay":
		
			//检查权限
			System :: check_func("mod-adsview-mod", false );		
		
			$delay = getnum("delay",0);
			
			$sql="UPDATE `mod:adsview` SET expire=expire+".$delay.",`modify`=".time().",mender='".$_SESSION['Manager']['account']."' WHERE id in(".$list.")";
			System :: $db -> execute( $sql );
						
			//缓存广告缓存
			Cached :: rows( $appid, "SELECT * FROM `mod:adsview` WHERE id in(".$list.")", array( 'jsonde' => array('config') ) );
			
			$sql="SELECT type FROM `mod:adsview` WHERE id in(".$list.") group by type";
			
			$result = System :: $db -> getAll( $sql );

			foreach( $result as $row ){
				
				//生成广告
				Adsview :: create("SELECT * FROM `mod:adsarea` WHERE id =".$row["type"]);
			}
			
			System :: redirect($jump,"广告延期成功!");
			
		break;
		
		case "create":
			
			//生成广告
			Adsview :: create("SELECT * FROM `mod:adsarea` WHERE parent>0");
			
			//缓存广告缓存
			Cached :: rows( $appid, "SELECT * FROM `mod:adsview`", array( 'jsonde' => array('config') ) );
			
			//更新替补缓存
			Cached :: multi( $appid, "SELECT * FROM `mod:adsview` WHERE spare=1 and `state`>0 and `state`<3 ORDER BY sort asc,id desc", "table.alternate", array( 'alias'=>'alternate', 'jsonde' => array('config') ) );
			
			$_G['project']['message']="已生成所选广告！";
			
		break;
	}
	
	?>

        <?php
        echo loader_script(array(VI_BASE."js/mo.calendar.js"),"utf-8",$_G['product']['version']);    
        ?>
    
    <div id="search">
    
    <form name="formSeacrh" id="formSeacrh" method="get" action="?">
      <span class="action">
        
        <label>
        <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>
        </label>
        
        <label>
        <select name="type" id="type" onchange="Mo('#formSeacrh').submit();" ignore="true">
            <optgroup label="所在位置" />
            <option value="0">全部位置</option>
            <?php
                foreach($_CACHE['adsview']['adsarea'] as $key){
                    if($key["parent"]==$parent && $parent){
                        echo '<option value="'.$key["id"].'">'.$key["name"].'</option>';
                    }
                }
            ?>
        </select>
        </label>
      
        <select name="full" id="full" onchange="Mo('#formSeacrh').submit();" ignore="true">
            <optgroup label="收款情况" />
            <option value="-1">所有收款</option>
            <option value="0"><?php echo $_G['module']['adsview']["full"][0];?></option>
            <option value="1"><?php echo $_G['module']['adsview']["full"][1];?></option>
            <option value="2"><?php echo $_G['module']['adsview']["full"][2];?></option>
        </select>
      
        <select name="owner" id="owner" onchange="Mo('#formSeacrh').submit();" ignore="true">
            <optgroup label="所有者" />
            <option value="0">全部人员</option>
            <?php
                echo $_CACHE["sys.admin.option"];
            ?>
        </select>
        <input type="button" value="更新缓存" onclick="if(confirm('确定现在更新广告缓存吗？')){location.href='?action=create';}" class='button'>
       </span>

        <select name="s" id="s">
            <option value="name" checked>名称</option>
            <option value="id">ID</option>
            <option value="link">链接</option>
            <option value="tags">标签</option>
            <option value="zone">地区</option>
            <option value="contract">合同号</option>
            <option value="custom">客户名</option>
            <option value="account">用户</option>
        </select>
        <input name="q" type="text" class="text" title="请输入关键字" id="q" size="15" value="<?php echo $q;?>">
        
        <!--时间节点-->
        <input name="start" type="text" class="date" id="start" value="<?php echo $start;?>" size="10" readonly="true" onclick="return showCalendar(this.id,'y-mm-dd');" title="年月日" onchange="Mo('#formSeacrh').submit();">
        -
        <input name="end" type="text" class="date" id="end" value="<?php echo $end;?>" size="10" readonly="true" onclick="return showCalendar(this.id,'y-mm-dd');" title="年月日" onchange="Mo('#formSeacrh').submit();">
        <!--时间节点-->
        
        <button class="go" type="submit"></button>
    </form>
    
    </div>
    <script type="text/javascript">
    Mo("#s").value("<?php echo $s;?>");
    
    Mo("#full").value("<?php echo $full;?>");
    Mo("#owner").value("<?php echo $owner;?>");
   
    Mo.reader(
        function(){
            Mo("#type").value("<?php echo $type;?>");            
            Mo("#parent").value("<?php echo $parent;?>");
        }
    );
    </script>
    
    <!--用于动作处理_开始-->
    <form name="formPost" id="formPost" method="post">
        <input name="action" type="hidden" value="" />        
        <input name="state" type="hidden" value="" />
        <input name="delay" type="hidden" value="" />
        
        <input name="jump" type="hidden" value="" />
        <script>Mo('#formPost input[name=jump]').value( location.href );</script>
    
    <?php
    
    $sql="SELECT * FROM `mod:adsview` 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 ($type){
		
		$sql.=" and ( type=".$type." or CONCAT(',',share) like '%,".$type.",%' ) ";
		
    }elseif ($parent){
		
		$sql.=" and  parent ='".$parent."'";
    }
    
    if ($owner){
        $sql.=" and  owner ='".$owner."'";
    }
    
    //款项筛选
    switch($full){
        case 0:
            $sql.=" and  ar > pr";
        break;
        
        case 1:
            $sql.=" and  ar = pr";
        break;
        
        case 2:
            $sql.=" and  ar>0 and pr = 0";
        break;
    }
    
    //广告筛选
    switch($sel){
        //全部
        case "":
        
        break;
        
        //预定
        case "engage":
            $sql.=" and `state`=3 ";
        break;
        
        //过期预定
        case "expire-engage":
            $sql.=" and `state`=3 and expire<".time()." ";
        break;
        
        //过期
        case "expire":
            $sql.=" and expire<".time()." ";
        break;
        
        //快到期（10天内）
        case "last":
            //$sql.=" and expire < ". (time()+ (3600*24*$_G['setting'][$appid]["expire"])) ." and expire >= ". time() ." ";
			$sql.=" and expire < ". strtotime("+". $_G['setting'][$appid]["expire"] ." days", strtotime('23:59:59')) ." and expire >= ". time() ." ";
        break;
        
        //正常
        case "normal":
            $sql.=" and  `state`>0 and `state`<3 and expire>=". time() ." and start<=". time() ." ";
        break;
        
        //停用
        case "stop":
            $sql.=" and  state =0 ";
        break;
    }
    
        if ($ect) $sql.= $ect;

        //排序
        if( $_key && $_ord ){		
                $sql.=" order BY $_key $_ord";		
        }else{
                $sql.=" order BY sort asc,id desc";
        }
		
		//echo $sql;
    
        //查询数据库_总记录数
        $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'];	

        $result = System :: $db -> getAll( $sql );
    
        //分页链接
        $url="?sel=".$sel."&s=".$s."&q=$q&e=$e&type=$type&parent=$parent&full=$full&owner=$owner&start=$start&end=$end&_ord=$_ord&_key=$_key&page=";
    
    ?>

    <table width="100%" border="0" cellpadding="1" cellspacing="1" id="table" class="table">
        <?php
        if( count($result)> $_G['setting']['global']['pagesize']/2 ){
        ?>
            <tr class="thead">
                <td colspan="11" class="first">
                	<?php
					//清空排序
					if( $_key && $_ord ){
						echo '<span class="action"><a href="'.$url.$page.'">清空排序</a></span>';					
					}
					?>
                    <?php echo $_G['module']['adsview']['tool'];?>
                </td>
            </tr>
        <?php
        }
        ?>
    
        <tr class="title" id="thead">
            <td width="30">
                <script>
				Mo.Sort( "<?php echo $url.$page."&_ord={ord}&_key={key}";?>", "#", "id", "<?php echo $_key;?>", "<?php echo $_ord;?>" );
				</script>
            </td>
            <td>
                <script>
                Mo.Sort( "<?php echo $url.$page."&_ord={ord}&_key={key}";?>", "所在位置", "type", "<?php echo $_key;?>", "<?php echo $_ord;?>" );
                </script>
            </td>
            <td>
                <script>
                Mo.Sort( "<?php echo $url.$page."&_ord={ord}&_key={key}";?>", "广告名称", "name", "<?php echo $_key;?>", "<?php echo $_ord;?>" );
                </script>
            </td>
            <td>起止时间</td>
            <td>共投放</td>
            <td>
                状态            
                <script>Mo.Tools("Tip","<strong>广告状态</strong><br />已停用 广告被人为或到期自动停止<br />待播中 广告已启用,但还未被展示<br />已在播 广告正常投放中<br />预定中 广告处于预定状态,还未开始<br />已过期 广告已到期");</script></td>
            <td>
                <script>
				Mo.Sort( "<?php echo $url.$page."&_ord={ord}&_key={key}";?>", "客户名", "custom", "<?php echo $_key;?>", "<?php echo $_ord;?>" );
                </script>
            </td>
            <td>收款</td>
            <td>扩展</td>
            <td>图示</td>
            <td width="70">操作</td>
        </tr>			
        
        <?php
        
        
        
        $i=0;
        
        //今天
        $today = date("Y-m-d"); 
         
        foreach( $result as $row ){
            
            //到期倒记时
            $days=DateDiff("d",mktime(0, 0, 0, date("m"), date("j"), date("Y")),$row['expire']);

            echo '
              <tr class="'.zebra( $i, array( "line" , "band" ) ).'" mark="'.$row['id'].'" edit="adsview.edit.php?action=edit&id='.$row['id'].'&jump={jump}">
                <td>
                    <input name="list[]" type="checkbox" class="checkbox" value="'.$row['id'].'" title="'.$row['id'].'">
                </td>
                <td>
                    <a href="?parent='.$row["parent"].'">'.$_CACHE['adsview']['adsarea'][$row["parent"]]["name"].'</a> &gt; <a href="?type='.$row["type"].'">'.$_CACHE['adsview']['adsarea'][$row["type"]]["name"].'</a>
                </td>
                <td id="tips-'.$row['id'].'">
                    <script>Mo.Tools("RsFile","'.$row["file"].'","");</script>';
                    
                    if( $row['link'] ){
                        echo '<a href="'.$row['link'].'" target="_blank" title="'.$row['link'].'">'.format_substr($row['name'],22).'</a>';
                    }else{
                        echo '<span>'.format_substr($row['name'],22).'</span>';
                    }

					if($row['state']==-1){
						echo '<sup class="text-yes">[回收站]</sup>';
					}

                echo '</td>';
                
                echo '<td>'.date("y/m/d",$row['start']).' - ';
                
                    if ( $days<=$_G['module']['adsview']["expire"] && $days>-1 ){
                        echo '<span class="text-no">'.date("y/m/d",$row['expire']).'</span>';
                    }else{
                        echo date("y/m/d",$row['expire']);
                    }
                echo '</td>';
				
				echo '<td class="text-key">';
				
					echo FormatDateDiff($row['start'],$row['expire']);
					
					if( $row['expire'] > time() ){
						echo ' <span class="text-yes">(剩'.FormatDateDiff(time(),$row['expire']).')</span>';
					}
				echo '</td>';
                
                echo '<td id="mark-'.$row['id'].'">';
                    //广告状态
                    if( $row['expire']>time() ){
                        echo $_G['module']['adsview']["state"][$row['state']];
                    }else{
                        echo $_G['module']['adsview']["state"][4];
                    }
                echo '</td>';
				
				echo '
                <td onmouseover=\'Mo.Tips( this, event,"tips","合同号: '.$row["contract"].' - 所有者: <a href=&acute;?owner='.$row["owner"].'&acute;>'.$_CACHE['system']['admin'][$row["owner"]]["account"].'</a><br />客户名称：'.$row["custom"].' - 联系方式：'.$row["contact"].'<br />共投放 '.FormatDateDiff($row['start'],$row['expire']).'", "click",-20,30, { "unique" : "detail" });\'>
                    <a href="?s=custom&q='.urlencode($row["custom"]).'" title="'.$row["custom"].'">'.format_substr($row["custom"],20,true).'</a>
                    <script>Mo.Tools("Tip","'.$row["contact"].'");</script>
                </td>
                ';
                
                echo '<td>';
                    if( $row["pr"] < $row["ar"] ){
                        if( $row["pr"] == 0 ){
                            echo '<span class="text-no">'.$_G['module']['adsview']["full"][2].'</span>';
                        }else{
                            echo '<span class="text-no">'.$_G['module']['adsview']["full"][0].'</span>';
                        }
                    }else{
                        echo '<span class="text-yes">'.$_G['module']['adsview']["full"][1].'</span>';
                    }
                echo '</td>';                
				
				echo '
                <td>                
                    '.loader_image("icon/statistics.png","数据统计","","new parent.Mo.Dialog('dialog','统计分析', '<iframe src=".VI_BASE."module/analytic/analytic.show.php?appid=".$appid."&id=".$row['id']."&type=views,clicks&name=".urlencode($row['name'])." frameborder=0></iframe>' ,'900','500',{'remove' : true, 'draged' : true, 'create' : true}); return false;").'                    
                    '.loader_image("icon/monitor.png","广告预览","","new parent.Mo.Dialog('dialog','广告预览' ,'<iframe src=".VI_BASE."module/adsview/adsview.preview.php?action=ad&id=".$row['id']." frameborder=0></iframe>' ,'90%','500',{'remove' : true, 'draged' : true, 'create' : true}); return false;").'
                
                    <!--a href="javascript:_adWindow(\'ad.info\','.$id.',\''.$a_name.'\');" title="广告详细情况">详情</a> / 
                    <a href="javascript:_adWindow(\'ad.analyze\','.$id.',\''.$a_name.'\');" title="广告点击效果">效果</a> / 
                    <a href="javascript:_adWindow(\'ad.type.code\','.$type.',\''.$array_config["T".$type].'\');" title="广告调用代码">代码</a> / 
                    <a href="javascript:_adWindow(\'ad.link\','.$id.',\''.$a_name.'\');" title="广告链出地址">链出</a-->
                </td>
                <td>'
                    .(date('Y-m-d',$expire)==$today?loader_image("icon/warning.png","今天到期"):'')
                    .($row['form']?loader_image("icon/code.png","代码广告"):'')
                    .($row['spare']?loader_image("icon/ball.png","替补广告"):'')
                    .($row["area"]?loader_image("icon/globe.png","地区限制"):'')
                    .($row["share"]?loader_image("icon/folder.png","共享广告"):'')
                    .
                '</td>
                <td width="70">
                    <script>
                        Mo.Tools("RsEdit","adsview.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="11" class="notice">没有检索到相关广告，<a href="'.$appid.'.edit.php">创建一个？</a></td></tr>';
	}
        
        ?>
        <tr class="tfoot">
            <td colspan="11" class="first">
                
                <span style="float:right;">
                <?php
                echo loader_image("icon/warning.png");
                ?>
                今天到期
                
                <?php
                echo loader_image("icon/ball.png");
                ?>
                替补广告
                
                <?php
                echo loader_image("icon/code.png");
                ?>
                代码广告
                
                <?php
                echo loader_image("icon/statistics.png");
                ?>
                统计分析
                
                <?php
                echo loader_image("icon/globe.png");
                ?>
                地区限制
                
                <?php
                echo loader_image("icon/monitor.png");
                ?>
                广告预览
                
                <?php
                echo loader_image("icon/folder.png");
                ?>
                共享广告
                </span>
                
                <?php echo $_G['module']['adsview']["tool"];?>
                
                 - <a href="javascript:Mo('#_s_').toggle();void(0);" class="next">向后延期</a>
                 
                <ul id="_s_" class="select" style="display:none;">
                	<li><a href="javascript:if(confirm('确定要延期所选吗?')){ Mo('#formPost input[name=action]').value('delay'); Mo('#formPost input[name=delay]').value('86400'); Mo('#formPost').submit(); }void(0);">延期一天</a></li>
                	<li><a href="javascript:if(confirm('确定要延期所选吗?')){ Mo('#formPost input[name=action]').value('delay'); Mo('#formPost input[name=delay]').value('259200'); Mo('#formPost').submit(); }void(0);">延期三天</a></li>
                	<li><a href="javascript:if(confirm('确定要延期所选吗?')){ Mo('#formPost input[name=action]').value('delay'); Mo('#formPost input[name=delay]').value('604800'); Mo('#formPost').submit(); }void(0);">延期一周</a></li>
                </ul>
                
                <script>
                Mo(document).bind('click',function(){
					Mo('#_s_').hide();						   
				});
                </script>

            </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();?>