<?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 'config.php';

	$q = getgpc('q');
	$s = getgpc("s");
	$base = $_GET["b"];
	
	$list = getgpc('list');
	$list = implode(",", $list);
	
	$fid = getnum('fid',0);
	$appid = getgpc('appid');
	$action = getgpc('action');
	$state = getnum("state",1);
	
	//状态筛选
	$filter = getnum("filter",-1);
	
	//分类模式
	$model = getnum("model",-1);
	
	//日期筛选
	$start = getgpc('start');
	$end = getgpc('end');

	//时间
	if ($start && $end){
		$ect=" and  dateline >=".strtotime($start)." and dateline <= ".strtotime($end.' 23:59:59');
	}
	
	//加载缓存
	Cached :: loader( $appid, "form.".$fid );
	
	//如果没有权限，则限制为本人
	if( System :: check_func('mod-'.$appid.'-other') == false && $_CACHE[$appid]['form']['aid'] != $_SESSION['Manager']['id'] ){
		echo "<div id='state' class='failure'>对不起，没有权限查看他人的活动数据！</div>";
		exit;
	}
	
	$groups = $_CACHE[$appid]["group"];
	
	$options = $_CACHE[$appid]["option"];
	
	$config = $_CACHE[$appid]["form"]["config"];
	
	//连接数据库
	System :: connect();

	if ($action){
	
		switch($action){
			//删除
			case "delete":
			
				//检查权限
				System :: check_func( "mod-".$appid."-data-del", false );	
				
				//更新选项组及选项统计
				$sql="SELECT config FROM `mod:value` WHERE fid=".$fid." and id in(".$list.")";
				
				$result = System :: $db -> getAll( $sql );
				
				foreach( $result as $row ){
					
					//解析用户数据
					$data = fix_json($row['config']);
					
					switch($_CACHE[$appid]['form']["appid"]){
						
						//表单
						case "form":
					
							//表单数据
							foreach( $groups as $gid => $array ){
							
								$value = $data['G-'.$gid];
								
								if( $value && in_array($groups[$gid]["type"],array("text","textarea","file")) ){
								
									$sql="UPDATE `mod:group` SET stat=stat-1 WHERE stat>0 and id = ".$gid;
									
									System :: $db -> execute( $sql );
								
								}elseif( $value ){
									
									$sql="UPDATE `mod:option` SET stat=stat-1 WHERE stat>0 and id in(".$value.")";
									
									System :: $db -> execute( $sql );
								
								}
							}
							
						break;
						
						//表单
						case "pk":
						
							//投票对象
							$OBJECT = $data["OBJECT"];
							
							if( $OBJECT && $data[$OBJECT."-RESULT"] ){
							
								$data[$OBJECT."-RESULT"] = $data[$OBJECT."-RESULT"] - 1;
								
								//更新人数统计
								$sql="UPDATE `mod:form` SET config='".json_encode($data)."' WHERE id = ".$fid;
								
								System :: $db -> execute( $sql );
							
							}
							
						break;
						
						//试题
						case "test":
						
							if( $data["RESULT"] == "Y" ){
							
								//从答对者中减 1
								$config["RESULT"] = $config["RESULT"] - 1;
								
								//更新正确统计
								$sql="UPDATE `mod:form` SET config='".json_encode($config)."' WHERE id = ".$fid;
								
								System :: $db -> execute( $sql );
							
							}
					
							//表单数据
							foreach( $groups as $gid => $array ){
							
								$value = $data['G-'.$gid];
								
								if( $value && in_array($array["type"],array("radio","select","checkbox")) ){
								
									$sql="UPDATE `mod:option` SET stat=stat-1 WHERE stat >0 and id in(".$value.")";
									
									System :: $db -> execute( $sql );
								
								}
								
								//判断对错			
								$try = false;
								
								if( $value && $array["selected"] ){
									switch( $array["type"] ){
									
										case "radio":
										case "select":
											if( $value == $array["selected"] ){
												$try = true;	
											}
										break;
									
										case "checkbox":
											if( count(array_diff( explode(",",$array["selected"]) , explode(",",$value) )) == 0 ){
												$try = true;
											}					
										break;
									}
									
								}elseif( $value && !$array["selected"] ){
									$try = true;
								}
								
								if( $try ){
									
									$sql="UPDATE `mod:group` SET stat=stat-1 WHERE stat > 0 and id = ".$gid;
									
									System :: $db -> execute( $sql );
								}
								
							}
							
							
						break;
						
						//投票
						case "poll":
						case "vote":
						
							//echo $_CACHE[$appid]['form']["appid"];
							//echo '<br />';
					
							//表单数据
							foreach( $groups as $gid => $array ){
							
								$value = $data['G-'.$gid];
								
								//echo $value;
								//echo '<br />';
								
								if( $value && in_array($groups[$gid]["type"],array("radio","checkbox","button")) ){
								
									$sql="UPDATE `mod:option` SET stat=stat-1 WHERE stat >0 and id in(".$value.")";
									
									System :: $db -> execute( $sql );
									
									//echo $sql;
									//echo '<br />';
								
								}
							}
							
						break;
					
					}
					
				}
			
				//删除提交数据
				System :: $db -> execute( "DELETE FROM `mod:value` WHERE id in(".$list.")" );
				
				//echo "DELETE FROM `mod:value` WHERE id in(".$list.")";
				
				//echo '<br />';
				
				$result = System :: $db -> getAffectedRows();
				
				//echo $result;
				//echo '<br />';
				
				//更新表单统计
				System :: $db -> execute("UPDATE `mod:form` SET stat=stat-".$result." WHERE stat > 0 and id = ".$fid);				

				//echo "UPDATE `mod:form` SET stat=stat-".$result." WHERE stat > 0 and id = ".$fid;
				//echo '<br />';				
								
				//更新缓存
				Cached :: form( $_CACHE[$appid]['form']["appid"], $fid );
				
				//exit();
				
				//上页地址
				$url = getgpc("url");
				
				System :: redirect( $url ? $url : "member.value.php?appid=".$_CACHE[$appid]['form']["appid"]."&fid=".$fid,"用户数据删除成功!");
				
			break;			
			
			case "state":
			
				//检查权限
				System :: check_func( 'mod-'.$appid.'-mod', false );	
				
				$state = getnum('state',0);
			
				$sql="UPDATE `mod:value` SET state=".$state." WHERE id in(".$list.")";
				
				System :: $db -> execute($sql);
				
				System :: redirect("member.value.php?appid=".$appid."&fid=".$fid,"用户数据更新成功!");

			break;
		}
	}
	
	//载入模块配置和函数包
	require("../$appid/config.php");
	require("../$appid/function.php");

	//载入客户端函数包
	require(VI_ROOT."function/client.php");
	
	//计算应收款和已收款
	if( $config['PAYMENT_MONEY'] ){
		$sql = "SELECT sum(ar) as a,sum(pr) as p FROM `mod:trade` WHERE appid='".$appid."' and fid='".$fid."'";
		$count = System :: $db -> getOne($sql);
	}
			
    ?>
    
    <div class="item">
    		<?php
		if( $config['PAYMENT_MONEY'] ){
		?>
 		<span class="action">		
			应收款：<strong class="text-key"><?php echo $count["a"];?></strong>
			已收款：<strong class="text-yes"><?php echo $count["p"];?></strong>
			欠收款：<strong class="text-no"><?php echo $count["a"] - $count["p"];?></strong>
		</span>
		<?php
		}
		?>
		<?php echo $_CACHE[$appid]['form']["name"];?> <span class="text-yes">用户列表</span>
    </div>

	<?php    
    echo loader_script(array(VI_BASE."js/mo.calendar.js"),"utf-8",$_G['product']['version']);    
    ?>
        
    <div id="search">
    
    <form name="formSearch" id="formSearch" method="get" action="?">
    
    	<span class="action">
		
			<button class="button" onclick="Mo('#formAdv').toggle( 0, function(e,s){if(!s){ Mo('#formAdv input').checked(false); Mo('#formSearch').submit();}});" type="button">高级选项</button>
            <?php
			if( System :: check_func( "mod-".$appid."-data-dow" ) ){
			?>
			<button class="cancel" type="button" onclick="location.href=location.href.replace('value.php','report.php');">下载数据</button>
            <button class="cancel" type="button" onclick="new parent.Mo.Dialog( 'dialog','表单选项组', '<iframe src=module/member/api.php?appid=<?php echo $appid;?>&fid=<?php echo $fid;?> frameborder=0></iframe>' ,'80%','60%',{ 'remove' : true, 'draged' : true, 'create' : true }); return false;">数据接口</button>
            
            <?php
			if( function_exists("mcrypt_module_open") ){
				
				//这里很奇怪，只支持长度为4的数组，所以要注意
				$hash = array("appid"=>$appid,"fid"=>$fid,"name"=>$_CACHE[$appid]['form']["name"],"expire"=>time());
				
				$keys = authcrypt( serialize($hash), VI_START );
			?>                
                <a href="member.share.php?keys=<?php echo rawurlencode($keys);?>" target="_blank"><?php echo loader_image("share.gif");?></a>
			<?php
            }else{?>
				<button class="cancel" type="button" title="本功能需要服务器开启 mcrypt 模块" onclick="alert(this.title);">分享数据</button>
            <?php
            
            }
            ?>
            <?php
			}
			?>
        </span>
    
        <select name="s" id="s">
            <option value="id" checked> I D</option>
            <option value="account"> 用户名</option>
			<option value="ip"> IP</option>
			<option value="config"> 数据</option>			
        </select>
        
        <input name="q" type="text" class="text" id="q" value="<?php echo $q;?>" size="15" />
        <input name="fid" value="<?php echo $fid;?>" type="hidden" />
        <input name="appid" value="<?php echo $appid;?>" type="hidden" />
        
        <!--时间节点-->
        <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();">
        <!--时间节点-->
        
        <select id="filter" name="filter">
            <option value="-1">所有状态</option>
            <option value="0">未确认</option>
            <option value="1">已确认</option>
        </select>
        
        <select id="model" name="model">
            <option value="-1">分页显示</option>
            <option value="0">系统默认</option>
            <option value="1">全部显示</option>
        </select>
       
        <button class="go" type="submit"></button>
        
        <div id="formAdv" class="advanced" style="display:none;">        
			<?php
            foreach ($_G['module']['member']["fieds"] as $fied => $name){
                echo '<label><input name="b['.$fied.']" value="1" type="checkbox" class="checkbox" '.($base[$fied]?' checked="checked"':'').' onchange="Mo(\'#formSearch\').submit();" onclick="Mo(\'#formSearch\').submit();" ignore="true" /> '.$name.'</label>';
            }
            ?>        
        </div>
       
    </form>
    </div>
    
    <script type="text/javascript">
        Mo("#s").value("<?php echo $s;?>");
        Mo("#filter").value("<?php echo $filter;?>");
        Mo("#model").value("<?php echo $model;?>");
		
		<?php
		if( is_array($base) ){
			echo "Mo('#formAdv').toggle();";
		}
		?>
    </script>

    <?php
	
    $sql="SELECT * FROM `mod:value` WHERE fid=".$fid." ";
	
    if ( $q && $s ){
        $sql.=" and `".$s."` like '%".$q."%'";
    }
	
    if ( $filter >- 1){
        $sql.=" and state = ".$filter;
    }
	
	if ($ect) $sql.= $ect;
    
    //排序
    $sql.=" order BY id desc";
    
    //查询数据库_总记录数
    $row_count = System :: $db -> getCount( $sql );
	
	if( $model<1 ){

		//分页参数
		$page=getpage("page");
		$page_start=$_G['setting']['global']['pagesize']*($page-1);
		$sql=$sql." limit $page_start,".$_G['setting']['global']['pagesize'];
	}
    
    //分页链接
    $url="?q=".urlencode($q)."&s=".$s."&appid=".$_CACHE[$appid]['form']["appid"]."&fid=".$fid."&".format_get("b",$base)."&filter=$filter&model=$model&page=";
    
    $result = System :: $db -> getAll( $sql );
	
    ?>
    
	<?php
    
    //表格统计
    $x = 0;
    
    //表单数据
    foreach( $_CACHE[$appid]['group'] as $id => $array ){
        $thead .= '<td title="GID '.$id.'">'.$array["name"].'</td>';
        $x++;
    }
    
    //用户数据
    if( is_array($base) ){
        foreach ($_G['module']['member']["fieds"] as $fied => $name){
            if( $base[$fied] ){
				$thead .= '<td title="会员 '.$fied.'">'.$name.'</td>';
				$x++;	
			}
            
        }
    }
    
    //数据扩展
    foreach( $_G['module'][$appid]["value"] as $fied => $name ){
        $thead .= '<td title="扩展 '.$fied.'">'.$name.'</td>';
        $x++;
    }
	    
    ?>
	
	<!--用于动作处理_开始-->
	<form name="formPost" id="formPost" method="post" action="?">
		<input name="action" id="action" type="hidden" value="" />
		<input name="state" id="state" type="hidden" value="" />
		<input name="fid" value="<?php echo $fid;?>" type="hidden" />
		<input name="appid" value="<?php echo $appid;?>" type="hidden" />
		
		<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" id="table" class="table">
		<?php
		if( count($result)> $_G['setting']['global']['pagesize']/2 ){
		?>
        <tr class="thead">
            <td colspan="<?php echo ($x+7);?>" class="first"><?php echo $_G['module']['member']["tool"];?></td>
        </tr>
      	<?php
		}
		?>
      
        <tr class="title" id="thead">
            <td width="30"></td>
            <td>ID</td>
            <td>用户名</td>
            <?php echo $thead;?>
            <td width="60">状态</td>
            <td width="100">IP 地址</td>
            <td>地理位置</td>
            <td width="130">提交时间</td>
        </tr>
      
    <?php
    //VeryIDE 绝对路径
    $url_path=url_path();
    
    foreach( $result as $row ){
		
		//删除空白字符
		$row['config'] = preg_replace("/([\r\n\t\f])/"," ",$row['config']);
		
		$data = fix_json( $row['config'] );	
		
		//读取用户信息
		$user = array();
		
		if( is_array($base) && $row['uid'] ){
			
			$sql="SELECT * FROM `mod:member` WHERE id='".$row['uid']."'";
			
			System :: $db -> query($sql);
			$user = System :: $db -> fetchRow();
		}
		
		//var_dump($config);
		//exit();
        
        ?>
          <tr class="<?php echo zebra( $i, array( "line" , "band" ) );?>" mark="<?php echo $row['id'];?>">
            <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 title='<?php echo $row['name'];?>'>
            	<?php //echo $row['state']?loader_image("icon/online.png","已确认"):loader_image("icon/offline.png","未确认");?>
                <a href="?fid=<?php echo $fid;?>&appid=<?php echo $appid;?>&s=account&q=<?php echo $row['account'];?>" title="UID:<?php echo $row['uid'];?>" ><?php echo format_substr($row['account'],30,"...");?></a>
                
                <?php
				if( $row['uid'] ){
				?>
                <sup>
                <a href="<?php echo "member.profile.php?uid=".$row['uid'];?>" target="_blank" onclick="new parent.Mo.Dialog('dialog','用户个人信息 - <?php echo $row['account'];?>' , '<iframe src='+this.href+' frameborder=0></iframe>','50%','70%',{ 'remove' : true, 'draged' : true, 'create' : true }); return false;"><?php echo loader_image('icon/profile.png','个人档案');?></a>
		
		<a href="<?php echo VI_BASE."module/passport/api.php?action=space&uid=".$row['uid'];?>" target="_blank" onclick="new parent.Mo.Dialog('dialog','用户个人信息 - <?php echo $row['account'];?>' , '<iframe src='+this.href+' frameborder=0></iframe>','80%','70%',{ 'remove' : true, 'draged' : true, 'create' : true }); return false;"><?php echo loader_image('icon/user.png','个人空间');?></a>
                </sup>
                <?php
				}
				?>
            </td>
            <?php
			
			//表单数据
			foreach( $groups as $gid => $array ){
				
				//echo '<td>'.'G-'.$gid." : ".$data['G-'.$gid].'</td>';
				
				if( in_array($groups[$gid]["type"],array("text","textarea","file")) ){
					
					$value = $data['G-'.$gid] ? $data['G-'.$gid] : '';
					
					echo '<td>';
					
					if( $groups[$gid]["type"] == "file" ){
						echo '<a href="'.$value.'" target="_blank">'.filename($value).'</a>';
						
						//缩略图
						$thumb = $data['G-'.$gid.'-EXT'];						
						if( $thumb ){
							echo '<a href="'.$thumb.'" target="_blank">'.loader_image("thumb.gif","缩略图").'</a>';
						}
						
					}else{
						echo $value;
					}
					
					echo '</td>';
				
				}else{
					
					$array = explode(",", $data['G-'.$gid]);
					
					$value = "";
					
					$n = 1;
					foreach( $array as $oid ){					
						$value .= $options[$gid][$oid]["name"].($n!=count($array)?'、 ':'');
						$n++;
					}
					
					if( $data['G-'.$gid.'-EXT'] ){
						$value .= ($value?'、 ':'').$data['G-'.$gid.'-EXT'];
					}
					
					echo '<td>'.$value.'</td>';
				
				}
				
			}
			
			//用户数据
			foreach ($_G['module']['member']["fieds"] as $fied => $name){
				
				//转换数据					
				switch($fied){
				
					case 'sex':						
						$val = $_G['project']['sex'][$user[$fied]];
					break;
				
					case 'marriage':						
						$val = $_G['project']['marriage'][$user[$fied]];
					break;
				
					case 'dateline':						
						$val = date("Y/m/d H:i:s",$user[$fied]);
					break;
				
					//没有从字段中取得信息就从内容中获取
					case 'account':						
					case 'name':						
					case 'email':						
					case 'phone':						
					case 'idcard':						
					case 'company':						
					case 'qq':						
						$val = $data[strtoupper($fied)] ? $data[strtoupper($fied)] : $user[$fied];
					break;
				
					default:						
						$val = $user[$fied];
					break;
				
				}
				
				if( $base[$fied] )	echo '<td> '.$val.' </td>';
			}
			
			//数据扩展
			foreach( $_G['module'][$appid]["value"] as $fied => $name ){					
				echo '<td>'.call_user_func(array($appid, 'parse_value'), $fied, $row, $data, $config ).'</td>';
			}
					
			?>
            <td><?php echo $_G['module']['member']['sign'][$row['state']];?></td>
            <td><?php echo '<span class="text-no">'.$row["ip"].'</span>';?></td>
            <td><?php echo convertip( $row["ip"] );?></td>
            <td title="<?php echo date("Y-m-d H:i:s",$row['dateline']);?>">
                <?php
                echo '<span class="text-yes">'.date("y-m-d H:i:s",$row['dateline']).'</span>';
                ?>
            </td>
            </tr>
        <?php
        }
	
	if( count( $result ) == 0 ){
		echo '<tr><td colspan="'. ( $x+7 ) .'" class="notice">没有检索到相关数据</td></tr>';
	}
        ?>
        
            <tr class="tfoot">
                <td colspan="<?php echo ($x+7);?>" class="first">
                    <?php echo $_G['module']['member']["tool"];?>
                </td>
            </tr>
        </table>
    <?php
  
	//关闭数据库
	System :: connect();
    
    ?>
    
	</form>
	<!--用于动作处理_结束-->
	
    <!--up-->
    
    <div id="saving">
		<?php
			if( $model===1 && $key ){
				$_G['setting']['global']['pagesize'] = $row_count;
			}
            echo multipage($page,$row_count,$_G['setting']['global']['pagesize'],$url,"page");
        ?>
    </div>
    
<!--body end-->

<?php html_close();?>