<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	$Id: ,v1 10:39 2008-7-27 Leilei $
*/

require("../../include/header.php");

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

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

	//module
	require("naver.php");

	//mysql open
	reader_mysql();

	if( !loader_cache($appid,"table.adsarea") ){
		//更新分类数组缓存
		cache_table($appid,$mysql,VI_DBMODPRE."adsarea",'<option value=\'{table:id}\'>{table:name}</option>');		
	}
	
	//'***********************
	
	$sel = GetQuery("sel");

	$q = GetQuery("q");
	$s = GetQuery("s");

	$parent = GetQuery("parent");
	$type = GetQuery("type");
	
	$action = GetQuery("action");
	
	//批处理列表
	$list = $_POST["list"];
        $list = implode(",", $list);
    
        //上一页
        $jump = $_POST["jump"];
	
	$full = GetNumber("full",-1);
	$owner = GetNumber("owner",0);
	
	//排序方式
	$_key = GetQuery("_key");
	$_ord = GetQuery("_ord");
	
	//日期筛选
	$start = GetQuery("start");
	$end = GetQuery("end");

	//时间
	if ($start && $end){
	
		//开始时间
		$e_array=explode("-",$start);
		$time1=mktime(0, 0, 0, $e_array[1], $e_array[2], $e_array[0]);
		
		//到期时间
		$e_array=explode("-",$end);
		$time2=mktime(23, 59, 59, $e_array[1], $e_array[2], $e_array[0]);
		
		$ect.=" and  start >=".$time1." and expire <= ".$time2;
	}
	
	switch($action){
		//删除
		case "delete":
		
			//检查权限
			checker_func("mod-adsview-del");		
			
			//直接删除不经过回收站
			if( $Group["sys-system-recycle"]=="Y" ){
					
				//删除本广告
				$sql="delete from ".VI_DBMODPRE."adsview where id in(".$list.")";
				mysql_query($sql,$mysql);
				
				$Project["queries"]++;
				
				//清空统计
				require("../analytic/function.php");
				clear($appid,$list);
					
			}else{
			
				$sql="update ".VI_DBMODPRE."adsview set status=-1,modify=".time().",mender='".$_SESSION["Manager"]["account"]."' where id in(".$list.")";
				mysql_query($sql);				
				
			}
				
			//生成广告
			ad_create("SELECT * FROM ".VI_DBMODPRE."adsarea where parent>0 order by type",$mysql);
			
			$Project["message"]="成功删除广告！";
			
		break;
		
		//状态
		case "status":
		
			//检查权限
			checker_func("mod-adsview-mod");		
		
			$status = GetNumber("status",0);
			
			$sql="update ".VI_DBMODPRE."adsview set status=".$status.",modify=".time().",mender='".$_SESSION["Manager"]["account"]."' where id in(".$list.")";
			mysql_query($sql,$mysql);
						
			$Project["queries"]++;
						
			//缓存广告缓存
			cache_rows($appid,$mysql,VI_DBMODPRE."adsview","select * from ".VI_DBMODPRE."adsview where id in(".$list.")");
			
			//type
			$sql="select type FROM ".VI_DBMODPRE."adsview where id in(".$list.") group by type";
			
			$result=mysql_query($sql,$mysql);
			
			$Project["queries"]++;
			
			while($row=mysql_fetch_assoc($result)){
				
				$type=$row["type"];
				
				//生成广告
				ad_create("SELECT * FROM ".VI_DBMODPRE."adsarea where id =".$type ,$mysql);
			}
			
			reader_redirect($jump,"广告更新成功!");
			
		break;
		
		case "create":
			
			//生成广告
			ad_create("SELECT * FROM ".VI_DBMODPRE."adsarea where parent>0",$mysql);
			
			//缓存广告缓存
			cache_rows($appid,$mysql,VI_DBMODPRE."adsview","select * from ".VI_DBMODPRE."adsview");
			
			$Project["message"]="已生成所选广告！";
			
		break;
	}
	
	?>

	<?php    
    echo loader_script(array(VI_BASE."js/mo.calendar.js"),"utf-8",$Project["version"]);    
    ?>
    
    <div id="search">
    
    <form name="formSeacrh" id="formSeacrh" method="get" action="?">
      <span class="action">
        
        <label>
        <select name="parent" id="parent" onChange="$('type').length=0;Mo('#formSeacrh').submit();" ignore="true">
            <optgroup label="所在频道" />
            <option value="0">全部频道</option>
            <?php
                foreach($VICACHE["mod.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($VICACHE["mod.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 $Modules["adsview"]["full"][0];?></option>
            <option value="1"><?php echo $Modules["adsview"]["full"][1];?></option>
            <option value="2"><?php echo $Modules["adsview"]["full"][2];?></option>
        </select>
      
        <select name="owner" id="owner" onChange="Mo('#formSeacrh').submit();" ignore="true">
            <optgroup label="所有者" />
            <option value="0">全部人员</option>
            <?php
                echo $VICACHE["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;?>");
            
            <?php
            //只针对新增内容
            if($_GET['mark']){
            ?>
            //操作提示
            Mo.Tips(null,$("mark-<?php echo $_GET['mark'];?>"),'info','新增广告均为 已停用 状态，选中广告并 <a href="javascript:void(0);" onclick="$(\'status-1\').scrollIntoView(true);Mo.Tips(null,$(\'status-1\'),\'info\',\'启用所选 在这里哦！<br />^_^ 页面底部不怎么显眼~~\',document,\'click\',0,10);">启用所选</a > 才会投放',document,'click',0,20);
            <?php
            }
            ?>
            
        }
    );
    </script>
    
    <!--用于动作处理_开始-->
    <form name="formPost" id="formPost" method="post">
        <input name="action" id="action" type="hidden" value="" />        
        <input name="status" id="status" type="hidden" value="" />
        
        <input name="jump" type="hidden" value="" />
        <script>Mo('#formPost input[name=jump]').value( location.href );</script>
    
    <?php
    
    $sql="SELECT * FROM ".VI_DBMODPRE."adsview where 1=1";
    
    if ($q && $s){
        
        if( strpos($s,"id") !== false ){
            $sql.=" and  ".$s." = ".$q;
        }else{
            $sql.=" and  ".$s." like '%".$q."%'";
        }     
        
    }
	
	//显示回收站
	if( $Group["sys-system-recycle"]!="Y" ) $sql.=" and status > -1 ";    
    
    if ($type){
        //$sql.=" and  type ='".$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 status=3 ";
        break;
        
        //过期预定
        case "expire-engage":
            $sql.=" and status=3 and expire<".(time())." ";
        break;
        
        //过期
        case "expire":
            $sql.=" and expire<".(time())." ";
        break;
        
        //快到期
        case "last":
            $sql.=" and expire<". (time()+ (3600*24*$Setting[$appid]["expire"])) ." and expire>=". time() ." ";
        break;
        
        //正常
        case "normal":
            $sql.=" and  status>0 and status<3 and expire>=". (time()) ." and start<=". (time()) ." ";
        break;
        
        //停用
        case "stop":
            $sql.=" and  status =0 ";
        break;
    }
    
    if ($ect) $sql.= $ect;
    
	//排序
	if( $_key && $_ord ){		
		$sql.=" order BY $_key $_ord";		
	}else{
		$sql.=" order BY id desc";
	}
    
    
    //查询数据库_总记录数
	$row_count = $db -> getValue( str_replace("*","count(type)",$sql) );
    
    $Project["queries"]++;

    //分页参数
    $page=GetPage("page");
    $page_start=$Global["pagesize"]*($page-1);
    $sql=$sql." limit $page_start,".$Global["pagesize"];	
    
    $result=mysql_query($sql,$mysql);
    
    //分页链接
    $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( mysql_num_rows($result)> $Global["pagesize"]/2 ){
        ?>
            <tr class="thead">
                <td colspan="10" class="first">
                	<?php
					//清空排序
					if( $_key && $_ord ){
						echo '<span class="action"><a href="'.$url.$page.'">清空排序</a></span>';					
					}
					?>
                    <?php echo $Modules[$appid]["tool"];?>
                </td>
            </tr>
        <?php
        }
        ?>
    
        <tr class="title" id="thead">
            <td>
                <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>
                状态            
                <script>Mo.Tools("Tip","<strong>广告状态</strong><br />已停用 广告被人为或到期自动停止<br />待播中 广告已启用,但还未被展示<br />已在播 广告正常投放中<br />预定中 广告处于预定状态,还未开始<br />已过期 广告已到期");</script></td>
            <td>起止时间</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>操作</td>
        </tr>			
        
        <?php
        
        $Project["queries"]++;
        
        $i=0;
        
        //今天
        $today = date("Y-m-d"); 
         
        while($row=mysql_fetch_assoc($result)){
            
            //到期倒记时
            $days=DateDiff("d",mktime(0, 0, 0, date("m"), date("j"), date("Y")),$row["expire"]);

            echo '
              <tr class="line" 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"].'">'.$VICACHE["mod.adsarea"][$row["parent"]]["name"].'</a> &gt; <a href="?type='.$row["type"].'">'.$VICACHE["mod.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["status"]==-1){
						echo '<sup class="text-yes">[回收站]</sup>';
					}

                echo '</td>';
                
                echo '<td id="mark-'.$row["id"].'">';
                    //广告状态
                    if( $row["expire"]>time() ){
                        echo $Modules["adsview"]["status"][$row["status"]];
                    }else{
                        echo $Modules["adsview"]["status"][4];
                    }
                echo '</td>';
                
                echo '<td>'.date("y/m/d",$row["start"]).' - ';
                
                    if ( $days<=$Modules["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 onmouseover=\'Mo.Tips( this, event,"tips","合同号: '.$row["contract"].' - 所有者: <a href=&acute;?owner='.$row["owner"].'&acute;>'.$VICACHE["sys.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">'.$Modules["adsview"]["full"][2].'</span>';
                        }else{
                            echo '<span class="text-no">'.$Modules["adsview"]["full"][0].'</span>';
                        }
                    }else{
                        echo '<span class="text-yes">'.$Modules["adsview"]["full"][1].'</span>';
                    }
                echo '</td>';
                
				
		echo '
                <td>                
                    '.loader_image("icon/statistics.png","数据统计","","parent.Mo.Window('window','统计分析' ,'".VI_BASE."module/analytic/analytic.show.php?appid=".$appid."&id=".$row["id"]."&type=views,clicks&name=".urlencode($row["name"])."' ,'900','500',{}); return false;").'                    
                    '.loader_image("icon/monitor.png","广告预览","","parent.Mo.Window('window','广告预览' ,'".VI_BASE."module/adsview/adsview.preview.php?action=ad&id=".$row["id"]."' ,'90%','500',{}); 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/document.png","代码广告"):'')
                    .($default?loader_image("icon/help.png","替补广告"):'')
                    .($row["stat_view"] || $row["stat_click"]?loader_image("icon/statistics.png","统计分析"):'')
                    .($row["area"]?loader_image("icon/globe.png","地区限制"):'')
                    .($row["share"]?loader_image("icon/folder.png","共享广告"):'')
                    .
                '</td>
                <td>
                    <script>
                        Mo.Tools("RsEdit","adsview.edit.php?action=edit&id='.$row["id"].'","");
                        Mo.Tools("RsDelete","?action=delete&list='.$row["id"].',","");
                    </script>
                </td>
              </tr>
            ';
              
            $i++;
        }
        
        ?>
        <tr class="tfoot">
            <td colspan="4" class="first">
                <?php echo $Modules["adsview"]["tool"];?>
                <a href="#">延期一个月</a>
            </td>
            <td colspan="6">
                <?php
                echo loader_image("icon/warning.png");
                ?>
                今天到期
                
                <?php
                echo loader_image("icon/help.png");
                ?>
                替补广告
                
                <?php
                echo loader_image("icon/document.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");
                ?>
                共享广告
            </td>
        </tr>
    </table>
            
	<?php
	
	//mysql close
	reader_mysql(true);
			
	?>
    </form>
    <!--用于动作处理_结束-->
    
    <div id="saving">
		<?php
            echo GetPageLink($page,$row_count,$Global["pagesize"],$url,"page");
        ?>
    </div>

<!--body end-->

<?php html_close();?>