<?php

class My_complain_xiao extends MY_Controller {
    
    
     /**
    * 当前页码
    *
    * @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;
    
    /**
     * 举报原因
     * @access public
     * @var array
     */
    public $allReason;
    /**
     *举报可获得房豆
     * @var type 
     */
    private $credit;


    /**
     * 解析函数
     *
     * @access public
     * @return void
     */
    public function __construct($type = NULL) {
        parent::__construct($type);
        $this->config_cityflag = 'nj';
        $this->load->model('broker_model');     
        $this->load->model('complain_model');
        //用户信息初始化
        $info = $this->broker_model->get_user_session();
        $this->info = $info;
        $this->allReason = $this->config->item('complain_reason');
        $this->credit = $this->getComplainHouseScore($this->info['package_id']);//举报可获得的房豆
    }
    
    
    
    /**
     * 举报tab
     */
    public function complain(){
        
        $check = $this->checkAccess();
        if ($check!==true) {
          //  $page_text = "免费用户不可以使用此功能哦，先去付费吧！";
          //  $this->jump('/', $page_text, 4000);
          //  return;
        }
        
        $join_black = $this->joinBlackList();//是否加入黑名单      
        $complain_num = $this->getComplainNum();//当天投诉次数    	
        $viewData['page_title'] = "竞投房源举报-举报";
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['info'] = $this->info;
        $viewData['join_black'] = $join_black;
        $viewData['complain_num'] = $complain_num;
        $viewData['credit'] = $this->credit;
		$viewData['documentation'] = $this->config->item('documentation');
        $this->view('ucenter','complain/complain_xiao', $viewData);
    }
    
   
    
    /**
     * 举报记录list
     */
    public function myList(){        
        $check = $this->checkAccess();
        if ($check!==true) {
           // $page_text = "免费用户不可以使用此功能哦，先去付费吧！";
           // $this->jump('/', $page_text, 4000);
           // return;
        }
        
      
        $post_param = array();      
        $post_param = $this->input->get(NULL , TRUE);
        $current_page = isset($post_param['page']) ? intval($post_param['page']) : 1;    
        $status = !isset($post_param['status']) ? "" : $post_param['status']; 
   
        $allStatus = $this->config->item('complain_status');
        //参数初始化
        $this->_init_pagination($current_page);      
        $complainRecord = new ComplainRecord();              
         //符合条件的总行数
        $this->_total_count = $complainRecord->findCountByBrokerAndStatus($this->info['uid'],$status);
        //计算总页数
        $pages  = $this->_total_count > 0 ? ceil( $this->_total_count / $this->_limit ) : 0;
        //获取数据源($conf,$order='',$limit='',$offset='') 
        $data_info = $complainRecord->findByBrokerAndStatus($this->info['uid'],$status,'id DESC', $this->_offset, $this->_limit);
        
        $successComplainList = $this->complain_model->getSuccessComplain();
        //是否显示分页
        $pagination = NULL;
        if( $this->_total_count > $this->_limit)
        {
            $pagination = helper_pagination( $current_page , $pages , $this->_total_count );
        }
       
        $data_info = $this->myRecordListData($data_info, $allStatus);
        
        /** 页面初始化 */
        $viewData['page_title'] = '竞投房源举报-我的记录';
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css'); //需要加载的css
       
        $viewData['post_param']  = $post_param;
        $viewData['data_info']  = $data_info;
        $viewData['page']  = $current_page;
        $viewData['pagination'] = $pagination;
        $viewData['total'] = $this->_total_count;
        $viewData['documentation'] = $this->config->item('documentation');
        $viewData['allStatus'] = $allStatus;
        $viewData['status'] = $status;
        $viewData['info'] = $this->info;
        $viewData['credit'] = $this->credit;
        $viewData['successComplainList'] = $successComplainList;
        //加载模板
        $this->view('ucenter','complain/my_list', $viewData);     
        
    }
    
    
    //房源记录数据处理
    private function myRecordListData($data_info,$allStatus){
        if(CommonBase::isFullArray($data_info)){
            foreach ($data_info as $key=>$value){   
				if($value['status']==2){
					$color = "green";
				}elseif($value['status']==3){
                    $color = "red";
				}else{
					 $color = "";
				}
                $data_info[$key]['status'] = "<span style='color:".$color."'>".$allStatus[$value['status']]."</span>";
                $data_info[$key]['check_time'] = $value['check_time'] == "0000-00-00 00:00:00" ? "" : $value['check_time'];
                $data_info[$key]['feedback'] = $value['feedback']!='' ? $value['feedback'] : '——';                
                $data_info[$key]['reason'] = $value['reason'] == '' ? '' : $this->getComplainReason($value['reason']);                
                
            }
            return $data_info;            
        }    
    }
    
    /**
     * 获取举报原因
     */
    function getComplainReason($reason_type){
        $reason_arr= explode('|', $reason_type);
        if(count($reason_arr)>0){
             if(CommonBase::isFullArray($reason_arr)){
                 foreach ($reason_arr as $value){
                     $reason[] = $this->allReason[$value];
                 }
                $reason = implode('<br/>', $reason);                 
             }
        }else{
            $reason = "";
        }        
        return $reason;
    }


   /**
    * 添加举报记录
    */    
    public function ajaxComplain(){      
        $post_param = $this->input->post(NULL , TRUE);        
        $house_id = intval($post_param['houseid']);
        $house_telno = $this->textConvert($post_param['telno']);
        $house_address = $this->textConvert($post_param['address']);        
        $reason_arr = $post_param['reason'];
        $house_description = $this->textConvert($post_param['description']);
      
        //是否加入黑名单
        if(!$this->joinBlackList()&&$this->getComplainNum()<5){
             //判断是否被同公司人举报和房源是否下架
            if(!$this->isInvalid($house_id)&&!$this->complainBySameCompany($house_id)){         
               $complain_record = new ComplainRecord();
               $reason = $this->complainReason($reason_arr);
			   $complain_broker = $this->getBrokerIdByHouse($house_id);
               $is_bid = $this->isBidHouse($house_id) ? 1 : 0;
               $fieldData = array('house_id'=>$house_id,'tbl'=>'sell','is_bid'=>$is_bid,'broker_id'=>$this->user_arr['uid'],
				   'complain_broker'=>$complain_broker,'house_telno'=>$house_telno,'house_address'=>$house_address,
				   'reason'=>$reason,'description'=>$house_description,'status'=>'1');
             //  var_dump($fieldData); 
			   //var_dump($fieldData);
               $insert_return = $complain_record->insert($fieldData);               
               $return = $insert_return>0 ? array('status'=>1,'msg'=>'加入记录成功') : array('status'=>2,'msg'=>'加入记录失败');
            }else{
               $return = array('status'=>3,'msg'=>'已下架或被举报');
            } 
        }else{
            $return = array('status'=>4,'msg'=>'加入黑名单或当日举报超过3次！');
        }
        echo json_encode($return);       
       
    }
    
    /**
     * 虚假房源判断
     */
    public function judgeHouse(){
        $house = $this->input->post('house',TRUE);
        if($this->isInvalid($house)){
            $status = 2;//已经下架
        }elseif ($this->houseComplainNum($house)>=3) {
            $status = 3;//举报大于三个
        }elseif($this->complainBySameCompany($house)){
            $status = 4;//被自己公司经纪人举报
        }elseif($this->isBidHouse($house)){
            $status = 1;//是竞投房源           
        }else{
            $status = 5;//普通房源     
        }
        echo  $status;
    }
    
    
    
    /**
     * 举报人是否加入黑名单(加缓存)
     */
    private function joinBlackList(){        
        $key = $this->config_cityflag."_complain_join_black_list_".$this->user_arr['uid'];
        $return = $this->mc->get($key);
        if($return === false) {
            $BrokerBlacklist = new ComplainBrokerBlacklist();
            $blacklist = $BrokerBlacklist->findByBroker($this->user_arr['uid']);
            $return = count($blacklist)>0 ? TRUE :FALSE;
        }
        return $return;
    }
    
    /**
     * 当天举报次数
     */    
    private function getComplainNum(){
        $complainRecord = new ComplainRecord();
        $time = date('Y-m-d');
        $start_time = $time." 00:00:00";
        $end_time = $time." 23:59:59";
        $conf = "broker_id = ".$this->user_arr['uid']." and add_time>'".$start_time."' and add_time< '".$end_time."'";
        $complain_count = $complainRecord->findCountByConf($conf);
        return $complain_count;        
    }
    
    /**
     * 投诉原因存储前处理
     */
    private function complainReason($reason_arr){       
        return implode('|', $reason_arr);
    }
    
    /**
     * 房源是否被同公司的经纪人举报过
     */
    public function complainBySameCompany($house){
        //查找出举报该房源的记录
        $complainRecord = new ComplainRecord();        
        $is_same = FALSE;
        $house_arr = $complainRecord->findByHouseIdFromDb($house);
        if(count($house_arr)>0){
            //经纪人同一总公司下的所有分公司
            $all_company_code = $this->complain_model->all_company_code($this->user_arr['agentcode']);			
            foreach($house_arr as $value){
                $this->broker_model->set_uid($value['broker_id']);                
                $broker_info = $this->broker_model->get_broker_info();
                $broker_agent[] = $broker_info['agentcode'];
            }		
			$broker_agent = $this->arrToLow($broker_agent);
			$all_company_code = $this->arrToLow($all_company_code);		
            $same_agent_arr = array_intersect($broker_agent, $all_company_code);
		
            if($same_agent_arr){
               $is_same =  TRUE;
            }
        }
        
        return $is_same;
    }    
    
    
    /**
     * 房源是竞投房源（加缓存）
     */
    public function isBidHouse($house){
        $key = $this->config_cityflag."_complain_bid_hosue_".$house;
		//$this->mc->delete($key);//缓存取消
        $return = $this->mc->get($key);
        if($return === false) {
            $bidHouse = new GrowthBidHouseRecordFinish();
            $date_time = date('Y-m-d H:i:s');
            $where = "house_id = $house and tg_start_time<='".$date_time."' and '".$date_time."'<=tg_end_time";
            $house_num = $bidHouse->findNumberBy($where);			
            $return = $house_num>0 ? TRUE : FALSE;
            $this->mc->set($key,$return,600);	
        }
            return $return;
    }
    
    /**
     * 房源是否下架(加缓存)
     */
    public function isInvalid($house){     
        $key = $this->config_cityflag."_complain_is_Invalid_".$house;
		//$this->mc->delete($key);//缓存取消
        $return = $this->mc->get($key);
        if($return === false) {
            $this->load->model('sell_model');        
			$conf['id']=$house;
            $house_info = $this->sell_model->find_one_by($conf);			
            $house_info['esta'] = isset($house_info['esta']) ? $house_info['esta'] : 0;			
            $return = $house_info['esta']!=1 ? TRUE : FALSE;
            $this->mc->set($key,$return,600);	
        }
        return $return;
    }

	/**
     * 房源是否下架(加缓存)
     */
    public function getBrokerIdByHouse($house){     
        $key = $this->config_cityflag."_complain_broker_id_".$house;
		//$this->mc->delete($key);//缓存取消
        $uid = $this->mc->get($key);
        if($uid === false) {
            $this->load->model('sell_model');        
			$conf['id']=$house;
            $house_info = $this->sell_model->find_one_by($conf);			
            $uid = $house_info['uid'];	
            $this->mc->set($key,$uid,86400);	
        }
        return $uid;
    }
    
    /**
     * 房源是被几个人举报过
     */
    public function houseComplainNum($hosue){
        $complainRecord = new ComplainRecord();         
        $house_count = $complainRecord->findCountByHouseId($hosue);
        return $house_count;
    }
    
    /**
     *
     * @return boolean 成功时返回true，失败时返回等级
     */
    private function checkAccess() {
        //判断有无权访问
        $group_id = $this->user_arr['groupid'];      
        if ($group_id == 1) {
            return true;
        } else {
            return false;
        }
    }


    /**
    * 初始化分页参数
    *
    * @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());
        }
    }
    
    
     /**
     * 举报可得的房豆
     */
    private function getComplainHouseScore($groupId) {
        $key = $this->config_cityflag .'growth_credit_way_alias_package_complain_house_2'.$groupId;
		//$this->mc->delete($key);
        $complainHouseScore = $this->mc->get($key);
        if($complainHouseScore === false){
            $growthCreditWayPackage = new PaymentHousebeanWay();
            $complainBidHouseScore = $growthCreditWayPackage->getNumByWayAlias('complainBid',$groupId);
            $complainCommanHouseScore = $growthCreditWayPackage->getNumByWayAlias('complainComman',$groupId);
			 $complainDeleteHouseScore = $growthCreditWayPackage->getNumByWayAlias('complainDelete',$groupId);
            $complainHouseScore = array('bid'=>$complainBidHouseScore,'comman'=>$complainCommanHouseScore,'delete'=>$complainDeleteHouseScore);
            $this->mc->set($key,$complainHouseScore,300);
        }
        return $complainHouseScore;
    }
    
    
    //中文编码转换
    private function textConvert($answerText){
        $answerText = urldecode($answerText);
        return  iconv('utf-8','gb2312',$answerText);        
    }
    
    //
    
    

     
    //一个月内举报成功记录
    private function getSuccessComplain(){
        $paymentHousebeanRecord = new PaymentHousebeanRecord();
        
        $paymentHousebeanRecord->getListBy('', $starttime, $endtime, '', $wayAlias);
           
    }

    //数组大写转小写
	private function arrToLow($arr){
		if(is_array($arr)&&!empty($arr)){
			foreach($arr as $key=>$value){
				$temp[$key] = strtolower($value);
			}
		}
		return $temp;		
	}

	 //显示页面
    public function view($menu_key  = 'index', $page_key  = 'index', $data = array())
    {
        global $gb_sql_num, $gb_sql_arr;

        $data['gb_sql_num'] = $gb_sql_num;
        $data['gb_sql_arr'] = $gb_sql_arr;
        $data['admin_debug'] = $this->input->cookie('admin_debug', TRUE);

        $left_arr = $this->config->item('left_menu');
        $no_show_arr = array();//array('index'); 


        /****虚假房源举报屏蔽免费经纪人start****/
        if($this->user_arr['groupid'] == 2){
            $no_show_arr[] = 'complain';
            $no_show_arr[] = 'my_list';
        } 
        /*****虚假房源举报屏蔽屏蔽免费经纪人end****/

        $this->load->model('package_model');
        $package = $this->package_model->find_by_id($this->user_arr['package_id']);
        if ($menu_key == 'house_manage')//控制发布出售和出租的权限
        {
            if (isset($package['package_sell_purview']) 
                    && $package['package_sell_purview'] != 1) //没有发布出售的权限
            {
                $no_show_arr[] = 'sell_modify';
                $no_show_arr[] = 'sell_manage';
                $no_show_arr[] = 'sell_manage_invalid';
                $no_show_arr[] = 'sell_manage_frozen';
                //$no_show_arr[] = 'buy_match_manage';
                
            }
            if (isset($package['package_rent_purview']) 
                    && $package['package_rent_purview'] != 1) //没有发布出租的权限
            {
                $no_show_arr[] = 'rent_modify';
                $no_show_arr[] = 'rent_manage';
                $no_show_arr[] = 'rent_manage_invalid';
                $no_show_arr[] = 'rent_manage_frozen';
                //$no_show_arr[] = 'rent_match_manage';
            }
        }
        
        //头部房源管理链接
        $header_house_url = '/sell/manage/active/';
        if(isset($package['package_sell_purview']) 
                    && $package['package_sell_purview'] != 1){
            $header_house_url = '/rent/manage/active/';
        }
        
        $data['header_data_arr'] = $this->user_arr;
        $this->load->model('message_model');
        $data['message_num'] = $this->message_model->get_message_no_read($this->user_arr['uid']);
        $data['memu_key'] = $menu_key;
        $data['memu'] = $left_arr;
        $data['header_house_url'] = $header_house_url;

		if(!empty($_GET['testw']))
		{
			$this->load->view('header_wang', $data);
		}
		else
		{
			$this->load->view('header', $data);
		}
        $left_arr[$menu_key][]="complain/complain_xiao";
        if(isset($left_arr[$menu_key]) 
                && is_array($left_arr[$menu_key]) && count($left_arr[$menu_key]) > 0 
                && $this->my_in_array($page_key, $left_arr[$menu_key]))
        {
            $left_menu_num = count($left_arr[$menu_key]);

            if( count($no_show_arr) > 0 )
            {   
                //去掉不显示的菜单项
               foreach ( $left_arr[$menu_key] as $key =>$value)
                {   
                   if( is_array($value) && !empty($value))
                   {    
                        foreach($value as $sub_key => $sub_val)
                        {   
                            if( in_array( $sub_val , $no_show_arr) )
                            {   
                                unset($left_arr[$menu_key][$key][$sub_key]);
                            }
                        }
                   }
                   else
                   {
                        if( in_array( $value , $no_show_arr))
                        {   
                            unset($left_arr[$menu_key][$key]);
                        }
                   }
                }
            }
            
            $menu_left_arr = array_values(array_filter($left_arr[$menu_key]));
            if(is_array($menu_left_arr) && !empty($menu_left_arr))
            {  
                $this->load->view('left_xiao', array('menu_left_arr'=>$menu_left_arr, 'page_key'=>$page_key));
            }
        }
        $this->load->view($page_key,$data);
        $this->load->view('footer');
    }

	 private function my_in_array($v,$arr) {
        $flag = false;
        foreach ($arr as $va) {
            if(!is_array($va)) {
                if($va == $v) {
                    $flag =  true;
                    break;
                } else {
                    continue;
                }
            } else {
                $flag = $this->my_in_array($v, $va);
                if($flag) {
                    break;
                } else {
                    continue;
                }
            }
        }
        return $flag;
    }
}