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

class Personal_house extends MY_Controller {

    private $library;

    /**
     * 解析函数
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * Index Page for this controller.
     */
    public function index()
    {
        $this->sell();
    }

    /**
     * Get the sell house
     */
    public function sell()
    {
        $pg = $this->input->post('page', TRUE);
        $page = intval($pg) > 0 ? intval($pg) : 1;

        $this->load->library('server',array('appName'=>NS_SELL,'strCheckMethod'=>"",'returnMethod'=>"ary",'returnCharSet'=>"gbk"));

        $this->load->model('broker_model');
        $dist = $this->broker_model->get_broker_district();

        $arr = '' != $dist ? $this->_get_house($this->server, 'sell', $dist) : array('data'=>array(), 'pages'=>'');
        $data_arr['house_arr'] = $arr['data'];
        // var_dump($this->server);exit;
        $data_arr['pages'] = $arr['pages'];
        $data_arr['tab'] = 'sell';
        $data_arr['dist'] = $dist;
        $data_arr['page_title'] = '本区个人房源-出售房源';
        $data_arr['css'] = load_css('zsb/css/v1.0/style1.css');
        $data_arr['google_analytics'] = get_ga_js_code('/营销中心/本区个人房源/出售房源/'.$page.'/');
        $this->view('market', 'personal_house', $data_arr);
    }

    /**
     * Get the rent house
     */
    public function rent()
    {
        $pg = $this->input->post('page', TRUE);
        $page = intval($pg) > 0 ? intval($pg) : 1;
        $this->load->library('server',array('appName'=>NS_RENT,'strCheckMethod'=>"",'returnMethod'=>"ary",'returnCharSet'=>"gbk"));

        $this->load->model('broker_model');
        $dist = $this->broker_model->get_broker_district();

        $arr = '' != $dist ? $this->_get_house($this->server, 'rent', $dist) : array('data'=>array(), 'pages'=>'');
        $data_arr['house_arr'] = $arr['data'];
        $data_arr['pages'] = $arr['pages'];
        $data_arr['tab'] = 'rent';
        $data_arr['dist'] = $dist;
        $data_arr['page_title'] = '本区个人房源-出租房源';
        $data_arr['css'] = load_css('zsb/css/v1.0/style1.css');
        $data_arr['google_analytics'] = get_ga_js_code('/营销中心/本区个人房源/出租房源/'.$page.'/');
        $this->view('market', 'personal_house', $data_arr);
    }

    /**
     * 获取房源
     */
    private function _get_house($server, $tbl, $dist)
    {
        if('' == $server->appName OR !in_array($tbl, array('sell', 'rent')))
        {
            return array();
        }

        $pg = $this->input->post('page', TRUE);
        $page = intval($pg) > 0 ? intval($pg) : 1;
        unset($pg);
        $pagesize = 20;
        $offset=$pagesize*($page-1);

        //起始时间
        $starttime = strtotime('-1 day');
        $endtime = time()-600;
        if ($tbl == 'sell') {
            $strCondition = 'id,uid,infotype, blockshowname, room, hall, buildarea, price, creattime, contactor, telno,tel400';
        } else {
            $strCondition = 'id,uid,infotype, blockshowname, room, hall, buildarea, price, creattime, priceunit, renttype, contactor, telno';
        }
        /*
        $sql = "SELECT ".$strCondition." FROM ".$tbl." WHERE infofrom = 1 and esta = 1 and creattime >= '".$starttime."' and district = '".$dist."'
            ORDER BY updatetime DESC LIMIT ".$offset.",".$pagesize." LUC";
		*/

        $sql = "SELECT ".$strCondition." FROM ".$tbl." WHERE infofrom = 1 and esta = 1 and creattime <='$endtime' and creattime >= '".$starttime."' and district = '".$dist."'
		
            ORDER BY updatetime DESC LIMIT ".$offset.",".$pagesize." LUC";
        //$sql ="SELECT id FROM rent WHERE infofrom = 1 and esta = 1 luc";

        $ary = $server->query($sql);

        $numrows = intval($ary["TOTAL"]);
        $pages = $numrows ? ceil($numrows/$pagesize) : 0;  //计算总页数
        $page = $page > $pages ? $pages : $page;  //判断跳转页数

        $return = array();
        if(count($ary["Record"]) > 0)
        {
            $j = 0;
            foreach($ary["Record"] as $value){

                $arr_key=array_keys($value);
                for($i=0;$i<count($arr_key);$i++){
                    $value[strtolower($arr_key[$i])] = $value[$arr_key[$i]];
                    unset($value[$arr_key[$i]]);
                }
                $arr[$j]=$value;

                $j++;
            }

            $this->load->helper('common_url');
            $house_conf = $this->config->item('house');
            foreach($arr as &$val)
            {
                $val['url'] = $tbl =='sell' ? get_sellinfo_url($val['id']) : get_rentinfo_url($val['id']);
                $val['unit'] = $tbl =='sell' ? '万' : $house_conf['personunit'][$val['priceunit']];
                $val['type'] = $tbl =='sell' ? '' : $val['renttype'];
                $val['infotype_str'] = $house_conf['infotype'][$val['infotype']];

                //如果是隐私保护房源则显示400号码
                if(isset($val['uid']) && $val['uid'] > 0 && isset($val['tel400']) && $val['tel400'] == 1  )
                {
                    $this->load->helper('common_api');
                    $api_url = USER_CENTER.'api_400/get_telno400_by_uid/';
                    $api_url_param = $val['uid'].'/'.GB_CITY;
                    $telno_400_json = get_api($api_url.$api_url_param);
                    if(!empty($telno_400_json))
                    {
                        $telno_info = json_decode($telno_400_json , TRUE);
                        if(isset($telno_info[0]['num_400']) && isset($telno_info[0]['num_group']))
                        {
                            $telno_400 = $telno_info[0]['num_400'].'转'.$telno_info[0]['num_group'];
                            $val['telno'] = $telno_400;
                        }
                    }
                }
            }

            $return['pages'] = helper_pagination($page, $pages, 0);

            $return['data'] = $arr;
        }

        return $return;
    }


    public function loupan_talent()
    {
        $uid        =$this->user_arr['uid'];
        $this->load->model('loupan_model');

        $claim_data =$this->loupan_model->getBlockInfoByUid($uid);
        //echo $uid;die;
        if(isset($_GET['district'])){
            $district =$_GET['district'];
        }else
        {
            $district =0;
        }
        $data_arr =array();
        $data_arr['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css,zsb/css/v1.0/feedback.css');
        //需要加载的JS
        $data_arr['js'] = load_js('zsb/js/v1.0/collect.js,common/js/swf/swfupload.js,zsb/js/v1.0/swfu_building.js,zsb/js/v1.0/handlers_building.js,zsb/js/v1.0/handlers_building1.js,zsb/js/v1.0/handlers_building2.js,zsb/js/v1.0/handlers_building3.js,zsb/js/v1.0/handlers_building5.js');

        $data_arr['uid']  =$uid;
        $explain_switch              =$this->loupan_model->read_loupan($uid);

        if(count($claim_data))
        {
            //小区认领成功页面
            $data_building              =$this->loupan_model->getBuildingByBlockId($claim_data['0']['id'],$uid);
            //取消按钮展示
            $cancel_button              =$this->loupan_model->cancal_button_info($claim_data['0']['id'],$uid);

            $data_arr['data_building']  =$data_building;
            $data_arr['claim_data']      =$claim_data;
            $data_arr['explain_switch']      =$explain_switch;
            $data_arr['page_title']      = '楼盘达人征集';
            $data_arr['cancel_button']   =$cancel_button;
            $this->view('market', 'personal_house/loupan_talent_building', $data_arr);
        }else
        {
            //小区待认领页面

            $house = $this->config->item('house');
            $house['district_talent'] =array_values($house['district_talent']);

            $district_str =$house['district_talent'][$district];
            $data_arr['district']= $house['district_talent'];
            $this->load->model('loupan_model');
            $data_arr['block']      =$this->loupan_model->getBlockInfoByDistrict($district_str);
            // print_r($data_arr);die;
            $data_arr['page_title'] = '楼盘达人征集';
            $data_arr['explain_switch']      =$explain_switch;
            $this->view('market', 'personal_house/loupan_talent', $data_arr);
        }

    }

    public function loupan_read()
    {
        $uid        =$this->user_arr['uid'];
        $this->load->model('loupan_model');

        $claim_data =$this->loupan_model->getReadInfoUid($uid);


        $explain_switch  =$this->loupan_model->read_loupan($uid);

        if($explain_switch==0)
        {
            $this->jump(GB_WO_URL);
            exit;
        }
        $new_block_id   =$claim_data['0']['new_block_id'];

        $template_info  =$this->loupan_model->get_template_info($new_block_id);



        $data_arr   =array();
        $data_arr['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css,zsb/css/v1.0/feedback.css');
        $data_arr['js'] = load_js('zsb/js/v1.0/actual.min.js,common/js/swf/swfupload.js,zsb/js/v1.0/swfu_read.js,zsb/js/v1.0/handlers_read.js,zsb/js/v1.0/handlers_read1.js,zsb/js/v1.0/handlers_read2.js,zsb/js/v1.0/handlers_read3.js');
        $data_arr['explain_switch']     = $explain_switch;
        $data_arr['claim_data']         =$claim_data;
        $data_arr['page_title'] = '多维解读';
        $data_arr['templateinfo'] = $template_info;
        $this->view('market', 'personal_house/loupan_read', $data_arr);
    }

    public function cancal_button_set()
    {
        $uid        =$this->user_arr['uid'];
        $new_block_id   =$_GET['new_block_id'];
        $this->load->model('loupan_model');
        $arr =$this->loupan_model->add_cancal_log($new_block_id,$uid);
        echo $arr;
    }



    public function get_block_claim()
    {
        $id     =   $_POST['id'];
        $this->load->model('loupan_model');

        $data       =$this->loupan_model->getBlockInfoById($id);
        $days       =$data[0]['contribution_days']-1; //当天算一天

        $time       = strtotime("+$days day");

        $month      =date('m',$time);
        $day        =date('d',$time);
        $arr        =array();
        $arr['blockname']  =iconv('GBK','utf-8',$data[0]['blockname']);
        $msg       ="认领后您需要在".$month."月".$day."日前提交该小区楼栋照片，是否确认认领？";
        $arr['msg']  =iconv('GBK','utf-8',$msg);
        echo json_encode($arr);
    }

    public function set_block_claim()
    {
        $result     =array();
        $result['status']=0;
        $result['msg']='小区认领失败!';
        $this->load->model('loupan_model');
        $id                     = $_POST['id'];
        $data['id']             =$id;
        $data['contribution_open_time'] =time();
        $arr                    =$this->loupan_model->getBlockInfoById($id);

        if($arr[0]['claim_uid']>0 || $arr[0]['lock_build_contribution']>0)
        {
            echo json_encode($result);exit;
        }
        $data['contribution_end_time'] =strtotime(date('Y-m-d'))+(($arr[0]['contribution_days'])*86400)-1;
        $data['claim_status']   =1;
        $data['claim_uid']      =$this->user_arr['uid'];
        $this->loupan_model->setBlockClaimById($data);

        $val_arr =$this->loupan_model->get_new_block_uid_log($this->user_arr['uid'],$id);
        $val_arr =array();

        if(empty($val_arr)) {
            //添加认领日志
            $insert_data = array();
            $insert_data['uid'] = $this->user_arr['uid'];
            $brokerInfo = $this->loupan_model->getbrokerinfo($this->user_arr['uid']);
            $insert_data['username'] = $brokerInfo[0]['username'];
            $insert_data['truename'] = $brokerInfo[0]['truename'];
            $insert_data['telno'] = $brokerInfo[0]['telno'];

            $insert_data['new_block_id'] = $id;
            $new_block_info = $this->loupan_model->getBlockInfoById($id);
            $insert_data['blockname'] = $new_block_info['0']['blockname'];

            $insert_data['ctime'] = time();
            $insert_data['etime'] = $data['contribution_end_time'];

            $this->loupan_model->addBlockUid($insert_data);

        }
        $result['status']=1;
        $result['msg']='小区认领成功!';
        echo json_encode($result);exit;


    }

    /**
     * 点击楼栋获取上传图片的信息
     */
    public function select_building_info()
    {
        $buildid =$_GET['flag_id'];
        $this->load->model('loupan_model');
        $buildname  =$this->loupan_model->getbuildname($buildid);

        $result     =array();
        $result['status']=1;
        $result['buildname']    =iconv('gbk','utf-8',$buildname);
        $data =json_encode($result);
        echo $data;

    }

    /**
     *
     */
    public function set_building_images()
    {
        $result             =array();
        $data               =$_POST['data'];
        $buildid            =$_POST['buildid'];
        $new_block_id       =$_POST['new_block_id'];
        $buildname          =$_POST['buildname'];

        $uid        =$this->user_arr['uid'];
        $arr        =explode('&',$data);

        if(!isset($new_block_id))
        {
            $num =count($arr);
            $arr_new =$arr[$num-1];
            $new_block_id_arr =explode('=',$arr_new);
            $new_block_id     =$new_block_id_arr[1];
        }



        $this->load->model('loupan_model');

        if(trim($buildid,'')=='add_build')  //经纪人自己添加楼栋
        {
            $buildname =iconv('utf-8','gbk',$buildname);

            //print_r($arr);
            unset($arr[0]);
            unset($arr[count($arr)]);
            $this->load->model('loupan_model');

            $buildid    =$this->loupan_model->get_block_build_name_info($new_block_id,$buildname);

            //楼栋名称名称不能重复
            if($buildid==1)
            {
                $result['status']   =2;
                echo json_encode($result);exit;
            }
            else
            {
                $is_new =1;
            }
        }else
        {

            unset($arr[count($arr)-1]);
            $is_new =0;
        }
        //echo $is_new;die;
        //print_r($arr);die;

        //防止重复提交
        $this->loupan_model->check_building_check_manage($buildid,$uid);

        $build_manage_id    =$this->loupan_model->insert_building_check_manage($buildid,$uid,$is_new);
        $this->loupan_model->update_new_block_uid_log($new_block_id,$uid);
        foreach ($arr as $key =>$rs)
        {
            $val =urldecode($rs);
            $this->loupan_model->insert_building_images($val,$buildid,$uid,$build_manage_id);
        }

        $result['status']   =1;
        echo json_encode($result);

    }

    /**
     * 添加信息报错
     */
    public function add_error_read()
    {
        $uid                =$this->user_arr['uid'];
        $result             =array();
        $data_val           =$_POST['data'];
        $error_str          =$_POST['error_str'];
        $arr        =explode('&',$data_val);
        $this->load->model('loupan_model');

        $this->loupan_model->check_add_error($uid);
        $this->loupan_model->addErrorRead($arr,$error_str,$uid);

        $result['status']   =1;
        echo json_encode($result);

    }

    public function set_read_loupan()
    {
        $data   =array();
        $data['house_read']             =iconv('UTF-8','GBK',$_POST['house_read']);
        $data['mating_facility']        =iconv('UTF-8','GBK',$_POST['mating_facility']);
        $data['block_defect']           =iconv('UTF-8','GBK',$_POST['block_defect']);
        $data['build_dist']             =iconv('UTF-8','GBK',$_POST['build_dist']);
        $data['safe_keep']              =iconv('UTF-8','GBK',$_POST['safe_keep']);
        $data['health_keep']            =iconv('UTF-8','GBK',$_POST['health_keep']);
        $data['park_manage']            =iconv('UTF-8','GBK',$_POST['park_manage']);
        $data['block_advantage_pic']    =iconv('UTF-8','GBK',$_POST['block_advantage_pic']);
        $data['block_defect_pic']       =iconv('UTF-8','GBK',$_POST['block_defect_pic']);
        $data['build_dist_pic']         =iconv('UTF-8','GBK',$_POST['build_dist_pic']);
        $data['property_manage_pic']    =iconv('UTF-8','GBK',$_POST['property_manage_pic']);
        $new_block_id                   =iconv('UTF-8','GBK',$_POST['new_block_id']);

        $this->load->model('loupan_model');
        $this->loupan_model->setReadLoupan($data,$new_block_id);

    }

    //我的贡献
    public function loupan_my_contribution(){

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->model('loupan_model');
        $this->_limit       = 10;
        $uid         = $this->user_arr['uid'];

        $this->load->model('loupan_model');

        $claim_data        =$this->loupan_model->getBlockInfoByUid($uid);
        $explain_switch    =$this->loupan_model->read_loupan($uid);
        /** 分页参数 */
        $page = $this->input->post( 'page' , TRUE);
        $page = (isset($page)&& intval($page) > 0) ? intval($page) : 1;
        $this->_init_pagination($page);
        if($_GET['type'] == 'explain'){
            $total_count = $this->loupan_model->getMyExplainTotal($uid);
            $pages       = $total_count > 0 ? ceil( $total_count/$this->_limit ) : 0;
        }elseif ($_GET['type'] == 'error_report')
        {
            $total_count = $this->loupan_model->getErrorReportTotal($uid);
            $pages       = $total_count > 0 ? ceil( $total_count/$this->_limit ) : 0;
        }
        else{
            $total_count = $this->loupan_model->getMyContributionTotal($uid);
            $pages       = $total_count > 0 ? ceil( $total_count/$this->_limit ) : 0;
        }


        //是否显示分页
        $pagination = NULL;
        if( $total_count > $this->_limit)
        {
            $pagination = helper_pagination( $this->_current_page,$pages,$total_count);
        }

        $data_arr    = array();
        $data_arr['css'] = load_css('zsb/css/v1.0/style1.css,zsb/css/v1.0/realhouse.css,zsb/css/v1.0/feedback.css');
        $data_arr['js'] = load_js('common/js/My97DatePicker/WdatePicker.js');
        $result    = $this->loupan_model->getMyContribution($uid,$this->_offset ,$this->_limit);
        $result2   = $this->loupan_model->getMyExplain($uid,$this->_offset ,$this->_limit);
        $result3   = $this->loupan_model->getMyErrorReport($uid,$this->_offset ,$this->_limit);

//

        if($_GET['type'] == 'explain'){
            $data_arr['contribution_info']  = $result2;
        }
        elseif($_GET['type'] == 'error_report'){
            $data_arr['contribution_info']  = $result3;
        }
        else{
            $data_arr['contribution_info']  = $result;
        }

        $data_arr['page']               = $this->_current_page;
        $data_arr['pagination']         = $pagination;
        $data_arr['explain_switch']     = $explain_switch;
        $this->view('market', 'personal_house/loupan_my_contribution', $data_arr);

    }
    /**
     * 初始化分页参数
     *
     * @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());
        }
    }



}
