<?php

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

require '../../include/loader.php';
html_start("选票选项 - VeryIDE");
?>

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

	$appid = Module :: get_appid();

	//module
	require 'config.php';
	require 'function.php';
	//require 'naver.php';
	
	//连接数据库
	System :: connect();
	
	$do = getgpc('do');

	$action = getgpc('action');
	$jump = getgpc('jump');
	
	$fid = getnum('fid',0);
	$gid = getnum('gid',0);
	
	//批处理列表
	$list = getgpc('list');
	$list = is_array($list) ? implode(",", $list) : $list;

	//上一页
	$jump = $_POST["jump"];
	
	if ($action){

		$name = getgpc('name');
		$sort = getnum("sort",0);
		$state = getnum('state',0);
		$oid = getnum('id',0);
		$stat = getnum("stat",0);
		$description = getgpc("description");
		
		$image = getgpc("image");
		$quote = getgpc("quote");

		switch($action){
			
			case "add":
			
				//检查权限
				System :: check_func( 'mod-vote-add', false );
		
				//批量插入
				foreach($_POST["_name"] as $key => $val){
					
					//不为空
					if( $val ){
						
						$name = $_POST["_name"][$key];
						
						$sort = intval($_POST["_sort"][$key],0);
						
						$quote = $_POST["_quote"][$key];
						
						$desc = $_POST["_description"][$key];
						
						$image = file_upload( "_image", $key , $_G['upload']['image'] ) ;
						
						$image = is_string($image) ? $image : '';
					
						$sql="INSERT INTO `mod:option`(name,sort,fid,gid,dateline,description,stat,state,quote,image) values('".$name."',".$sort.",".$fid.",".$gid.",".time().",'".$desc."',".$stat.",".$state.",'".$quote."','".$image."')";
						
						System :: $db -> execute( $sql );
						
						$id = System :: $db -> getInsertId();
						
					}
				}
				
				//生成缓存
				Cached :: form( $appid, $fid );
				
				System :: redirect("?do=list&fid=".$fid."&gid=".$gid,"信息提交成功!");
				
			break;
				
			case "edit":
			
				$sql="SELECT * FROM `mod:option` WHERE id=".$oid;
				$row = System :: $db -> getOne( $sql );
			
			break;
				
			case "update":
			
				//检查权限
				System :: check_func( 'mod-vote-mod', false );
		
				$sql="UPDATE `mod:option` SET name='".$name."',sort=".$sort.",description='".$description."',state=".$state.",quote='".$quote."',image='".$image."' WHERE id=".$oid;
				System :: $db -> execute( $sql );
				
				//修改票数
				if( $stat ){
					$sql="UPDATE `mod:option` SET stat='".$stat."' WHERE id=".$oid;
					System :: $db -> execute( $sql );
				}
								
				//生成缓存
				Cached :: form( $appid, $fid );
				
				System :: redirect("?do=list&fid=".$fid."&gid=".$gid,"信息修改成功!");
			break;
				
			case "delete":
			
				//检查权限
				System :: check_func( 'mod-vote-del', false );
		
				$sql="DELETE FROM `mod:option` WHERE id in(".$list.")";
				System :: $db -> execute( $sql );
				
				System :: redirect("?do=list&fid=".$fid."&gid=".$gid,"信息删除成功!");
			break;
			
			//重新计算票数
			case "stat":
			
				//检查权限
				System :: check_func( 'mod-vote-mod', false );
		
				$sql="SELECT id FROM `mod:option` WHERE gid=".$gid;
				
				$result = System :: $db -> getAll( $sql );

        			foreach( $result as $row ){
					
					//投票值
					$stat = Vote :: stat( $fid, $gid, $row['id'] );
					
					$sql="UPDATE `mod:option` SET stat=".$stat." WHERE id = ".$row['id'];
					
					System :: $db -> execute( $sql );
					
				}
								
				//生成缓存
				Cached :: form( $appid, $fid );
				
				System :: redirect("?do=list&fid=".$fid."&gid=".$gid,"选项统计已重新计算!");
				
			break;
			
			case "state":
			
				//检查权限
				System :: check_func( 'mod-vote-mod', false );
		
				$sql="UPDATE `mod:option` SET state=".$state." WHERE id in(".$list.")";
				System :: $db -> execute( $sql );
								
				//生成缓存
				Cached :: form( $appid, $fid );
				
				System :: redirect("?do=list&fid=".$fid."&gid=".$gid,"选项状态更改成功!");
				
			break;							
							
		}		
		
  	}	
	
	//加载缓存
	Cached :: loader( $appid, 'form.'.$fid );
	?>
<!--main-->
	<?php
	
	echo '
    <div class="item">
        <strong>'.$_CACHE[$appid]['form']["name"].' &gt;&gt; '.$_CACHE[$appid]['group'][$gid]["name"].'</strong> 	
    </div>
    
    <ul id="naver">
        <li'.($do=='new'?' class="active"':'').'><a href="?do=new&fid='.$fid.'&gid='.$gid.'">'.($action=="edit"?'编辑':'新增').'子选项</a></li>
        <li'.($do=='list'?' class="active"':'').'><a href="?do=list&fid='.$fid.'&gid='.$gid.'">管理子选项</a></li>
    </ul>
	';
	?>
    
    <div id="box">
    
    <?php 
	if($do=="new"){
		
		$config = $_CACHE[$appid]['group'][$gid]["config"];
		
		//展示模板
		$template = $config["GROUP_STYLE"] ? $_G['module']['vote']["style"][$config["GROUP_STYLE"]] : $config["GROUP_TEMPLATE"];
		
	?>
		<?php    
        echo loader_script(array(VI_BASE."js/mo.ubb.js"),"utf-8",$_G['product']['version']);    
        ?>

    	<form action="?fid=<?php echo $fid;?>&gid=<?php echo $gid;?>" method="post" verify="true" enctype="multipart/form-data">
        
        <table cellpadding="0" cellspacing="0" class="form">
        
        	<tr>
            	<td width="60"><strong>目标类型：</strong></td>
                <td>
                <?php
				echo $_G['module']['vote']["group"][$_CACHE[$appid]['group'][$gid]["type"]];
				?>
                </td>
            </tr>
            
            <?php
			if( $config["GROUP_STAT"] && !$action ){
			?>
        
            <tr>
                <td><strong>起始票数：</strong></td>
                <td>
                <?php echo $config["GROUP_STAT"];?>
                <input name="stat" type="hidden" id="stat" value="<?php echo $config["GROUP_STAT"];?>" />
                </td>
            </tr>
            
            <?php
			}
			?>
            
            <?php
			//批量添加
			if( $action == "" ){			
			?>
        
        	<tr>
            	<td><strong>批量创建：</strong></td>
                <td>
				
                	<div id="tag-box">
                    
                    <table id="tag-<?php echo $i;?>" cellpadding="0" cellspacing="1" border="0" class="gird">
                        <tr>
                            <td>
                            	<span class="action">
									<a onclick="javascript:Planer.move(this,'up');void(0);">上移</a>
									<a onclick="javascript:Planer.move(this,'down');void(0);">下移</a>
									<a onclick="javascript:Planer.remove(this);void(0);">删除</a>
								</span>
								
                           		名称：<br />
                                <input name="_name[]" type="text" class="text" value="<?php echo $key;?>" size="35" fix_name="标签名称" fix_null="yes" />

                                <input name="_sort[]" type="text" size="10" fix_name="标签排序" fix_number="no" title="显示排序" class="text digi" onclick="Mo.Soler( this, event, this.value, 'mo-soler', { '标签排序' : (function(){ var a = []; for(var i=-9;i<=60;i++){a.push(i);} return a; })() }, function( value ){ this.value = value; }, 1 , 23 );" readonly="true" value="<?php echo $row["sort"] ? $row["sort"] : "0";?>" />
								
								<?php
								if( stripos($template,"{LINK}") !== false ){
								?>								
                                <br />
                                链接：<br />
                                <input name="_quote[]" type="text" class="text" value="<?php echo $val;?>" size="51" />
								<?php
								}
								?>
																
								<?php
								if( stripos($template,"{IMAGE}") !== false ){
								?>								
                                <br />
                                图片：<br />
                                <input name="_image[]" type="file" class="text" value="<?php echo $val;?>" size="40" />
								<?php
								}
								?>
								
								<?php
								if( stripos($template,"{DESC}") !== false ){
								?>								
                                <br />
                                描述：<br />
                                <textarea name="_description[]" cols="50" rows="5"><?php echo $row["description"];?></textarea>								
								<?php
								}
								?>
                            </td>
                        </tr>
                    </table>
                    
                    </div>
                
                    <script type="text/javascript">
                    var Planer = new Mo.Planer(Mo.$("tag-box"));
                    </script>
                    
                    <a onclick="javascript:Planer.copy();void(0);">添加</a>
                
                </td>
            </tr>
            
            <?php
			}else{			
			?>
        
        	<tr>
            	<td><strong>标签名称：</strong></td>
                <td>
                	<input name="name" type="text" class="text" id="name" value="<?php echo $row['name'];?>" size="50" fix_name="标签名称" fix_null="yes" />
               		<input name="sort" type="text" size="35" fix_name="标签排序" fix_number="no" title="显示排序" class="text digi" onclick="Mo.Soler( this, event, this.value, 'mo-soler', { '标签排序' : (function(){ var a = []; for(var i=-9;i<=60;i++){a.push(i);} return a; })() }, function( value ){ this.value = value; }, 1 , 23 );" readonly="true" value="<?php echo $row["sort"] ? $row["sort"] : "0";?>" />
                </td>
            </tr>
            
            <?php
			//if( stripos($template,"{DESC}") !== false ){
			?>
        
        	<tr>
            	<td><strong>标签描述：</strong></td>
                <td>
				<script type="text/javascript">
                	Mo.UBB.show({
						id:"description",
						toolbar:["font","size","color","bold","italic","under","link","zoom","zoomin","zoomout","html","stat","about"]							
					});
                </script>
                <textarea name="description" cols="80" rows="7" id="description"><?php echo $row["description"];?></textarea>
                </td>
            </tr>
            
            <?php
			//}
			?>
            
            <?php
			if( stripos($template,"{IMAGE}") !== false ){
			?>
        
            <tr text='填写此表单的关键字词,将用于显示与此相关的表单'>
                <td><strong>上传图片：</strong></td>
                <td>
                <script type="text/javascript">
                new Serv.Upload("image","<?php echo $row['image'];?>",{'format':['<?php echo implode("','",$_G['upload']['image']);?>'],'again':true,'recovery':true,'input':true});
                </script>
                </td>
            </tr>
            
            <?php
			}
			?>
            
            <?php
			if( stripos($template,"{LINK}") !== false ){
			?>
        
            <tr text='填写此表单的关键字词,将用于显示与此相关的表单'>
                <td><strong>链接地址：</strong></td>
                <td>
                <input name="quote" type="text" class="text" id="quote" value="<?php echo $row["quote"];?>" size="60" />
                </td>
            </tr>
            
            <?php
			}
			?>
        
            
            <?php
			}			
			?>
        
        	<?php
			if( $_G['licence']['type'] != 'free' ){
				
				$stat = $_CACHE[$appid]['form']["stat"] <= 10000 ? Vote :: stat( $fid, $gid, $row['id'] ) : '-';
				
			?>
        	<tr>
            	<td><strong>当前票数：</strong></td>
                <td>
                    <input name="stat" type="text" class="text" value=""> 
                    当前 <?php echo $row['stat'];?> 票（真实票数：<?php echo $stat;?>），如果不修改，请保持为空
                </td>
                
            </tr>
            
            <?php
			}			
			?>
        
        	<tr>
            	<td><strong>项目状态：</strong></td>
                <td>
                    <label>
                    <input name="state" type="radio" class="radio" value="1" checked> 
                    完全开放
                    </label>
                    <label>
                    <input name="state" type="radio" class="radio" value="0">
                    禁用项目
                    </label>
                </td>
                
            </tr>
         
        	<tr class="nobr">
            	<td><strong></strong></td>
                <td>
					<?php
                    if ($action=="edit"){
						 echo '
						<input name="action" type="hidden" id="action" value="update" />
						<input name="id" type="hidden" id="id" value="'.$row['id'].'" />
						';
                       echo '<input type="submit" name="Submit" value="修改项目" class="submit" />';
                    }else{
						echo '
						<input name="action" type="hidden" id="action" value="add" />
						';
                        echo '<input type="submit" name="Submit" value="新增项目" class="submit" />';
                    }
                    ?>
                </td>
            </tr>
            
          </table>
          
          <?php
		  if( isset($row['config']) ){
			require(VI_ROOT."module/member/config.php");
		  ?>
          
          <table width="100%" border="0" cellpadding="1" cellspacing="1" class="table">
          
          	<tr><td colspan="2" class="section"><strong>报名信息</strong></td></tr>
                    
			<?php
			
			$config = fix_json( $row['config'] );
            
            //用户数据
            $i = 0;
            foreach ( $config as $fied => $value){
				
				$fied = strtolower( $fied );
                
                //转换数据					
                switch($fied){
                
                    case 'sex':						
                        $value = $_G['project']['sex'][$value];
                    break;
                
                    case 'marriage':						
                        $value = $_G['project']['marriage'][$value];
                    break;
                
                    case 'modify':
                    case 'dateline':
                        $value = $value ? date("Y/m/d H:i:s",$value) : '-';
                    break;
                
                }
                
                echo '<tr class="'.($i%2?'title':'line').'"> <td width="100" align="right">'.$_G['module']['member']['fieds'][$fied].'</td> <td class="text-yes"> '.$value.' </td></tr>';
                
                $i++;
            }
            
            
            ?>
        </table>
          
          <?php
		  }
		  ?>
        
        <script type="text/javascript">
        	Mo("input[name=state]").value("<?php echo isset($row['state']) ? $row['state'] : 1;?>");
        </script>
        
	 </form>
	
    <?php
	}elseif($do=="list"){
	?>
    
    <form name="formPost" id="formPost" method="post" action="?fid=<?php echo $fid;?>&gid=<?php echo $gid;?>">
		<input name="action" id="action" type="hidden" value="mass" />
		<input name="state" id="state" type="hidden" value="" />
		
		<input name="jump" type="hidden" value="" />
		<script>Mo('#formPost input[name=jump]').value( location.href );</script>

		<table width="100%" border="0" cellpadding="1" cellspacing="1" class="table" id="table">
	
			<?php
            if( count($result)> $_G['setting']['global']['pagesize']/2 ){
            ?>
            <tr class="thead">
                <td colspan="10" class="first">
                    <?php echo $_G['module']['vote']['tool'];?>
                </td>
            </tr>
            <?php
            }
            ?>
	
			<tr class="title">
            <td></td>
            <td>ID</td>
            <td>排序</td>
			<td>标签名称</td>
			<td>统计（当前值）</td>
			<td>统计（有效值）</td>
			<td>链接地址</td>
			<td>添加时间</td>
            <td>状态</td>
			<td width="70">操作</td>
			</tr>
			<?php
				$sql="SELECT * FROM `mod:option` WHERE gid=".$gid." order BY state desc,sort asc";
				
				$result = System :: $db -> getAll( $sql );

				foreach( $result as $row ){
					
					//投票值
					/*
					$val = '"G-'.$gid.'":"'.$row['id'].'"';
					$val = '"G-'.$gid.'":"'.$row['id'].',%"';
					$val = '"G-'.$gid.'":"%,'.$row['id'].'"';
					$val = '"G-'.$gid.'":"%,'.$row['id'].',%"';
					
					//计算准确值
					$sql = "SELECT count(id) FROM `mod:value` WHERE config like '%".$val."%' and fid = ".$fid;
					
					echo $sql;
					
					$stat = System :: $db -> getValue( $sql );
					*/
					
					$stat = $_CACHE[$appid]['form']["stat"] <= 10000 ? Vote :: stat( $fid, $gid, $row['id'] ) : '-';
					
					?>
					
					<tr class="<?php echo zebra( $i, array( "line" , "band" ) );?>" mark="<?php echo $row['id'];?>" edit="<?php echo $appid;?>.option.php?do=new&action=edit&fid=<?php echo $fid;?>&gid=<?php echo $gid;?>&id=<?php echo $row['id'];?>&jump={jump}">
                        <td title="<?php echo $row['id'];?>">
                            <input name="list[]" type="checkbox" class="checkbox" value="<?php echo $row['id'];?>">
                        </td>
						<td><?php echo $row['id'];?></td>
						<td><?php echo $row["sort"];?></td>
						<td><strong class="text-yes"><?php echo $row['name'];?></strong></td>
						<td class="text-yes"><?php echo $row["stat"];?></td>
						<td class="<?php echo ( $stat != $row["stat"] ? 'text-key' : 'text-yes' );?>"><?php echo $stat;?></td>
						<td><script>Mo.Tools("RsFile","<?php echo $row['image'];?>","");</script><a target="_blank" href="<?php echo $row["quote"];?>"><?php echo $row["quote"];?></a></td>
						<td><?php echo date($_G['setting']['global']['dateformat'],$row['dateline']);?></td>
                        <td>
                            <?php echo $_G['project']['state'][$row['state']];?>           
                        </td>
						<td>
							<script type="text/javascript">
                            Mo.Tools("RsEdit","?do=new&action=edit&fid=<?php echo $row["fid"];?>&gid=<?php echo $row["gid"];?>&id=<?php echo $row['id'];?>","");
                            Mo.Tools("RsDelete","?do=list&action=delete&fid=<?php echo $row["fid"];?>&gid=<?php echo $row["gid"];?>&list=<?php echo $row['id'];?>","");
							</script>
						</td>
					</tr>
                    
                    <?php
                    
				}
			?>
		
			<tr class="tfoot">
				<td colspan="11" class="first">
                	
                    <span style="float:right;">
                    	<button type="button" class="button" onclick="if(confirm('确定要重新计算吗?')){ location.href='?do=list&fid=<?php echo $fid;?>&gid=<?php echo $gid;?>&action=stat'; }">重新计算</button>
                    </span>
                
					<?php echo $_G['module']['vote']['tool'];?>
				</td>
			</tr>
        </table>
    
    </form>
	
    <?php 
	
	}
	
	//关闭数据库
	System :: connect();
	?>
	
    </div>
    	
<!--body end-->

<?php html_close();?>