<?php
define('IN_OUN', true);
/* 经销商经销商维护 */
include_once( "includes/command.php");
//include_once(ROOT_PATH.'includes/fck/fckeditor.php');
if(!empty($Aconf['priveMessage']))
{
   echo showMessage($Aconf['priveMessage']);
   exit;
}

$db_table = $pre."pravail";
//post
if( $_POST['action'] == 'add' || $_POST['action'] == 'edit' )
{
	$cotype = 0; 
	if(!isset($fid))       $fid=false; 
	if(!isset($praid))   $praid=false;
	if(!isset($ifshow)) $ifshow=false;
	if(!isset($cotype)) $cotype=false;
	if(!isset($pra_name)) $pra_name=false;
	if(!isset($sort_order)) $sort_order=false;
	if(!isset($password)) $password=false;
	if(!isset($user_name)) $user_name=false;
	if(!isset($my_name)) $my_name=false;
	if(!isset($user_id)) $user_id=false;
	if(!isset($add_time)) $add_time=false;
	if(!isset($action_list)) $action_list=false; 

	if($_POST['action'] == 'add' && $_POST['pra_name'])
	{  
        $pra_name = clean_html(trim($pra_name));
        $sql = "SELECT praid FROM ".$db_table." 
	            WHERE `pra_name` LIKE '".$pra_name."'";
        $tmppraid = $oPub->getone($sql);
        if($tmppraid > 0)
        {
  	             $strMessage = '此厂商已存在，不能添加';
        } else {
			$sql = "INSERT INTO " . $db_table . "(fid,cotype,pra_name,dateadd,sort_order,domain_id)" .
				 "VALUES ('$fid','$cotype','$pra_name',  '".gmtime()."','$sort_order','$_SESSION[$un_domain_id]')"; 
			$oPub->query($sql);
			$praid = ($_POST['action'] == 'add') ? $oPub->insert_id() : $praid;
			if($praid) {
				$fid = $fid + 0;
				$sql = "SELECT next_node FROM ".$db_table." where praid = ".$fid." AND domain_id=".$_SESSION[$un_domain_id];
				$Anorm = $oPub->selectrow($sql);
				$next_node = ($Anorm["next_node"] == '' || $Anorm["next_node"] == 0) ?$praid:$Anorm["next_node"].','.$praid;
				$Afields=array('next_node'=>$next_node);
				$condition = "praid = ".$fid." AND domain_id=".$_SESSION[$un_domain_id];
				$oPub->update($db_table,$Afields,$condition); 
			}
			unset($Anorm);
			$strMessage = '添加成功';
		}
	    
	} else if($_POST['action'] == 'edit' && $praid ) { 
	    $strwhere = " where praid = ".$praid." AND domain_id=".$_SESSION[$un_domain_id];
	    $sql = "SELECT fid,next_node FROM ".$db_table.$strwhere;
				 
	    $Anorm = $oPub->selectrow($sql);
	    if($Anorm['fid'] != $fid)
	    {
         /* 修改原有节点标识 */
	      $strwhere = " where praid = ".$Anorm['fid'];
	      $sql = "SELECT * FROM ".$db_table.$strwhere;
	      $Aupn = $oPub->selectrow($sql);
	      $next_node = str_replace(','.$praid,'',$Aupn['next_node']);
	      $next_node = str_replace($praid.',','',$next_node);
	      $next_node = str_replace($praid,'',$next_node);
          $Afields=array('next_node'=>$next_node);
	      $condition = "praid = ".$Anorm['fid']." AND domain_id=".$_SESSION[$un_domain_id];
          $oPub->update($db_table,$Afields,$condition);
          unset($Aupn);
	     /* 插入新节点 */
          $sql = "SELECT next_node FROM ".$db_table." where praid = ".$fid." AND domain_id=".$_SESSION[$un_domain_id];
	      $Anins = $oPub->selectrow($sql);
	      $next_node = ($Anins[next_node] == '' || $Anins[next_node] == 0) ?$praid:$Anins[next_node].','.$praid;
          $Afields=array('next_node'=>$next_node);
	      $condition = "praid = ".$fid." AND domain_id=".$_SESSION[$un_domain_id];
	      $oPub->update($db_table,$Afields,$condition);
	      unset($Anins);
	    } 
		$sql = "UPDATE " . $db_table . " SET 
		       fid        = '$fid',
		       cotype     = '$cotype',
		       pra_name   = '$pra_name',
			   sort_order = '$sort_order',
			   ifshow = '$ifshow' 
		       WHERE `praid` =".$praid." and domain_id=".$_SESSION[$un_domain_id];
        $oPub->query($sql);
		$strMessage = '修改成功';
    
	}
    
	//判断是否添加管理账号 start 
	if($praid) {

	   if (trim($password) == '' || $user_name == '') {
            $strMessage =  "商家添加成功，请添加管理账号与初始密码！";
	   } else {
		   $db_table = $pre."admin_user";
           $user_name = clean_html(trim($user_name));
           $sql = "SELECT user_id FROM ".$db_table." 
	            WHERE `user_name` LIKE '".$user_name."'";
           $Auser = $oPub->selectrow($sql);
           if($Auser['user_id'] > 0) {
  	             $strMessage = '此帐号已经被其它用户使用！请添加不同的管理账号';
           } else {
              $action_list = implode(",",$admin_nave["list_br_3"]);
              $db_table = $pre."admin_user";
		      $password  = md5(trim($password)); 
              $Afields=array('user_name'=>$user_name,'password'=>$password,'add_time'=>gmtime(),'praid'=>$praid,'action_list'=>$action_list,'domain_id'=>$_SESSION[$un_domain_id]);
              $oPub->install($db_table,$Afields);
		      $user_id =  $oPub->insert_id();
		      /* 增加姓名 */
		      $db_table = $pre."admin_userbase"; 
		      $_POST['my_name'] = $pra_name;
              $Afields=array('user_id'=>$user_id,'my_name'=>$_POST['my_name'],'domain_id'=>$_SESSION[$un_domain_id]);
              $oPub->install($db_table,$Afields);   
		      $strMessage =  "管理账号添加成功!";
		  }
	   }
        
    }
   //判断是否添加管理账号 end
	unset($Anorm);unset($_POST);
}

//get
$db_table = $pre."pravail";
if( $_GET['action'] == 'edit'){
	$_GET['praid'] = $_GET['praid'] +0;
	$sql = "SELECT * FROM ".$db_table." where praid = ".$_GET['praid']." AND domain_id=".$_SESSION[$un_domain_id];
	$Anorm = $oPub->selectrow($sql);
	//查找所有能管理此经销商的账号 
	$db_table = $pre."admin_user";
	$sql = "SELECT user_id,user_name,add_time,last_login FROM ".$db_table." where praid = ".$_GET['praid']." AND domain_id=".$_SESSION[$un_domain_id];
	$struser = '';
	$row = $oPub->select($sql);
    while( @list( $k, $v ) = @each( $row ) ) 
	{
		$struser .= $v["user_name"].' ['.date("Y.j.n",$v["last_login"]).'] ';
    }


}
/* 是自己的经销商，还是上游进货的公司 */

/* 是否网页显示 */
if(!empty($Anorm)) {
   $selected_1 = ($Anorm["ifshow"] == 1)? 'SELECTED':'';
   $selected_0 = ($Anorm["ifshow"] == 0)? 'SELECTED':'';
} else {
   $selected_1 =  'SELECTED';
}
 

$db_table = $pre."pravail";
if( $_GET['action'] == 'del'){
	/*还有子分类将不能删除*/
	$_GET['praid'] = $_GET['praid'] + 0;
	$_GET['fid'] = $_GET['fid'] + 0;
	$strwhere = " where praid = ".$_GET['praid']." AND domain_id=".$_SESSION[$un_domain_id];
	$sql = "SELECT next_node FROM ".$db_table.$strwhere;
	$Anorm = $oPub->selectrow($sql);
	if($Anorm["next_node"] == '' && $_GET['fid'] != 0) {
		/* 上级分类标识整理 */
		$strwhere = " where praid = ".$_GET['fid']." AND domain_id=".$_SESSION[$un_domain_id];
		$sql = "SELECT * FROM ".$db_table.$strwhere;
		$Anorm = $oPub->selectrow($sql);
		$next_node = str_replace(','.$_GET['praid'],'',$Anorm['next_node']);
		$next_node = str_replace($_GET['praid'],'',$next_node);
		$Afields=array('next_node'=>$next_node);
		$condition = "praid = ".$Anorm['praid'];
		$oPub->update($db_table,$Afields,$condition);
		unset($Anorm);

		$condition = 'praid='.$_GET['praid']." AND domain_id=".$_SESSION[$un_domain_id];
		$oPub->delete($db_table,$condition);
	} elseif($_GET['fid'] == 0 && $Anorm["next_node"] == '') {
	  $condition = 'praid='.$_GET['praid'].' AND domain_id='.$_SESSION[$un_domain_id];
      $oPub->delete($db_table,$condition);
	} else {
       $strMessage = '存在下级分类，不能删除。';
	}
}

/* 是否显示 */
$db_table = $pre."pravail";
$sql = "SELECT COUNT(*) as count FROM ".$db_table;
$row = $oPub->getRow($sql);
$filter['record_count'] = $row["count"];
unset($row);
$page = new ShowPage;
$page->PageSize = 30;
$page->Total = $filter['record_count'];
$pagenew = $page->PageNum();
$page->LinkAry = array(); 
$strOffSet = $page->OffSet();

$sql = "SELECT * FROM ".$db_table." WHERE fid=0 and domain_id=".$_SESSION[$un_domain_id]." ORDER BY  sort_order ASC,praid DESC LIMIT ". $strOffSet;
$AnormAll = $oPub->select($sql);
$StrtypeAll = '';
$n = 0;
$db_table = $pre."admin_user";
while( @list( $key, $value ) = @each( $AnormAll) ) {
	   $n ++;
	   $tmpstr = ($n % 2 == 0)?"even":"odd";
       $StrtypeAll .= '<TR class='.$tmpstr.'>';
       $StrtypeAll .= '<TD align=left>';
	   $StrtypeAll .= '<A HREF="../prav_shops.php?praid='.$value["praid"].'" target="_blank">'.$n.'.'.$value["pra_name"].'</A>';
	   $StrtypeAll .= '</TD>';
	  //查找所有能管理此经销商的账号	   
	   $sql = "SELECT user_id,user_name,add_time,last_login FROM ".$db_table." where praid = ".$value['praid']." AND domain_id=".$_SESSION[$un_domain_id];
	   $struser = '';
	   $row = $oPub->select($sql);
       while( @list( $k, $v ) = @each( $row ) ) 
	   {
		   $struser .= $v["user_name"].',';
		   //$struser .= date("Y.n.j",$v[last_login]).',';
       }

	   if($struser)
	   {
           $struser = substr($struser,0,-1);
	   }

	   $StrtypeAll .= '<TD align=left>'.$struser.'</TD>';
       if($value["descs"])
	   {
	       $descs = sub_str(clean_html($value["descs"]),10);
	   }
	   else
	   { 
           $descs = '请通过管理账号登陆后，修改经销商基本资料';
	   }

	   $StrtypeAll .= '<TD align=left>'.$descs.'</TD>';
	   $StrtypeAll .= '<TD align=left>'.$value["sort_order"].'</TD>'; 
       $StrtypeAll .= '<TD align=left><a href="'.$PHP_SELF.'?praid='.$value["praid"].'&action=edit&fid=0&page='.$pagenew.'"><IMG SRC="images/b_edit.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="编辑"></a> _ ';
	   $StrtypeAll .= '<a href="'.$PHP_SELF.'?praid='.$value["praid"].'&action=del&fid=0&page='.$pagenew.'"><IMG SRC="images/b_drop.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="删除"></a></TD>';
       $StrtypeAll .= '</TR>';  	
	   
	   /* 查找儿子 */
       if($value["next_node"] != ''){          
           $StrtypeAll .= tab_next_node($value["next_node"],$value["praid"]);
	   }
	   /* 查找儿子 */	   
}
?>

<?php
include_once( "header.php"); 
if (!empty($strMessage))   echo  '<SCRIPT language="javascript"> alert( "'.$strMessage.'");</script>'; 
?>
<DIV class=content>
<TABLE width="100%" border=0>
  <TR >
  <form name="form1" method="post" enctype="multipart/form-data" action="<?php echo $PHP_SELF?>"> 
    <TD width="13%" align="left" colspan="5">
        <span style="font-weight: bold">经销商名称:</span>
     	<input name="pra_name" type="text" value="<?php echo !empty($Anorm['praid'])?$Anorm['pra_name']:''?>" size="20" />
 
		<?php echo !empty($Auser['user_id'])?'如果不需重设密码，请保持为空':''?>
		<span style="font-weight: bold">排序:</span>		
     	<input name="sort_order" type="text" value="<?php echo !empty($Anorm['praid'])?$Anorm['sort_order']:5;?>" size="3" />
        <span style="font-weight: bold">经销商管理帐号:</span>
		<input name="user_name" type="text" size="12" value="" />
        <span style="font-weight: bold">密码:</span>
		<input name="password" type="text" size="12" value="" />
        <input type="hidden" name="action" value="<?php echo !empty($Anorm['praid'])?'edit':'add'?>" />
        <input type="submit" name="Submit" value="<?php echo !empty($Anorm['praid'])?' 经销商编辑 ':' 经销商增加 ' ?>" style="background-color: #FFCC66"/>
		<input type="hidden" name="praid" value="<?php echo !empty($Anorm['praid'])?$Anorm['praid']:'0'?>" />  
		<input type="hidden" name="page" value="<?php echo $_REQUEST['page'];?>" /> 
    </TD>
    </form>
  </TR>	
  <TR class=bg5>
    <TD width="20%" align=left>经销商名</TD>
	<TD width="32%" align=left>参与管理的账号</TD>
	<TD width="35%" align=left>描述</TD>
	<TD width="5%" align=left>排序</TD> 
    <TD width="8%" align=left>操作</TD>
  </TR>
  <?php echo $StrtypeAll?>
  <TR class=bg5>
    <TD colspan="5" align=right><?php echo $showpage = $page->ShowLink();?></TD>
  </TR>
</TABLE>
</DIV>

<?php
/* OPTION 递归 经销商 */
function get_next_node($next_node,$fid,$str = '　')
{
   global $oPub,$pre;
   $db_table = $pre."pravail";
   $Agrad = explode(',',$next_node);
   $Stropt = '';
   if(count($Agrad) > 0 )
	{
	   $str .= '　';
	   $tn = 0;
	   while( @list( $k, $v ) = @each( $Agrad ) ) {
           if ($v == 0 && $v =='')
		   {
              break;
		   }		   
		   $sql = "SELECT * FROM ".$db_table." where praid = $v";
           $Anorm = $oPub->selectrow($sql);
		   if( $Anorm["pra_name"] != ''){
			   $tn ++;
	          if($Anorm[cotype] == 1)
	          {
		        $cotype = '[供货商]';

	          }
	          elseif($Anorm[cotype] == 2)
	          {
		        $cotype = '[代理商]';
		      }
	          else
	          {
		        $cotype = '[子公司]';
	           }
			   $selected = ($fid == $v)? 'SELECTED':'';
		      $Stropt .=  '<OPTION VALUE="'.$v.'" '.$selected.'>'.$str.$tn.'）'.$cotype.$Anorm["pra_name"].'</OPTION>';
              $Stropt .= get_next_node($Anorm["next_node"],$fid,$str);
		   }
		   
	   }
	}
	return $Stropt;
}
/* tbale 递归 */
function tab_next_node($next_node,$fid,$str = '　')
{
   global $oPub,$pre;
   $db_table = $pre."pravail";
   $Agrad = explode(',',$next_node);
   $Strtab = '';
   if(count($Agrad) > 0 )
	{
	   $str .= '　';
	   $tn = 0;
	   while( @list( $k, $v ) = @each( $Agrad ) ) {
           if ($v == 0 && $v =='')
		   {
              break;
		   }		   
		    $sql = "SELECT * FROM ".$db_table." where praid = $v";
            $Anorm = $oPub->selectrow($sql);
			if( $Anorm["pra_name"] != ''){
			  $tn ++ ;
	          $tmpstr = ($n % 2 == 0)?"even":"odd";
              $Strtab  .= '<TR class='.$tmpstr.'>';

              $Strtab  .= '<TD align=left>'.$str.$tn.'）'.$Anorm["pra_name"].'</TD>';

	          if($Anorm[cotype] == 1)
	         {
		        $tmp = '供货商';

	         }
	         elseif($Anorm[cotype] == 2)
	         {
		        $tmp = '代理商';
		     }
	         else
	         {
		        $tmp = '子公司';
	          }
              $Strtab  .= '<TD align=left>';
	          $Strtab  .= $tmp;
	          $Strtab  .= '</TD>';
	          $Strtab  .= '<TD align=left>'.$Anorm["contact"].'</TD>';
	          $Strtab  .= '<TD align=left>'.$Anorm["pra_url"].'</TD>';
	          $descs = sub_str(clean_html($Anorm[descs]),10);
	          $Strtab  .= '<TD align=left>'.$descs.'</TD>';
	          $Strtab  .= '<TD align=left>'.$Anorm["sort_order"].'</TD>'; 
              $Strtab  .= '<TD align=left><a href="'.$PHP_SELF.'?praid='.$v.'&fid='.$fid.'&action=edit"><IMG SRC="images/b_edit.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="[编辑]"></a> ';
	          $Strtab  .= ' _ <a href="'.$PHP_SELF.'?praid='.$v.'&fid='.$fid.'&action=del"><IMG SRC="images/b_drop.png" WIDTH="16" HEIGHT="16" BORDER="0" ALT="[删除]"></a></TD>';
              $Strtab  .= '</TR>';  
	          $n ++;
              $Strtab .= tab_next_node($Anorm["next_node"],$v,$str );
			}
	   }
	}
	return $Strtab;
}
?>
<?php
include_once( "footer.php");
?>