<?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_block_expert_xue extends MY_Controller {

    const TYPE_BLOCK = 'block';
    const TYPE_HOTWORD = 'hotword';

    private $uid;
    private $info;
    private $house;
    private $broker;
    private $growthBrokerCredit;
    /**
     *
     * @var GrowthBrokerBidBlockExpert 
     */
    private $growthBrokerBidBlockExpert;
    private $perPage = 4;

    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->initGrowthBrokerBidBlockExpert();
        
        $this->load->helper('common_url');
    }

    public function index() {
		
        $tab = 'all';
        $check = $this->checkBidLevel();
		$broker_new_info =$this->broker_model->get_broker_info_by_uid($this->uid);//20160226 add
         if($check!==true || intval($broker_new_info[0]['starlevel'])<3) {//检查不通过跳转//20160226 add
           // $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $page_text = "您升级至&nbsp;<span style='color:green;'>3</span>&nbsp;星就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }

        $cBidPeriods = $this->getCBidPeriods();
        //有竞投期次 
        $myRecords = $this->getMyRecords($cBidPeriods);
        $blockName = $this->input->get('blockName');
        $data = $this->getViewData($cBidPeriods, $tab, $myRecords, $blockName, $this->perPage);
        $viewData = array();
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData = array_merge($viewData, $data);
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/小区专家/可参与的小区/');
        $this->view('market', 'market_bid_block_expert/index', $viewData);
    }

    public function on() {
        $tab = 'on';
        $check = $this->checkBidLevel();
        $broker_new_info =$this->broker_model->get_broker_info_by_uid($this->uid);//20160226 add
         if($check!==true || intval($broker_new_info[0]['starlevel'])<3) {//检查不通过跳转//20160226 add
           // $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $page_text = "您升级至&nbsp;<span style='color:green;'>3</span>&nbsp;星就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }



        $cBidPeriods = $this->getCBidPeriods();
        //有竞投期次 
        $myRecords = $this->getMyRecords($cBidPeriods);
        $blockName = $this->input->get('blockName');
        $data = $this->getViewData($cBidPeriods, $tab, $myRecords, $blockName, $this->perPage);
        $viewData = array();
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
        $viewData = array_merge($viewData, $data);
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/小区专家/本期参与小区/');
        $this->view('market', 'market_bid_block_expert/index', $viewData);
    }

    public function history() {
        $tab = 'history';
        $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;        
        $row_perpage = 8; //每页显示数量
        //我参与的竞投 的历史记录
        $page = $this->input->get('page');//intval($_GET['pg']);
        $page = $page ? $page : 1;
        $limit = $row_perpage * ($page - 1) . "," . $row_perpage;
        $blockName = $this->input->get('blockName');//$_GET['blockName'];
        $myrecords = $growthBrokerBidBlockExpert->findBidHistoryRecord(0, $blockName, "utime desc", $limit);
        $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');
        //print_r($myrecords);exit;
        //$blocks = $growthBrokerBidBlockExpert->get_valid_bid_block ($myrecords,$tab);
        //分页
        $rows_all = $growthBrokerBidBlockExpert->findBidHistoryRecordNumber('', $blockName);
        $total_page = ceil($rows_all / $row_perpage);

        if ($page > $total_page) {
            $page = $total_page;
        }
        //$myrecords = array_slice($myrecords,$row_perpage*($pg-1), $row_perpage);
        //print_r($blocks);exit;
        //当前竞投期次状态
        $viewData = array();
        $viewData['person'] = $this->widget('person');
        $viewData['tabs'] = $this->overViewTab($tab); //tab页

        $viewData['blockName'] = $blockName;
        $viewData['list'] = $growthBrokerBidBlockExpert->get_bid_block_expert_history_list($myrecords);
        $viewData['blockName'] = $blockName;
        $queryArray = array();
        if ($blockName) {
            $queryArray['blockName'] = $blockName;
        }
        $queryString = http_build_query($queryArray);
        $base_url = '/market_bid_block_expert/history/?' . $queryString;
        $viewData['page'] = $this->page($rows_all, $row_perpage, 1, $base_url);
        $viewData['js'] = load_js('common/js/jquery.jcountdown.js');
        $viewData['css'] = load_css('zsb/css/v1.0/style1.css');
		$viewData['google_analytics'] = get_ga_js_code('/营销中心/小区专家/竞投历史/');
        $this->view('market', 'market_bid_block_expert/history', $viewData);
        //exit;
    }

    public function ajax() {
        $action = $this->input->get('action'); //$_GET['action'];
        if ($action == 'attention') {//关注
            $res = $this->attention();
            return $this->ajaxResponse($res);
        }
        if ($action == 'bid') {//竞投
            $res = $this->bid();
            return $this->ajaxResponse($res);
        }
        if ($action == 'refresh') {//刷新整个列表
            $res = $this->refresh();
            return $this->ajaxResponse($res, 'gbk', 'text');
        }
        if ($action == 'refreshRank') {//刷新战况
            $res = $this->refreshRank();
            return $this->ajaxResponse($res, 'gbk', 'text');
        }
        if ($action == 'cancelAttention') {//取消关注
        }
        return;
    }

    /**
     * 关注
     * @return string|int
     */
    private function attention() {
        $bidId = $this->input->get('bidid'); //intval($_GET['bidid']);
        if ($bidId) {
            //检查是否可以关注
            $attentionNumber = GrowthBidAttentionHelper::totalNumber($this->broker);
            //echo $attentionNumber;exit;
            if ($attentionNumber >= GrowthBidAttentionHelper::ATTENTION_MAX_NUMBER) {
                $data['result'] = 0;
                $data['error'] = '-2';
                return $data;
            }
            $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
            $re = $growthBrokerBidBlockExpert->checkAttention($bidId);
            $data = array();
            if ($re) {
                //关注
                $cBidPeriods = $this->getCBidPeriods();
                $attentionId = $growthBrokerBidBlockExpert->attent($bidId, $cBidPeriods['id']);
                $data['result'] = 1;
                $data['attention_id'] = $attentionId;
            } else {
                $data['result'] = 0;
                $bidError = $growthBrokerBidBlockExpert->getBidError();
                $data['error'] = $bidError;
            }
        } else {
            $data['result'] = 0;
        }
        return $data;
    }

    private function bid() {
        $bidId = $this->input->get('bid_id'); //intval($_GET['bid_id']);
        $score = $this->input->get('score'); //intval($_GET['score']);
        $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
        $growthBrokerBidBlockExpert->bid($bidId, $score);
        $error = $growthBrokerBidBlockExpert->getBidError();
        //print_r($error);
        if ($error) {
            $result = array('result' => 0, 'error' => $error);
        } else {
            $result = array('result' => 1,);
        }
        return $result;
    }

    private function refresh() {
        //我参与的竞投
        //我的竞投记录
        $cBidPeriods = $this->getCBidPeriods();
        if (!$cBidPeriods) {
            return '';
        }
        $tab = $this->input->get('tab');
        $tab = in_array($tab, array('on', 'all')) ? $tab : 'all';

        $blockName = $this->input->get('blockName');
        if ($blockName) {
            $blockName = iconv('UTF-8', 'GBK', $blockName);
        }
        $myRecords = $this->getMyRecords($cBidPeriods);
        $viewData = $this->getViewData($cBidPeriods, $tab, $myRecords, $blockName, $this->perPage);
        
        $data = $this->load->view('market_bid_block_expert/center', $viewData, true);
         
     
		
        return $data;
    }

    /**
     * 
     * @param type $cBidPeriods
     * @param type $tab
     * @param type $myRecords
     * @param type $blockName
     * @param type $row_perpage
     * @return type
     */
    private function getViewData($cBidPeriods, $tab, $myRecords, $blockName, $row_perpage) {
        $bidPeriodsStatus = $cBidPeriods['status'];
        $blocks = $this->getValidBidBlock($cBidPeriods, $tab, $myRecords, $blockName);
		
        $rows_all = count($blocks);
        $viewData = array();
        $viewData['bidPeriodsStatus'] = $bidPeriodsStatus;
        $viewData['list'] = $this->getList($cBidPeriods, $blocks, $myRecords, $row_perpage);
        $viewData['growthBrokerBidBlockExpert'] = $this->growthBrokerBidBlockExpert;

        $viewData['person'] = $this->widget('person');
        $viewData['tab'] = $tab; //tab页
        $viewData['tabs'] = $this->overViewTab($tab); //tab页
        $page = $this->input->get('page'); //intval($_GET['page']);
        $viewData['cpage'] = $page ? $page : 1;
        $viewData['blockName'] = $blockName;
        $queryArray = array();
        if ($blockName) {
            $queryArray['blockName'] = $blockName;
        }
        $queryString = http_build_query($queryArray);
        if($tab=='on'){
            $base_url = '/market_bid_block_expert/'.$tab.'/?' . $queryString;
        } else {
            $base_url = '/market_bid_block_expert/index/?' . $queryString;
        }
        $viewData['page'] = $this->page($rows_all, $row_perpage, 1, $base_url);
        return $viewData;
    }

    /**
     * 返回列表数据
     * @param type $tab 'on' or 'all'
     * @param type $cBidPeriods 竞投期次
     * @param type $myrecords Description
     * @param type $blockName 小区名称
     * @param type $row_perpage 数据条数
     * @return array
     */
    private function getList($cBidPeriods, $blocks, $myrecords, $row_perpage = 4) {
        //分页
		
        $rows_all = count($blocks);
        $total_page = ceil($rows_all / $row_perpage);
        $page = $this->input->get('page'); //intval($_GET['page']);
        $page = $page ? $page : 1;
        if ($page > $total_page) {
            $page = $total_page;
        }
        $blocks = array_slice($blocks, $row_perpage * ($page - 1), $row_perpage);
        //当前竞投期次状态
        $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
        $list = $growthBrokerBidBlockExpert->get_bid_block_expert_list($blocks, $cBidPeriods, $myrecords);
		

        return $list;
    }

    /**
     * 返回所有可用小区
     * @param type $cBidPeriods 竞投期次
     * @param type $tab 'on' or 'all'
     * @param type $myrecords
     * @param type $blockName 小区名称
     * @return type
     */
    private function getValidBidBlock($cBidPeriods, $tab, $myrecords, $blockName) {
        $cBidPeriodsId = $cBidPeriods['id'];
        $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
        $blocks = $growthBrokerBidBlockExpert->get_valid_bid_block($cBidPeriodsId, $myrecords, $tab, $blockName);
		//print_r($blocks);die;
        return $blocks;
    }

    /**
     * 
     * @param type $cBidPeriods
     * @return type
     */
    private function getMyRecords($cBidPeriods) {
        $cBidPeriodsId = $cBidPeriods['id'];
        $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
        $myrecords = $growthBrokerBidBlockExpert->findBidRecord($cBidPeriodsId);
        $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');
        return $myrecords;
    }

    private function refreshRank() {
        $rdata = array();
        $bidId = $this->input->get('bid_id'); //intval($_GET['bid_id']);
        $growthBid = new GrowthBidBlockExpert();
        $bid = $growthBid->findById($bidId);
        if ($bid) {
            $cBidPeriods = $this->getCBidPeriods();
            $cBidPeriodsId = $cBidPeriods['id'];
            $bidPeriodsStatus = $cBidPeriods['status'];
            $growthBrokerBidBlockExpert = $this->growthBrokerBidBlockExpert;
            if ($growthBrokerBidBlockExpert->checkViewAuth($cBidPeriodsId, $bid)) {
                $number = "<input type='hidden' class='bid_number' value='" . $bid['number'] . "' />";
                //我的竞投记录
                $myrecords = $growthBrokerBidBlockExpert->findBidRecord($cBidPeriodsId);
                $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');
                $myrecord = $myrecords[$bidId];
                $records = $growthBrokerBidBlockExpert->findTempWinnerRecord($bidId);
                $list = $growthBrokerBidBlockExpert->rankList($records, $bidPeriodsStatus, null, $myrecord);
                $rdata['result'] = $number . $list;
            } else {
                $rdata['result'] = '-2';
            }
        } else {
            $rdata['result'] = '-1';
        }
        return $rdata['result'];
    }

    private function cancelAttention() {
        $attentionId = intval($_GET['attention_id']);
        $re = $growthBrokerBidBlockExpert->cancelAttent($attentionId);
        //$re = 1;
        if ($re == 1) {
            $data['result'] = 1;
        } else {
            $data['result'] = 0;
        }
        echo json_encode($data);
    }

    /**
     * 初始化经纪人信息
     */
    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();
        $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;
    }

    /**
     * 初始化成长体系-经纪人小区专家竞投类
     */
    private function initGrowthBrokerBidBlockExpert() {
        $growthConfig = $this->config->item('growth');
        $mode = $growthConfig['mode'];
        $this->growthBrokerBidBlockExpert = new GrowthBrokerBidBlockExpert($this->broker, $this->growthBrokerCredit, $mode);
        //$this->growthBrokerBidHouse->setCheckStar(true);
        $additionalScore = $growthConfig['additionalScore']['block'];
        $this->growthBrokerBidBlockExpert->setAdditionalScore($additionalScore);
    }

    /**
     * 
     * @return boolean 成功时返回true，失败时返回等级
     */
    private function checkBidLevel() {
        //判断有无权访问
        $level = $this->broker['level'];
        $brokerLevelNum = intval(substr($level, 2));
        //经纪人操作等级最低权限
        $growthBidLowLevel = new GrowthBidLowLevel();
        $lowLevel = $growthBidLowLevel->findLevelByType(1);
        $lowLevelId = intval(substr($lowLevel, 2));
        if ($brokerLevelNum < $lowLevelId || $brokerLevelNum == '') {
            return $lowLevel;
        } else {
            return true;
        }
    }

    private function getBrokerLevel() {
        //经纪人成长值等级数据  
        $growthExp = new GrowthExp();
        $brokerExp = $growthExp->findOneByBrokerId($this->uid);
        $brokerExp['exp'] = $brokerExp['exp'] == '' ? 0 : $brokerExp['exp'];
        $growthLevel = new GrowthLevel();
        $brokerLevel = $growthLevel->findOneByExp($brokerExp['exp']);
        $this->brokerLevel = $brokerLevel;
        return $brokerLevel;
    }

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

    /**
     * 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;
    }

    /**
     * 页面小工具，以后可以重构
     * @param type $name
     * @param type $data
     * @return type
     */
    private function widget($name, $data = null) {
        switch ($name) {

            case 'person':
				// 2016-1-14 添加星级数据 -----------start -------->
				$info = $this->broker_model->get_user_session();
				
				
				//echo $uid;die;
				$broker_new_info =$this->broker_model->get_broker_info_by_uid($info['uid']);
				// 2016-1-14 添加星级数据 -----------end -------->
                $data = array('info' => $this->info, 'introUrl' => 'http://zsb.house365.com/help/nj/?p=876','broker_new_info' => $broker_new_info);
                $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;
        }
    }

    /**
     * 使用概况标签页
     * @param type $curPage
     * @return type
     */
    private function overViewTab($curPage) {
        $tabData = array();
        //$allTab = array('all' => '全部房源', 'on' => '本期我参与的房源', 'history' => '竞投历史');
        $tabData['all'] = array('url' => '/market_bid_block_expert/index/', 'name' => '我可以参与的小区');
        $tabData['on'] = array('url' => '/market_bid_block_expert/on/', 'name' => '本期我参与的小区');
        $tabData['history'] = array('url' => '/market_bid_block_expert/history/', 'name' => '竞投历史');
        $rightBtns = array();
        $rightBtns[] = array('url' => 'http://zsb.house365.com/help/nj/?p=555', 'name' => '小区专家竞投说明');
        return $this->tabpage->generate($tabData, $curPage, $rightBtns);
    }

    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']){
            $this->jump('/', '您当前套餐没有此功能的权限，请联系客户经理开通！');
            exit;
        }
    }



}
