<?php

/**
 *      【橙创家校通v4.0】 (C)2010-2012 Tuntron Inc.
 *      
 *    	 http://www.tuntron.com   QQ：1121251729
 *
 *      &讨论组基类文件&
 */

if (!defined('IS_RUN')) die('Forbidden');

class tj_group extends tj_model {

	var $table = 'dbpre_group';
    var $key = 'groupid';

	function __construct() {
		parent::__construct();
		$this->init_field();
	}

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

	function init_field() {
		$this->add_field('groupid,uid,bid,groupname,cateid,groupicon,count_topic,listorder,isrecommend,count_topic_today,count_user,addtime,isopen,ispost,isshow,uptime');
		$this->add_field_fun('groupid,uid,bid,cateid,listorder,count_topic,count_topic_today,count_user,isrecommend,addtime,isopen,ispost,isshow,uptime', 'intval');
        $this->add_field_fun('groupname,groupicon', '_T');
	}

	function read_all($type=null,$typestr='cateid',$all_bid) {
        $this->db->from($this->table);
		$this->db->order_by('isrecommend','DESC');
		$this->db->order_by('addtime','DESC');
		if($all_bid) {
            $this->db->where('bid', $all_bid);
        }
		if($type) $this->db->where($typestr,$type);
		$RE =$this->db->fetch_all_assoc();
		foreach($RE as $key=>$value){
				$newtopic =$this-> get_new_topic($value['groupid']);
				$RE[$key]['newtopictitle'] = $newtopic['title'];
				$RE[$key]['newtopicid'] = $newtopic['topicid'] ;
				$RE[$key]['newtopicuptime'] = $newtopic['uptime'] ;
			}
        return $RE;
    }
	
	function read_one($groupid) {
        $this->db->from($this->table);
        $this->db->where('groupid', $groupid);
        return $this->db->once_fetch_assoc();
    }
	
	
	
    function save(& $post, $groupid=NULL, $cache=TRUE) {
        $this->check_post($post);
		
        if(!$groupid) {
			global $_CO;
			$post['bid'] = $_CO['userbid'];
            $post['uid'] = $_CO['uid'];
            $post['addtime'] = $this->global['timestamp'];
			$post['uptime'] = $this->global['timestamp'];
        }
        return parent::save($post, $groupid, $cache, FALSE);
    }

    function update($post) {
        if(!is_array($post)) Note('global_op_unselect');
        foreach($post as $groupid => $val) {
            $this->db->from($this->table);
            $this->db->set($val);
            $this->db->where('groupid',$groupid);
            $this->db->update();
        }
    }
	
	function get_new_topic($groupid) {
		
		return G_class('topic')->read_one($groupid,'1');
       
    }
	
	function delgroup($groupid) {
		
        $this->db->where('groupid', $groupid);  
		
		$this->db->from($this->table);     

        $this->db->delete();
		
    }

    function check_post($post,$is_edit=false) {
        if(!$post['groupname']) Note('讨论组名称不能为空！');
        if(!$post['cateid']) Note('所属讨论区不能为空！');
    }
}
?>