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

class ask extends MY_Controller 
{
    
     /**
    * 当前用户uid
    *
    * @access private
    * @var int
    */
    private  $_uid = 0;

    /**
    * 当前页码
    *
    * @access private
    * @var string
    */
    private $_current_page = 1;

    /**
    * 每页条目数
    *
    * @access private
    * @var int
    */
    private $_limit = 10;

    /**
    * 偏移
    *
    * @access private
    * @var int
    */
    private $_offset = 0;

    /**
    * 条目总数
    *
    * @access private
    * @var int
    */
    private $_total_count = 0;
    
    
    
    /**
    * 解析函数
    */
    public function __construct()
    {
        parent::__construct();
        
		$functionSwitch = $this->config->item('functionSwitch');

		if(empty($functionSwitch['question']))
		{
			$this->jump('/', '没有权限！');
		}

        $this->config_cityflag = 'nj';        
        $this->load->model('Question_answer_model','qa_model'); 
        //用户信息初始化
        $info = $this->broker_model->get_user_session();
        $groupId = $info['package_id']; //套餐
        $gbc = new GrowthBrokerCredit(array('id' => $info['uid'], 'groupid' => $groupId));
        $gbe = new GrowthBrokerExp(array('id' => $info['uid'], 'groupid' => $groupId));
        //房豆
        $info['credit'] = $gbc->getValidCredit();
        //等级
        $info['level'] = $gbe->getLevel(2);
        //经验
        $info['exp'] = $gbe->getExp();
        $this->info = $info;        
        $this->_uid = $this->info['uid'];        
        
        
    }

    //待解决列表
    public function to_answer(){        
        $get_param = array();
        $get_param['page'] = '';
        $get_param['diff'] = '';
        $get_param = $this->input->get(NULL , TRUE);
     
        $current_page = isset($get_param['page'])  ? intval($get_param['page']) : 1;
        $diff = $get_param['diff'] == 1 || $get_param['diff'] == ''  ?  1 : 1;//难度系数
		if($get_param['diff'] == 1 || $get_param['diff'] == ''){
			$diff = 1;
		}else{
			$diff = 2;
		}
         /** 分页参数 */
        $this->_init_pagination($current_page);
        $qtype = intval($get_param['qtype']);
        $qclass = intval($get_param['qclass']);
        $typesql = $qtype > 0 ? "q_type = $qtype AND " : "";
        $classsql = $qclass > 0 ? "q_class = $qclass AND " : "";
        
        $diffsql = $diff == 1  ?  "(q_anum = 0 OR q_anum = 1) AND " : "q_anum > 1 AND ";
        $time = time();
        //查询条件
        $cond_where = "$typesql $classsql $diffsql q_esta = 1 AND q_expiredate>$time AND q_answer_type = 0";  
    
        $cond_where = ltrim($cond_where);
       
        $this->qa_model->set_tbl('qa_question');
        //符合条件的总行数
        $this->_total_count = $this->qa_model->find_count_by($cond_where);     
        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //排序字段
        $orderbyField = "q_anum ASC, q_dateline DESC";  
        //排序
        $orderby = "";
        //获取数据源
        $data_info = $this->qa_model->find_all_by( $cond_where , $this->_offset , $this->_limit ,$orderbyField,$orderby);

         
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages ,$this->_total_count );
        }  
        
        $qtypearr = $this->qa_model->getClass();
        $qclassarr = "";
        if($get_param['qtype']){
            $qclassarr = $this->qa_model->getSubClass(intval($get_param['qtype']));
        }
        
        $alise = $diff == 1  ? 'answerQuestionA' : 'answerQuestionB'; 
        $gcep = new GrowthExpWayPackage();                   
        $expScore = $gcep->findScoreByWayAliasAndPackageId($alise, $this->info['package_id']);
        
        
        //当天发布共获得多少成长值
        $exp_rank_day = $this->getExpRandDay($this->_uid);
       
	    // 2016-1-14 添加星级数据 -----------start -------->
		
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($this->_uid);

		// 2016-1-14 添加星级数据 -----------end -------->
        
        $tab = $diff == 1 ? '难度系数★★' : '难度系数★';        
        $data = array();         
        
        
        
        /** 页面初始化 */
        $data['page_title'] = '问答-待解决问题-'.$tab;     
        $data['js'] = load_js('zsb/js/v1.0/askPag.js');  
        $data['css'] = load_css("zsb/css/v1.0/style1.css");
        $data['display_diff'] = 1;//是否显示难易程度
        $data['expScore'] = $expScore;
        $data['growthDaySum'] = $exp_rank_day['exp'];        
        $data['rankRate'] = $exp_rank_day['rate'];//当前用的排序名次百分比
        $data['get_param']  = $get_param;
        $data['data_info']  = $data_info;
		$data['broker_new_info'] = $broker_new_info;
        $data['page']  = $current_page;
        $data['pagination'] = $pagination;    
        $data['diff'] = $diff;		 
        $data['qtypearr'] = $qtypearr;
        $data['qclassarr'] = $qclassarr;
        $data['info'] = $this->info;
        $data['documentation'] = $this->config->item('documentation');
        $data['google_analytics'] = get_ga_js_code('/租售宝问答/待解决问题/');
        //加载模板
        $this->view('question', 'qa_manage', $data);   
    }
    
    
    //全部问题列表
    public function all_qa(){
        $get_param = array();
        $get_param['page'] = '';
        $get_param['diff'] = '';
        $get_param = $this->input->get(NULL , TRUE);
     
        $current_page = isset($get_param['page'])  ? intval($get_param['page']) : 1;
        
         /** 分页参数 */
        $this->_init_pagination($current_page);
        
        $qtype = intval($get_param['qtype']);
        $qclass = intval($get_param['qclass']);
        $typesql = $qtype > 0 ? " q_type = $qtype AND " : "";
        $classsql = $qclass > 0 ? " q_class = $qclass AND " : "";
        
        //查询条件
        $cond_where = "$typesql $classsql q_esta = 1 ";  
        $cond_where = ltrim($cond_where);
        
        $this->qa_model->set_tbl('qa_question');
        //符合条件的总行数
        $this->_total_count = $this->qa_model->find_count_by($cond_where);

        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //排序字段
        $orderbyField = "q_id";  
        //排序
        $orderby = "DESC";
        //获取数据源
        $data_info = $this->qa_model->find_all_by( $cond_where , $this->_offset , $this->_limit ,$orderbyField,$orderby);

        
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages ,$this->_total_count );
        }
   
        $qtypearr = $this->qa_model->getClass();
        $qclassarr = "";
        if($get_param['qtype']){
            $qclassarr = $this->qa_model->getSubClass(intval($get_param['qtype']));
        }
        
        //当天发布共获得多少成长值
        $exp_rank_day = $this->getExpRandDay($this->_uid);
        // 2016-1-14 添加星级数据 -----------start -------->
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($this->_uid);

		// 2016-1-14 添加星级数据 -----------end -------->
        $data = array();         
        /** 页面初始化 */
        $data['page_title'] = '问答-待解决问题';
        $data['js'] = load_js('zsb/js/v1.0/askPag.js');   
        $data['css'] = load_css("zsb/css/v1.0/style1.css");
        $data['growthDaySum'] = $exp_rank_day['exp'];        
        $data['rankRate'] = $exp_rank_day['rate'];//当前用的排序名次百分比
        $data['get_param']  = $get_param;
        $data['display_diff'] = 0;
        $data['data_info']  = $data_info;
		$data['broker_new_info'] = $broker_new_info;
        $data['page']  = $current_page;
        $data['pagination'] = $pagination; 
        $data['qtypearr'] = $qtypearr;
        $data['qclassarr'] = $qclassarr;
        $data['info'] = $this->info;

        $data['documentation'] = $this->config->item('documentation');
		$data['google_analytics'] = get_ga_js_code('/租售宝问答/全部问题/');
        //加载模板
        $this->view('question', 'qa_manage1', $data);   
    }
    
    
    
    //我的问题列表
    public function my_qa(){
        
        $get_param = array();
        $get_param['page'] = '';
        $get_param['diff'] = '';
        $get_param = $this->input->get(NULL , TRUE);
     
        $current_page = isset($get_param['page'])  ? intval($get_param['page']) : 1;
        
         /** 分页参数 */
        $this->_init_pagination($current_page);
        
        $qtype = intval($get_param['qtype']);
        $qclass = intval($get_param['qclass']);
        $typesql = $qtype > 0 ? " q_type = $qtype AND " : "";
        $classsql = $qclass > 0 ? " q_class = $qclass AND " : "";
        
        $this->qa_model->set_tbl('qa_question');
        $join_arr = array('qa_answer'=>'qa_answer.a_qid = qa_question.q_id');
        $this->qa_model->set_join_table($join_arr,'left');        
     
        
        //查询条件
        $cond_where = "$typesql $classsql qa_question.q_esta = 1 AND qa_answer.a_userid = $this->_uid AND qa_answer.a_user_type = 1 AND qa_answer.a_type = 0";   
                        
        $cond_where = ltrim($cond_where);
       
        //符合条件的总行数
        $this->_total_count = $this->qa_model->find_count_by($cond_where);

        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //排序字段
        $orderbyField = "q_id";  
        //排序
        $orderby = "DESC";
        //获取数据源
        $data_info = $this->qa_model->find_all_by_master( $cond_where , $this->_offset , $this->_limit ,$orderbyField,$orderby);

        
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages ,$this->_total_count );
        }       
        $qtypearr = $this->qa_model->getClass();
        $qclassarr = "";
        if($get_param['qtype']){
            $qclassarr = $this->qa_model->getSubClass(intval($get_param['qtype']));
        }
        
        //当天发布共获得多少成长值        
		$exp_rank_day = $this->getExpRandDay($this->_uid);
        // 2016-1-14 添加星级数据 -----------start -------->
		
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($this->_uid);

		// 2016-1-14 添加星级数据 -----------end -------->
        $data = array();         
        /** 页面初始化 */
        $data['page_title'] = '问答-我的回答';
        $data['js'] = load_js('zsb/js/v1.0/askPag.js');  
        $data['css'] = load_css("zsb/css/v1.0/style1.css");
        $data['growthDaySum'] = $exp_rank_day['exp'];        
        $data['rankRate'] = $exp_rank_day['rate'];//当前用的排序名次百分比
        $data['get_param']  = $get_param;
        $data['display_diff'] = 0;
        $data['data_info']  = $data_info;
		$data['broker_new_info'] = $broker_new_info;
        $data['page']  = $current_page;
        $data['pagination'] = $pagination; 
        $data['qtypearr'] = $qtypearr;
        $data['qclassarr'] = $qclassarr;
        $data['info'] = $this->info;
        $data['documentation'] = $this->config->item('documentation');
		$data['google_analytics'] = get_ga_js_code('/租售宝问答/我的回答/');
        //加载模板
        $this->view('question', 'qa_manage2', $data);   
    }
    
    
    //加载详情
    public function load_detail(){
      
        //问题id
        $qid = $this->input->get('id',TRUE);
        $qid = intval($qid);       
        if($qid){
            $cond_where = "q_id = $qid and q_esta = 1";
            $this->qa_model->set_tbl('qa_question');
            $qdata = $this->qa_model->find_one_by($cond_where);               
            if($qdata){
                //我的回答
                $myanswer = $this->qa_model->getAidContentByUidQid($this->_uid,$qid);
                $myreqarr = "";
                //查看追问
                if(is_array($myanswer) && !empty($myanswer)){                   
                    $myreqarr = $this->qa_model->getReQuestion($myanswer['a_id']);	                  
                }
               
                //是否可回答
                $allowtoanswer = $this->qa_model->allowToAnsewer($qdata['q_expiredate'],$qdata['q_answer_type']);
                //该问题的所有回答数
                $total = $this->qa_model->answerCountByAid($qid);       

                $data = array();
                $data['uid'] = $this->_uid;
                $data['qid'] = $qid;
                $data['qdata'] = $qdata;
                $data['myanswer'] = $myanswer;
                $data['myreqarr'] = $myreqarr;
                $data['allowtoanswer'] = $allowtoanswer;
                $data['total'] = $total;
                header("Content-Type:text/html;charset=gb2312");
                $htmlData = $this->load->view('qa_answer_show',$data); 
				return $htmlData;
				//return $this->ajaxResponse($htmlData, 'gbk', 'text');

            }else{
                 $redirectUrl ="/ask/to_answer/";
                 $this->jump($redirectUrl, "该问题不存在！",2000);
                 return;
            }
        }else{
            $redirectUrl ="/ask/to_answer/";
            $this->jump($redirectUrl, "该问题不存在！",2000);
            return;
        }
        
         
    }
    
    //回答
    public function answer(){
        //回复类型
        $type = $this->input->post('type',TRUE);
        $qid = $this->input->post('id',TRUE);
        $answerText = $this->input->post('answerText',TRUE);
        $reqid = $this->input->post('reqid',TRUE);
        $cond_where = "q_id = $qid and q_esta = 1";
        $this->qa_model->set_tbl('qa_question');
       
        //字符转换
        $answerText = $this->textConvert($answerText);       
        $diffFlag = 0;
        $expScore = 0;
        if($type == 'submit_answer'){
            $reqid = 0;
            $q_type = 0;
            //增加成长值					
            $diff = $this->qa_model->questionDiff($qid);//问题难易程度			
            $alise = $diff == 0 ? 'answerQuestionA' : 'answerQuestionB'; 
            $diffFlag = $diff == 0 ? '2' : '1'; //难易程度星级
            $expScore = $this->getAnswerExp($alise);
        }elseif($type == 'submit_req_answer'){
            $reqid = $reqid;
            $q_type = 2;
        } 
        $qdata = $this->qa_model->find_one_by($cond_where);
		
        if($qdata){
            //是否禁言            
            if($this->qa_model->getIsforbiddenByuid($this->_uid,1) ){              
                return $this->ajaxResponse(array('mid'=>1,'qid'=>'','answerText'=>''));
                exit;			
            }else{
                 
              
                $insert_id = $this->qa_model->insert_answer($qid,$answerText,$this->_uid,$reqid,$q_type,$expScore,$diffFlag);
                if($insert_id>0){ 
                    //更新回复次数
                    if($type == 'submit_answer'){
                        $this->qa_model->updateReplyNum($qid);
                    }
                    //同步未读回复
                    $this->qa_model->syncNoReadReply($qid);
                    
                    
                    return $this->ajaxResponse(array('mid'=>2,'qid'=>$qid,'answerText'=>$answerText));           
                    exit;                
                }else{
                    //回复失败
                    return $this->ajaxResponse(array('mid'=>4,'qid'=>$qid,'answerText'=>''));           
                    exit; 
                }            
                
            }       
            
        }else{
            //该问题不存在
            return $this->ajaxResponse(array('mid'=>3,'qid'=>'','answerText'=>''));
            exit;
        }        
        
    }   



	private function getExpRandDay(){
		$key = $this->config_cityflag."_question_and_question_get_exp_rand_day_".$this->_uid;
        $exp_rank_day = $this->mc->get($key);
		if($exp_rank_day ===false){
			$growthExpDayCount = new GrowthExpDayCount();
            $publishEventArray = array('answerQuestionA','answerQuestionB','bestAnswer');
            $exp_rank_day = $growthExpDayCount->getExpAndRank($this->_uid, $publishEventArray);
			$this->mc->set($key,$exp_rank_day,60);
		}
		return $exp_rank_day;       

	}
    
    
    //获取答题成长值    
    private function getAnswerExp($alise){
        $key = $this->config_cityflag."_get_Answer_Exp_".$this->info['package_id']."_".$alise;
        $expScore = $this->mc->get($key);
        if($expScore === false) {
            $gcep = new GrowthExpWayPackage();                   
            $expScore = $gcep->findScoreByWayAliasAndPackageId($alise, $this->info['package_id']);
            $this->mc->set($key,$expScore,3600);
        }
        return $expScore;
    }



    //中文编码转换
    private function textConvert($answerText){
        $answerText = urldecode($answerText);
        return  iconv('utf-8','gb2312',$answerText);        
    }


    //问题二级分类
    public function subClassAjax(){        
        $sid = $this->input->get('sid',TRUE);
        $action = $this->input->get('action',TRUE);
        if($action=='getqaclass'){           
            $sid = intval($sid);
	        if($sid > 0){
                $qa_class_arr = $this->qa_model->getSubClass($sid);               
		        $ss = '';
		        if($qa_class_arr){
                    $ss = "<dd><a oid='0' class='link'>全部</a></dd>";
			        foreach($qa_class_arr as $qa_class){
                        $ss .= "<dd><a href='####' oid='".$qa_class['t_id']."' class='link'>".$qa_class['t_name']."</a></dd>";
			        }
		        }else{
                    $ss = "<dd><a href='####' oid='0' class='link'>全部</a></dd>";
		        }
	        }else{
                $ss = "<dd><a href='####' oid='0' class='link'>全部</a></dd>";
	        }

	    header("Content-Type:text/html;charset=gbk"); 
	    echo $ss;
	    exit;
        }
    }
    
     /**
    * 初始化分页参数
    *
    * @access public
    * @param  int  $current_page
    * @param  int  $page_size
    * @return void
    */
    private function _init_pagination($current_page = 1 , $page_size = 0)
    {
        /** 当前页 */
        $this->_current_page = ( $current_page && is_numeric( $current_page ) ) ? intval( $current_page ) : 1;

        /** 每页多少项 */
        $this->_limit = ( $page_size && is_numeric( $page_size ) ) ? intval( $page_size ) : $this->_limit;

        /** 偏移量 */
        $this->_offset = ( $this->_current_page - 1 ) * $this->_limit;

        if($this->_offset < 0)
        {
            redirect(base_url());
        }
    }
    
    
     /**
     * ajax响应
     * @param type $data 响应数据
     * @param type $encode 结果编码，当$type=json时起作用
     * @param type $type 结果格式 json 或 text
     */
    private function ajaxResponse($data, $encode = 'gbk',$type='json') {		
        if($type=='json') {
            if ($encode == 'gbk') {
                $data = $this->gbk2utf($data);
            }
            $res = json_encode($data);
            $this->output->set_content_type('application/json')
                ->set_output($res);
        } else {
            $res = $data;
            $this->output->set_content_type('text/html;charset=GB2312')
                ->set_output($res);
        }
        
    }
    
    private function gbk2utf($data) {
        if (is_array($data)) {
            foreach ($data as &$value) {
                $value = $this->gbk2utf($value);
            }
        } else {
            $data = iconv('gbk', 'utf-8', $data);
        }
        return $data;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}