<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of market_bid_house_manage
 *
 * @author Administrator
 */
class market_bid_house extends MY_Controller {
    
    const TYPE_BLOCK='block';
    const TYPE_HOTWORD='hotword';

    private $uid;
    private $info;
    private $house;
    private $broker;

    /**
     *
     * @var GrowthBrokerCredit 
     */
    private $growthBrokerCredit;
    /**
     *
     * @var GrowthBrokerBidHouse 
     */
    private $growthBrokerBidHouse;
    
    public function __construct($type = NULL) {
        parent::__construct($type);
        $this->initUserInfo();
        $this->checkAuth();
        $this->load->library('TabPage');
        $this->house = $this->config->item('house');
        $this->growthBrokerCredit = new GrowthBrokerCredit($this->broker);
        $this->initGrowthBrokerBidHouse();
        $this->load->helper('common_url');
		$this->load->helper('common_string');
    }

    public function hotword($tabName, $houseId,$bid=null) {
        if (!in_array($tabName, array('on', 'history'))) {
            show_404();
        }
        $type = 2;//
        if ($tabName == 'on') {
            $viewData = $this->on($houseId,$type,$bid);
        } else if ($tabName == 'history') {
            $viewData = $this->history($houseId,$type,$bid);
        }
        $this->view('market', 'market_bid_house/bid_house', $viewData);
    }
    
    public function block($tabName,$houseId,$bid=null) {
        if (!in_array($tabName, array('on', 'history'))) {
            show_404();
        }
        $type = 1;
        if ($tabName == 'on') {
            $viewData = $this->on($houseId,$type);
        } else if ($tabName == 'history') {
            $viewData = $this->history($houseId,$type,$bid);
        }
        $this->view('market', 'market_bid_house/bid_house', $viewData);
    }
	
	//区属词竞投
	public function districtword($tabName,$houseId,$bid=null) {
        if (!in_array($tabName, array('on', 'history'))) {
            show_404();
        }

        $functionSwitch = $this->config->item('functionSwitch');
        if(empty($functionSwitch['growthBidHouseDistrict']))
        {
            show_404();
        }

        $type = 3;
        if ($tabName == 'on') {
            $viewData = $this->on($houseId,$type);
        } else if ($tabName == 'history') {
            $viewData = $this->history($houseId,$type,$bid);
        }
        $this->view('market', 'market_bid_house/bid_house', $viewData);
    }
	
	//板块词竞投
	public function streetword($tabName,$houseId,$bid=null) {
        if (!in_array($tabName, array('on', 'history'))) {
            show_404();
        }

        $functionSwitch = $this->config->item('functionSwitch');
        if(empty($functionSwitch['growthBidHouseStreet']))
        {
            show_404();
        }

        $type = 4;
        if ($tabName == 'on') {
            $viewData = $this->on($houseId,$type);
        } else if ($tabName == 'history') {
            $viewData = $this->history($houseId,$type,$bid);
        }
        $this->view('market', 'market_bid_house/bid_house', $viewData);
    }

    /**
     * 本期竞投
     * @param type $houseId 房源id
     * @param type $type 1，小区词，2，热词
     * @param type $tab 'on' 当前，'history' 历史
     * @return type
     */
    private function on($houseId,$type=1,$bid=null) {
        //$status = $tab;
        $tab='on';
        $viewData['cBidPeriods'] = $this->getCBidPeriods();
        $growthBrokerBidHouse = $this->growthBrokerBidHouse;
        $records = $growthBrokerBidHouse->findHouseBidRecord($viewData['cBidPeriods']['id'], $houseId, $tab);
        $houseInfo = $growthBrokerBidHouse->findHouseBidRecordList($viewData['cBidPeriods'], $records, $type, $houseId,$bid);
        $errorCode = $growthBrokerBidHouse->getBidError();
        if ($errorCode) {
            $page_text = '房源不满足竞投标准，请重新选择!';
            $this->jump('/market_bid_house_manage/all/', $page_text,4000);
            exit;
        }
        if (!$houseInfo) {
            die();
        }
        if($houseInfo['bid']) {$bid=$houseInfo['bid'];}
		
		//竞投起拍房豆
		$this->load->model('growth_bid_start_model');
		if($type == 1)
		{
			$viewData['bidHouseBlockWord'] = $this->growth_bid_start_model->getGrowthStartHouseBeans('bidHouseBlockWord');
		}
		elseif($type == 2)
		{
			$viewData['bidHouseMarketWord'] = $this->growth_bid_start_model->getGrowthStartHouseBeans('bidHouseMarketWord');
		}
		elseif($type == 3)
		{
			$viewData['bidHouseDistrictWord'] = $this->growth_bid_start_model->getGrowthStartHouseBeans('bidHouseDistrictWord');
		}
		elseif($type == 4)
		{
			$viewData['bidHouseStreetWord'] = $this->growth_bid_start_model->getGrowthStartHouseBeans('bidHouseStreetWord');
		}
		
		$documentation = $this->config->item('documentation');
		
		$viewData['documentation'] = $documentation;
		$viewData['growthStartDate'] = $this->config->item('growthStartDate');
		$viewData['growthEndDate'] = $this->config->item('growthEndDate');
        $viewData['bid'] = $bid;
        $viewData['type'] = $type;
        $viewData['houseInfo'] = $houseInfo;
        $viewData['growthBrokerBidHouse'] = $growthBrokerBidHouse;
        $viewData['info'] = $this->info;
        //$viewData['person'] = $this->widget('person');
        $viewData['house'] = $this->house;
        $viewData['tabs'] = $this->overViewTab($type,$tab, array($houseId,$bid)); //tab页
        $viewData['tab'] = $tab;
        $viewData['person'] = $this->widget('person');
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        return $viewData;
    }

    /**
     * 竞投
     * @return type
     */
    public function bid() {
        if(isset($_SERVER['HTTP_RANGE']))
        {
            $result = array('result' => 0, 'error' => $error);
            return $result;
        }
        $bidId = $this->input->get('bid');
        $houseId = $this->input->get('houseid');//intval($_GET['houseid']);
        $score = $this->input->get('score');//intval($_GET['score']);
        $this->growthBrokerBidHouse->bid($bidId, $score, $houseId);
        $error = $this->growthBrokerBidHouse->getBidError();
        if ($error) {
            $result = array('result' => 0, 'error' => $error);
        } else {
            $result = array('result' => 1,);
        }
        return $this->ajaxResponse($result);
        //echo json_encode($result);
        /*
        if ($action == 'refreshRank' && $bid != '') {
            
        } else if ($action == 'bid' && $bid != '') {
            
        } else if ($action == 'refresh') {
            
        } else if ($action == 'attention' && $bid != '' && $houseid != '') {
            
        }*/
    }

    /**
     * 刷新战况
     */
    public function refreshRank() {
        $growthBidHouse = new GrowthBidHouse();
        $bidOne = $growthBidHouse->findById($bid);
        $bidRecordInfo = $growthBrokerBidHouse->getNewBidBaseInfo($bidOne);
        $myRecords = $growthBrokerBidHouse->findHouseBidTypeRecord($bid, $id);
        //print_r($bidRecordInfo['records']);
        //print_r($myRecords);
        $rankHtml = $growthBrokerBidHouse->rankList($bidRecordInfo['records'], $cBidPeriods['status'], '', $myRecords);
        $rankHtml = iconv('GB2312', 'UTF-8', urlencode(addslashes($rankHtml)));
        echo urldecode(json_encode(array('number' => $bidRecordInfo['number'], 'recordHtml' => $rankHtml)));
    }

    /**
     * 刷新 页面的ajax响应
     * @return type
     */
    public function refresh() {
        $houseId = $this->input->get('houseid');
        $type = $this->input->get('type');
        $bid = $this->input->get('bid');
        if(!$type){$type=1;}
        $viewData = $this->On($houseId,$type,$bid);
        $data = $this->load->view('market_bid_house/on',$viewData,true);		
        return $this->ajaxResponse($data, 'gbk', 'text');
    }

    /**
     * 关注
     */
    public function attention() {
        //$houseid = intval($_GET['houseid']);
        $houseId = $this->input->get('houseid');
        $bidId = $this->input->get('bid');//intval($_GET['bid']);
        if ($bidId) {
            //检查是否可以关注
            $attentionNumber = GrowthBidAttentionHelper::totalNumber($this->broker);
            //echo $attentionNumber;exit;
            //达到最大关注数
            if ($attentionNumber >= GrowthBidAttentionHelper::ATTENTION_MAX_NUMBER) {
                $data['result'] = 0;
                $data['error'] = '-2';
                return $this->ajaxResponse($data);
            }
            $growthBrokerBidHouse = $this->growthBrokerBidHouse;
            $re = $growthBrokerBidHouse->checkAttention($bidId, $houseId);
            $data = array();
            if ($re) {
                //关注
                $cBidPeriods = $this->getCBidPeriods();
                $attentionId = $growthBrokerBidHouse->attent($bidId, $cBidPeriods['id'], $houseId);
                $data['result'] = 1;
                $data['attention_id'] = $attentionId;
            } else {
                $data['result'] = 0;
                $bidError = $growthBrokerBidHouse->getBidError();
                $data['error'] = $bidError;
            }
        } else {
            $data['result'] = 0;
        }
        return $this->ajaxResponse($data);
    }

    /**
     * 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;
    }
    /**
     * 初始化成长体系类
     */
    private function initGrowthBrokerBidHouse() {
        $growthConfig = $this->config->item('growth');
        $mode = $growthConfig['mode'];
        $this->growthBrokerBidHouse = new GrowthBrokerBidHouse($this->broker, $this->growthBrokerCredit,$mode);
        $this->growthBrokerBidHouse->setCheckStar(true);
        $additionalScore = $growthConfig['additionalScore']['house'];
        $this->growthBrokerBidHouse->setAdditionalScore($additionalScore);
    }

    /**
     * 最新一期的竞投
     */
    private function getCBidPeriods() {
        $growthBidPeriods = new GrowthBidPeriods();
        $cBidPeriods = $growthBidPeriods->currentBidPeriods(2);
        if (!$cBidPeriods) {
            show_404('出错啦');
        }
        return $cBidPeriods;
    }

    
    /**
     * 往期竞投参考
     * @param type $houseId
     * @param type $type 1,小区词，2，热搜词
     * @param string $tab 
     * @param type $bid
     * @return type
     */
    private function history($houseId,$type=1,$bid=null) {
        $bidHistoryRecord = array();
        $tab='history';
        $growthBrokerBidHouse = $this->growthBrokerBidHouse;
        $bids = $growthBrokerBidHouse->findBidHistoryRecordCount($type, $bid);
        $rows_all = $bids?count($bids):0;
        $per_page = 5;
        $pageSegment = 4;
        $page = $this->input->get('page')?$this->input->get('page'):1;
        $queryArray = array();
        $queryString = http_build_query($queryArray);
        if($type==1) {
            $base_url = '/market_bid_house/block/history/'.$houseId.'/'.$bid.'/?'.$queryString;
        } else {
            $base_url = '/market_bid_house/hotword/history/'.$houseId.'/'.$bid.'/?'.$queryString;
        }
        
        if ($rows_all > 0) {
            $start = ($page - 1) * $per_page;
            $bidNews = array_slice($bids, $start, $per_page);
            $bidHistoryRecord = $growthBrokerBidHouse->findBidHistoryRecordList($bidNews);
        }
        
		$documentation = $this->config->item('documentation');
		
		$viewData['documentation'] = $documentation;
        $viewData['bidHistoryRecord'] = $bidHistoryRecord;
        $viewData['bid'] = $bid;
        $viewData['type'] = $type;
        $viewData['houseId'] = $houseId;
        $viewData['info'] = $this->info;
        //$viewData['person'] = $this->widget('person');
        $viewData['house'] = $this->house;
        $viewData['tabs'] = $this->overViewTab($type,$tab, array($houseId,$bid)); //tab页
        $viewData['tab'] = $tab;
        $viewData['person'] = $this->widget('person');
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData['page'] = $this->page($rows_all, $per_page, $pageSegment, $base_url);
        return $viewData;
    }

    /**
     * 房源竞投tab页
     * @param type $type 1，小区词；2，热搜词
     * @param type $curPage
     * @return type
     */
    private function overViewTab($type,$curPage, $params = array()) {
        $tabData = array();
        //$types = $this->getTypes();
        $returnUrl = array(array('url'=>'/market_bid_house_manage/all/','name'=>'返回房源列表'));
        if($type==1) {
            //$allTab = array('all' => '全部房源', 'on' => '本期我参与的房源', 'history' => '竞投历史');
            $tabData['on'] = array('url' => '/market_bid_house/block/on/' . implode('/', $params), 'name' => '本期竞投');
            $tabData['history'] = array('url' => '/market_bid_house/block/history/' . implode('/', $params), 'name' => '往期竞投参考');
        }
        if($type==2) {
            $tabData['on'] = array('url' => '/market_bid_house/hotword/on/' . implode('/', $params), 'name' => '本期竞投');
            $tabData['history'] = array('url' => '/market_bid_house/hotword/history/' . implode('/', $params), 'name' => '往期竞投参考');
        }

		if($type==3) 
		{
            $tabData['on'] = array('url' => '/market_bid_house/districtword/on/' . implode('/', $params), 'name' => '本期竞投');
            $tabData['history'] = array('url' => '/market_bid_house/districtword/history/' . implode('/', $params), 'name' => '往期竞投参考');
        }

		if($type==4) 
		{
            $tabData['on'] = array('url' => '/market_bid_house/streetword/on/' . implode('/', $params), 'name' => '本期竞投');
            $tabData['history'] = array('url' => '/market_bid_house/streetword/history/' . implode('/', $params), 'name' => '往期竞投参考');
        }

        return $this->tabpage->generate($tabData, $curPage,$returnUrl);
    }

    private function getTypes() {
        return array(1=>'小区词',2=>'热搜词');
    }
    /**
     * 初始化经纪人信息
     */
    private function initUserInfo() {
        $info = $this->broker_model->get_user_session();

        $groupId = $info['package_id']; //套餐
        //$brokerType = $info['groupid'];//免费or付费
        $gbe = new GrowthBrokerExp(array('id' => $info['uid'], 'groupid' => $groupId));
        $gbc = new GrowthBrokerCredit(array('id' => $info['uid'], 'groupid' => $groupId));

        //等级
        $info['level'] = $gbe->getLevel(2);
        //经验
        $info['exp'] = $gbe->getExp();
        //升级天数
        /*
          $allLevel = $this->allLevel();
          $info['nextLevel'] = $this->nextLevel($info['level'],$allLevel);
          $growthExpDayLimit = $this->getGroupDayMaxExp($groupId);
          $info['level_day'] = $this->calUpgradeDays($info['nextLevel'],$growthExpDayLimit,$info['exp']);
         */
        
        $this->load->model('payment_model');
        $info['payment_url'] = $this->payment_model->get_module_url('recharge');   
        //房豆
        $info['credit'] = $gbc->getValidCredit();
        $this->info = $info;
        $this->uid = $info['uid'];
       
        $broker['id'] = $this->uid;
        $broker['level'] = 'LV'.$this->info['level'];
        $broker['credit'] = $this->info['credit'];
        $broker['groupid'] = $groupId;
        $broker['is_pay'] = $this->info['is_pay'];
        $this->broker = $broker;
    }

    /**
     * 页面小工具
     * @param type $name
     * @param type $data
     * @return type
     */
    private function widget($name, $data = null) {
        switch ($name) {
            case 'person':
				
				$documentation = $this->config->item('documentation');

                $data = array('info' => $this->info, 'introUrl' => $documentation['what_credit']);
                $person = $this->load->view('widget/person', $data, true);
                return $person;
                break;
            case 'imitateSelect':
                $value = $data['value'];
                if ($value) {
                    $data['name'] = $data['options'][$value];
                } else {
                    $data['name'] = '不限';
                }
                if (!isset($data['def'])) {
                    $data['def'] = true;
                }
                $widget = $this->load->view('widget/imitateSelect', $data, true);
                return $widget;
                break;
            default:
                break;
        }
    }
    
    private function page($total,$per_page,$pageSegment,$base_url) {
        //分页配置
        $this->load->library('pagination');
        $config['use_page_numbers'] = TRUE;
        $config['full_tag_open'] = '<div class="picPreviewPag">';
        $config['full_tag_close'] = '</div>';
        //首页
        $config['first_link'] = '首页';
        $config['first_tag_open'] = '<span class="prev">';
        $config['first_tag_close'] = '</span>';
        //末页
        $config['last_link'] = '末页';
        $config['last_tag_open'] = '<span class="next">';
        $config['last_tag_close'] = '</span>';
        //下一页
        $config['next_link'] = '下一页&gt;';
        $config['next_tag_open'] = '<span class="next">';
        $config['next_tag_close'] = '</span>';
        //上一页
        $config['prev_link'] = '&lt;上一页';
        $config['prev_tag_open'] = '<span class="prev">';
        $config['prev_tag_close'] = '</span>';
        //当前页
        $config['cur_tag_open'] = '<span class="lin current">';
        $config['cur_tag_close'] = '</span>';
        //其他页
        $config['num_tag_open'] = '<span class="lin">';
        $config['num_tag_close'] = '</span>';
        $config['anchor_class'] = 'class="xx"';
        
        $config['base_url'] = $base_url;//
        $config['total_rows'] = $total;
        $config['per_page'] = $per_page;
        $config['uri_segment'] = $pageSegment;
        $config['num_links'] = 3;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'page';
        $this->pagination->initialize($config); 

        return $this->pagination->create_links();
    }
    
    private function checkAuth() {
        if($this->info['is_pay'] != payStatus){
            $this->jump('/', '您当前套餐没有此功能的权限，请联系客户经理开通！');
            exit;
        }
    }

}
