<?php

/**
 *      【橙创家校通v4.0】 (C)2010-2012 Tuntron Inc.
 *      
 *    	 http://www.tuntron.com   QQ：1121251729
 *
 *      &部门基类文件&
 */
 
if (!defined('IS_RUN')) die('Forbidden');

class tj_branch extends tj_model {

    var $table = 'dbpre_branch';
    var $key = 'bid';
	var $dbpre;
	var $info = array();

    function __construct() {
        parent::__construct();
        global $_G;
        $this->dbpre = $_G['dbinfo']['dbpre'];
        $this->init_field();
    }

    function tj_usergroup() {
        $this->__construct();
    }

    function init_field() {
        $this->add_field('bid,btype,bname,pid,access,mod');
        $this->add_field_fun('btype,bname', '_T');
		$this->add_field_fun('btype,bname,mod', 'trim');
        $this->add_field_fun('bid,pid', 'intval');
    }

    function read($bid) {
        $result = parent::read($bid);
        $result['access'] = $result['access'] ? unserialize($result['access']) : array();
        return $result;
    }


	function findbranch($bid,$re) {
		 
		 $arrresult = $this->read($bid);
		 
		 $result=$arrresult['bname'].'/'.$re;
		
		 if($arrresult['pid']>1){
			 
		 	$result = $this->findbranch($arrresult['pid'],$result);
			return $result;
		 }
		 
		 
		$result= substr($result,0,-1);
		 return $result;
	 }
	 
	  function get_branchhtml($bid,$ty,$c,$debid='1') {
		  
		  global $mod,$_G;
		  
		  $branch = $this->findbid($bid);
			
			if($bid>$debid){
				
				if($ty=='null'){
					
				foreach($branch[1] as $key=>$item){

				if( $item['isleaf']=='closed'){
					
					$islast1 = $key+1>=$branch[0]?'last':'';
					//参数验证
					$urlauthcode = fields_code($item['bid'],'bid');
					
					$cAt.='<li class="closed '.$islast1.'"un="node"appended="'.$item['bid'].'"><div un="line"class="line"><ins class="icon"bid="'.$item['bid'].'"></ins><span un="content"><ins class="folder"><div un="structline"mot="hideMenuTip"mor="showMenuTip"style="float:left;"><a title="'.$item['bname'].'"bid="'.$item['bid'].'"href="'.SITEURL.'?mod='.$mod.'&do=member&c='.$c.'&bid='.$item['bid'].'&authcode='.$urlauthcode.'"class="item <!--selected_'.$item['bid'].'-->"un="item"dr="1">'.$item['bname'].'<span ck="showUpDownMenu"bid="'.$item['bid'].'"class="arrow"style="display: none; "></span></a></div></ins></span></div><!--replace_'.$item['bid'].'--></li>';
					
				}else{
					//参数验证
					$urlauthcode = fields_code($item['bid'],'bid');
					
					$islast = $key+1>=$branch[0]?'last':'';
					$lAt.='<li class="leaf '.$islast.'"un="node"appended="1"><div un="line"class="line"><ins class=""></ins><span un="content"><ins class="folder"><div un="structline"mot="hideMenuTip"mor="showMenuTip"style="float:left;"><a title="'.$item['bname'].'"bid="'.$item['bid'].'"href="'.SITEURL.'?mod='.$mod.'&do=member&c='.$c.'&bid='.$item['bid'].'&authcode='.$urlauthcode.'"class="item <!--selected_'.$item['bid'].'-->"un="item"dr="1">'.$item['bname'].'<span ck="showUpDownMenu"bid="'.$item['bid'].'"class="arrow"style="display: none; "></span></a></div></ins></span></div></li>';
					
					
				}
			}
			
				}else{
					
					
					foreach($branch[1] as $key=>$item){
				
				if( $item['isleaf']=='closed'){
					
					$islast1 = $key+1>=$branch[0]?'last':'';
					
					$cAt.='<li class="closed '.$islast1.'" un="node" bid="'.$item['bid'].'">
                                                            <div un="line" class="line">
                                                                <ins class="icon" bid="'.$item['bid'].'" ty="cbranch">
                                                                </ins>
                                                                <span un="content">
                                                                    <ins class="folder">
<input id="ckStruct_'.$item['bid'].'" bid="'.$item['bid'].'" bname="'.$item['allbname'].'" icon="party" ck="select" type="checkbox">
                                                                        <label for="ckStruct_'.$item['bid'].'">
                                                                         '.$item['bname'].'
                                                                        </label>
                                                                    </ins>
                                                                </span>
                                                            </div>
															<!--replace_'.$item['bid'].'-->
                                                        </li>';
					
				}else{
					$islast = $key+1>=$branch[0]?'last':'';
					$lAt.='
					
					<li class="leaf '.$islast.'" un="node">
                                                            <div un="line" class="line">
                                                                
                                                                <span un="content">
                                                                    <ins class="folder">
<input id="ckStruct_'.$item['bid'].'" bid="'.$item['bid'].'" bname="'.$item['allbname'].'" icon="party" ck="select" type="checkbox">
                                                                        <label for="ckStruct_'.$item['bid'].'">
                                                                       '.$item['bname'].'
                                                                        </label>
                                                                    </ins>
                                                                </span>
                                                            </div>
                                                        </li>';
					
					
				}
			}
					
				}
				}
		  
		  $html= '<ul>'.$cAt.$lAt.'</ul>';
		  
		  return $html;
		  
		  
	  }
	  
	  
	  
	  
	   function get_do_branchhtml($str_bid,$ty,$c) {
		   
		   global $_CO;
		  
			$ArrBranch = explode('/',$str_bid);

			//echo _T($html_1);
			
			foreach($ArrBranch as $key=>$item) {
				
				
				
				$html=$this->get_branchhtml($item,$ty,$c);
				
				if($key==0){
					
					$html_1=$this->get_branchhtml($_CO['userbid'],'null',$c,'0');
					$html2 = str_replace('<!--replace_'.$item.'-->',$html,$html_1);
					
				}else{
					
					$html2 = str_replace('<!--replace_'.$item.'-->',$html,$Allhtml);
				}
				
				$html2 = str_replace('<li class="closed "un="node"appended="'.$item.'">','<li class="open "un="node"appended="'.$item.'">',$html2);
				$html2 = str_replace('<li class="closed last" un="node" appended="'.$item.'">','<li class="open last" un="node" appended="'.$item.'">',$html2);
				
					$html2 = str_replace('<li class="closed last"un="node"appended="'.$item.'">','<li class="open last" un="node" appended="'.$item.'">',$html2);
			
				if($key+1==count($ArrBranch)) $html2 = str_replace('<!--selected_'.$item.'-->','selected',$html2);
				
				$Allhtml= $html2;

				}
				
				return $Allhtml;
		  
	  }
	  
	  
	 
	 
	 
	 function FindAllBid($bid,$re) {
		 
		 $arrresult = $this->read($bid);
		 
		 $result=$arrresult['bid'].'/'.$re;
		
		 if($arrresult['pid']>1){
			 
		 	$result = $this->FindAllBid($arrresult['pid'],$result);
			return $result;
		 }
		 
		 
		$result= substr($result,0,-1);
		 return $result;
	 }
	 
	 
	 function deletebranch($bid) {

       $this->db->where('bid', $bid);  
		
	   $this->db->from($this->table);     

       $result = $this->db->delete();
		
		return $result;
		
	 }


	 function isleaf($bid) {
			 
			 
			$this->db->from($this->table);
	
			$this->db->where('pid',$bid);
			
			if($row = $this->db->get()) {
          	$result = TRUE;
        	}else{
				$result = FALSE;
			}
			return $result;
	 }
	
	 function findbid($bid,$rebid) {
		 
		 
		$this->db->from($this->table);

		$this->db->where('pid',$bid);
		
		
		
		 if($row = $this->db->get()) {
          	$results = $row->fetch_all_assoc();
			
        	}
			 foreach($results as $key=>$item){
				 
				 $result[$key] = $item;
				 $result[$key]['allbname'] = $this->findbranch($item['bid']);
				 if($this->isleaf($item['bid'])){
				 $result[$key]['isleaf'] ='closed';
				 }else{
					 
					  $result[$key]['isleaf'] ='leaf';
				 }
				 
			 }
			
		
		//print_r($arrresult);
		//exit;
		/*
		if(is_array($arrresult)){
		 foreach($arrresult as $key=>$item){
		 
		 $result=$item['bid'].','.$rebid;
		 
		// echo $result.'<br>';
		
		 if($item['bid']){
			 
		 	$result = $this->findbid($item['bid'],$result);
			
			return $result;
			
		 }
		 }
		}else{
			$result = $rebid;
			
		}
		*/
		 //print_r($result);
		 
		 $total = count($result);
		 $result = array($total,$result);
		 return $result;
		

	 }
	 //根据部门ID获取所有下属部门
	 function findbid_by_sub($bid){
	 	$sql = "SELECT * FROM {$this->dbpre}branch WHERE pid='$bid'";
	 	$bids = $this->db->fetch_all_assoc($sql);
	 	if($bids != NULL){
	 		foreach($bids as $key=>$value){
	 			$this->info[$value['bid']] = $value['bid'];
	 			$this->findbid_by_sub($value['bid']);
	 		}
	 	}else{
	 		return $this->info;
	 	}
	 	return $this->info;
	 }
	 
	//根据部门ID获取所有下属部门管理员
	 function findbid_by_sub_admin($bid){
	 	$sub_bid = $this->findbid_by_sub($bid);
	 	$sql = "
	 		SELECT groupid FROM {$this->dbpre}usergroups WHERE grouptype in ('system','school')
	 	";
	 	$group_result = $this->db->fetch_all_assoc($sql);
	 	$group = array();
	 	foreach($group_result as $value){
	 		$group[] = $value['groupid'];
	 	}
	 	if($sub_bid != NULL){
	 		$bid_string = implode(',', $sub_bid);
	 		$bid_string = "{$this->dbpre}users.bid IN ($bid_string) AND ";
	 	}else{
	 		$bid_string = '';
	 		return '';
	 	}
	 	if($group != array()){
	 		$groupid_string = implode(',', $group);
	 		$groupid_string = "{$this->dbpre}users.groupid IN($groupid_string) AND ";
	 	}else{
	 		$groupid_string = '';
	 	}
	 	$sql = "
	 		SELECT uid,username,realname,sex,phonenum,{$this->dbpre}users.groupid,{$this->dbpre}users.bid,sms_balance,groupname,bname
	 		FROM {$this->dbpre}users,{$this->dbpre}usergroups,{$this->dbpre}branch
	 		WHERE
	 			{$bid_string}{$groupid_string}
	 			{$this->dbpre}users.bid = {$this->dbpre}branch.bid AND
	 			{$this->dbpre}users.groupid = {$this->dbpre}usergroups.groupid
	 			
	 	";
	 	$result = $this->db->fetch_all_assoc($sql);
	 	return $result;
	 }
	
	
    function read_all($type=null) {
        $this->db->from($this->table);
        if($type) {
            $this->db->where('btype', $type);
            if($type=='member') {
                $this->db->order_by('pid');
            }
        }
        $this->db->select('bid,btype,bname,pid,order');
        return $this->db->get();
    }

    function update(& $post) {
        if(!is_array($post)) return;
        foreach($post as $key => $val) {
            $this->save($val, $key, FALSE);
        }
    }

    function save($post,$bid=null) {
		
        $edit = $bid!=null;
		
        if($edit) {
            if(!is_numeric($bid) || $bid < 1) Note(lang('global_sql_keyid_invalid','bid'));
            if(!$detail=$this->read($bid)) Note('member_usergroup_empty');
            isset($post['access']) && $post['access'] = $post['access'] ? serialize($post['access']) : '';
        }else{
			$this->isorder($post['pid'],$post['btype']);	
		}
        $bid = parent::save($post,$bid);
        return $bid;
    }

    function & pid_by_usergroup($pid) {
        if(!isset($this->global['usergroup'])) {
            $this->global['usergroup'] = $this->variable('usergroup');
            if(!$this->global['usergroup']) return;
        }
        $bid = 0;
        foreach($this->global['usergroup'] as $key => $val) {
            if($val['btype'] != 'member') continue;
            if($pid > $val['pid']) $bid = $key;
        }
        return $bid;
    }
	
	 function isorder($pid,$btype) {
		 
		 $parr=$this->read($pid);
		 
		 switch ($btype){
			 
			 case 'system':
			 	
			 Note($parr['bname'].'下无法建立系统部门');
			
			 break;
			 
			 case 'school':
			 
			 if(in_array($parr['btype'],array('school','grade','class','group','other'))) Note($parr['bname'].'下无法建立学校');
			 
			 break;
			 
			 case 'grade':
			 
			 if(in_array($parr['btype'],array('grade','class','group','other'))) Note($parr['bname'].'下无法建立年级');
			 
			 break;
			 
			 case 'class':
			 
			 if(in_array($parr['btype'],array('class','group','other'))) Note($parr['bname'].'下无法建立班级');
			 
			 break;
			 
			 case 'group':
			 
			 if(in_array($parr['btype'],array('group','other'))) Note($parr['bname'].'下无法建立小组');
			 
			 break;
			 
		 }
		
    }

    function check_post(& $post, $edit = FALSE) {
        if($edit && isset($post['bname']) && !$post['bname']) Note('部门名称不能为空！');
        if(!$edit && !$post['bname']) Note('部门名称不能为空！');
        if(!$edit && !in_array($post['btype'],array('system','school','grade','class','group','other'))) Note('您选择的部门类型有误！');
        if(!$edit && !$post['btype']) Note('请选择部门类型！');
    }
}
?>