<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 首页功能类 
 *
 * @package         zsb
 * @subpackage      Models
 * @category        Models
 * 
 */
class Question_answer_model extends MY_Model{
    private $tbl_question = '';
    private $tbl_answer = '';
    private $tbl = '';

	/**
    * 缓存KEY
    *
    * @access private
    * @var string
    */
    private $_mem_key = 'qusetion_answer_model';
    
    /**查询的字段
     * @var string
     */
    protected $select_fields = '';
    
    /**
     * 连表查询
     * @var array
     */
    protected $join_arr = array();
    
    /**
     * 连表类型
     * @var string
     */
    protected $join_type = '';
    
    public function __construct() {
        parent::__construct(1,1,3);
       
        $this->tbl_question = "qa_question";
        $this->tbl_answer = "qa_answer";       
       
       
   }
   
   
   /**
     * 设置需要查询的字段
     * @param array $select_fields
     */
    public function set_select_fields($select_fields)
    {
        $select_fields_str = '';
        if(isset( $select_fields ) && !empty($select_fields))
        {   
            $select_fields_str = implode( ',', $select_fields) ;
        }
        $this->select_fields = $select_fields;
    }
    
    
    /**
     * 获取需要查询的字段
     * @return type
     */
    public function get_select_fields()
    {
        return $this->select_fields;
    }
    
    /**
     * 设置联合查询
     */
    public function set_join_table($join_arr,$join_type){
        $this->join_arr = $join_arr;
        $this->join_type = $join_type;
    }
    
    /**
     * 清空联合查询
     */
    public function clear_join_table(){
        $this->join_arr = '';
        $this->join_type = '';
    }
    
    /**
     * 获取联合查询
     */
    public function get_join_table(){
        return $this->join_arr;
    }
   
    /**
     * 设置查询数据的表名
     * @param string $tbl
     */
    public function set_tbl($tbl) 
    {
        $this->tbl = $tbl;
    }
    
    /**
     * 获取查询数据的表名
    * @return string $tbl 表名
    */
   public function get_tbl() {
           return $this->tbl;
   }
   
   /**
     * 获取问题列表页
     * @param string $where 查询条件
     * @param int $start 查询开始行
     * @param int $limit 数据偏移量
     * @param int $order_key 排序字段
     * @param string $order_by 升序、降序，默认降序排序
     * @return array 返回消息数组
     */
    public function find_all_by($where, $start = 0, $limit = 20, 
            $order_key = 'id' , $order_by = 'DESC') 
    {
        
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }       
		//查询条件
		$this->dbback->where($where);
		//排序条件
        
		$this->dbback->order_by($order_key, $order_by);

		if ( $start >= 0 && $limit > 0 )
		{
			$this->dbback->limit($limit, $start);
		}      
		if(is_array($this->join_arr)&&!empty($this->join_arr))
		{
			foreach ($this->join_arr as $key=>$value)
			{
				$this->dbback->join($key,$value,$this->join_type);
			}            
		}
		
		$result_array = $this->dbback->get($this->tbl)->result_array();      
        
        return $result_array;
    }

	 /**
     * 获取问题列表页从主库走
     * @param string $where 查询条件
     * @param int $start 查询开始行
     * @param int $limit 数据偏移量
     * @param int $order_key 排序字段
     * @param string $order_by 升序、降序，默认降序排序
     * @return array 返回消息数组
     */
    public function find_all_by_master($where, $start = 0, $limit = 20, 
            $order_key = 'id' , $order_by = 'DESC') 
    {
        
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }       
		//查询条件
		$this->dbback->where($where);
		//排序条件
        
		$this->dbback->order_by($order_key, $order_by);

		if ( $start >= 0 && $limit > 0 )
		{
			$this->dbback->limit($limit, $start);
		}      
		if(is_array($this->join_arr)&&!empty($this->join_arr))
		{
			foreach ($this->join_arr as $key=>$value)
			{
				$this->dbback->join($key,$value,$this->join_type);
			}            
		}
		
		$result_array = $this->dbback->get($this->tbl)->result_array();      
        
        return $result_array;
    }
    
    
    
    /**
     * 获取满足查询条件的统计条数
     * @param string $where 查询条件
     * @return int 数量
     */
    public function find_count_by($where)
    {          
            $this->dbback->where($where);
            $this->dbback->from($this->tbl);            
            if(is_array($this->join_arr)&&!empty($this->join_arr))
           {
                foreach ($this->join_arr as $key=>$value)
                {
                    $this->dbback->join($key,$value,$this->join_type);
                }            
            }        
            $count = $this->dbback->count_all_results();
          //  echo $this->dbback->last_query();          
            return $count;
    }
    
    
    /**
     * 根据查询条件返回一条问题的记录
     * @param string $where 查询条件
     * @return array 返回一条一维数组的信息记录
     */
    public function find_one_by($where = '')
    {
        //查询字段
        if ($this->select_fields)
        {
            $this->dbback->select($this->select_fields);
        }
        //查询条件
        $this->dbback->where($where);       
        if(is_array($this->join_arr)&&!empty($this->join_arr)){
            foreach ($this->join_arr as $key=>$value){
                $this->dbback->join($key,$value,$this->join_type);
            }            
        }
        return $this->dbback->get($this->get_tbl())->row_array();
    }
    
    
    
     /**
     * 添加问题答案
     * insert_answer
     * @param int id 问题id
     * @param string  $answertext 回答内容   
     * @param int $uid 用户id 
     * @param int追问id
     * @param int 回答类型
     */    
    public function insert_answer($id,$answertext,$uid,$reqid=0,$type=0,$expScore=0,$diffFlag=0){  
        $data_array['a_qid']	  = $id;
		$data_array['a_message']  = csubstr(strip_tags($answertext), 2000);
        $data_array['a_userid']	  = $uid;
        $data_array['a_dateline'] = time();
        $data_array['a_user_type']= 1;
        $data_array['a_ip']		  = get_ip();
        $data_array['a_num']	  = 0;
        $data_array['a_type']	  = $type;
        $data_array['a_best']	  = 0;
        $data_array['a_req_id']	  = $reqid;
        $data_array['a_score']    = $expScore;
        $data_array['a_diff']     = $diffFlag;
        $return = $this->db->insert($this->tbl_answer, $data_array);
        return $this->db->insert_id();
      
    }
    
    
    /**
     * 更新回复次数
     * updateReplyNum
     */
    public function updateReplyNum($id){
        //$this->db->where("q_id = $id");
        //$this->db->update($this->tbl_question,array('q_anum'=>'q_anum+1'));

		$sql = "UPDATE $this->tbl_question set q_anum=q_anum+1 WHERE `q_id` = '".$id."'";
		return $result = $this->db->query($sql);
		 //echo $this->db->last_query();  
    }
    
    
    /**
     * 同步未读回复
     * syncNoReadReply
     */   
    public function syncNoReadReply($id){        
        //查询字段
        $this->dbback->select("q_id");
        //查询条件
        $this->dbback->where("q_id = $id");
        //查询
        $arr_data = $this->dbback->get('qa_question_sub')->row_array();
        
        if($arr_data['q_id']){
            $this->updateReplyNumLog($id);
        }else{
            $this->addReplyNumLog($id);
        }  
        
    }
    
    /**
     * 添加问题回答次数记录
     * addReplyNumLog
     * @param int $id
     */
    
    private function addReplyNumLog($id){
        $data = array('q_id' => $id, 'q_anum' => 1);
        $this->db->replace('qa_question_sub',$data);
    } 
    
    
    /**
     * 修改问题回答次数
     * updateReplyNumLog
     * @param int  $id
     */
    private function updateReplyNumLog($id){
       // $this->db->where("q_id = $id");
        //$this->db->update('qa_question_sub',array('q_anum'=>'q_anum+1'));

		$sql = "UPDATE qa_question_sub set q_anum=q_anum+1 WHERE `q_id` = '".$id."'";
		return $result = $this->db->query($sql);
        
    }
    
    /**
     * 根据经纪人问题id和uid查看回答的ID和内容
     * getAidContentByUidQid
     * @param int $uid 
     * @param int $qid 
     * @return array
     */
    public function getAidContentByUidQid($uid,$qid){        
        //查询字段
        $this->dbback->select("a_id,a_message");
        //查询条件
        $this->dbback->where("a_qid = $qid and a_type = 0 AND a_userid = $uid AND a_user_type = 1");
        //查询
        $arr_data = $this->dbback->limit(1)->get($this->tbl_answer)->row_array();
        return $arr_data;
    }
    
    /**
     * 查看追问
     * getReQuestion
     * @param int $id 最问id
     * @return array 
     */
    public function getReQuestion($id){
        if(!$id) {
            return FALSE;            
        }     
        $cond_where = "a_req_id = $id";
        $this->dbback->where($cond_where);        
        $arr_data = $this->dbback->order_by("a_id", "asc")->limit(10)->get($this->tbl_answer)->result_array(); 
        return $arr_data;
    }
    
    /**
     * 是否能回答
     * allowToAnsewer
     * @param time $q_expiredate 时间
     * @param int $q_answer_type 类型
     * @return Boolean 
     */
    public function allowToAnsewer($q_expiredate,$q_answer_type){
        $nowtime = time();
        $allowtoanswer = $q_expiredate >= $nowtime && $q_answer_type == 0 ? true : false;
        return $allowtoanswer;
    }
    
    /**
     * 问题难以程度判断（根据回答数目，没回答的是困难的）
     * questionDiff
     * @param int $qid 问题id 
     */
    public function questionDiff($qid){
        //查询字段
        $this->dbback->select("q_anum");
        //查询条件
        $this->dbback->where("q_id = $qid");
        //查询
        $arr_data = $this->dbback->get($this->tbl_question)->row_array();    
		 
        return $arr_data['q_anum'];
    }

    /**
     * 该问题的所有回答数
     * @param int $id 问题ID
     * @return int 统计数量
     */
    public function answerCountByAid($id){
		$mem_key = $this->_mem_key.'answer_Count_By_Aid_2014_10_24'.$id;     
		$cache = $this->mc->get($mem_key);        
        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $count_num = $cache['data'];
        }
        else
        {
			$cond_where = "a_qid = $id  AND  a_type = 0 ";
			$this->dbback->where( $cond_where );
			$count_num = $this->dbback->from($this->tbl_answer)->count_all_results(); 
			$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$count_num) , 10);
		}
        return $count_num;
    }
    
    /**
     * 获取分类
     * getClass
     */
    public function getClass(){
		$mem_key = $this->_mem_key.'ask_get_Class_2014_10_23';     
		$cache = $this->mc->get($mem_key);        
        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $arr_data = $cache['data'];
        }
        else
        {
			$this->dbback->select(" t_id,t_name");
			$cond_where = "t_level = 0";
			$this->dbback->where($cond_where);
			$arr_data = $this->dbback->get("qa_type")->result_array();  
			$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$arr_data) ,  86400);
		}
		return $arr_data;
    }
    
   /**
    * 获取二级分类
    * getSubClass
    * @param int $id   一级分类id
    * @return array
    */
    public function getSubClass($id){    
		$mem_key = $this->_mem_key.'ask_get_Sub_Class_2014_10_15_'.$id;     
		$cache = $this->mc->get($mem_key);        
        if(isset($cache['is_ok']) && $cache['is_ok'] == 1 )
        {
            $arr_data = $cache['data'];
        }
        else
        {
			$this->dbback->select(" t_id,t_name");
			$cond_where = "t_fid = $id";
			$this->dbback->where($cond_where);
			$arr_data = $this->dbback->get("qa_type")->result_array(); 
			$this->mc->add($mem_key , array('is_ok'=>1 , 'data'=>$arr_data) ,  86400);

		}
      
        return $arr_data;        
    }
    
    
    /** Get_IsforbiddenByuid($uid,$usertype,$day)
	* @ 获取用户是否被禁言
	* @param  int $uid		user编号
	* @param  string $day	user类型 1 经纪人，2个人网友
	* @return boolean $is_forbidden 是否被禁言
	**/
	public function getIsforbiddenByuid($uid,$usertype,$day=3){	
		$is_forbidden = false;		
        $mem_key = $this->_mem_key.'ask_user_IsforbiddenByuid_2014_10_15_'.$uid.'_'.$usertype."_".$day;       
		$result_t = $this->mc->get($mem_key);
		if($result_t){
			$result = $result_t;
		}else{
			$day = $day >0 ? $day :3;
			$nowtime	= time();
			$starttime	= $nowtime - $day*86400;
            $this->set_tbl('qa_forbid');
            $cond_where = "f_uid = '".intval($uid)."' AND f_userType = '".intval($usertype)."' AND f_esta = 1 AND dateline BETWEEN ".$starttime."  AND ".$nowtime."  ";
            $result = $this->find_count_by($cond_where);			
			
			$this->mc->add($mem_key,$result,false,600);
		}
		
		$is_forbidden = $result > 0 ?  true : false;

		return $is_forbidden;
	}
    
    
    
    
    
    
   
   
  
   
  
   
   
    
}




