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

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

    private $uid;
    private $info;
    private $house;
    private $broker;
    private $growthBrokerCredit;
    /**
     *
     * @var GrowthBrokerBidSchoolExpert 
     */
    private $growthBrokerBidSchoolExpert;
    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->initGrowthBrokerBidSchoolExpert();
       
        $this->load->helper('common_url');
    }

    public function index() {
        
      
        $tab = 'all';
        $check = $this->checkBidLevel();
        if ($check!==true) {
            $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }

        $cBidPeriods = $this->getCBidPeriods();
       
        //有竞投期次 
        $myRecords = $this->getMyRecords($cBidPeriods);
        
       
        $schoolName = $this->input->get('schoolName');
		
        
        $data = $this->getViewData($cBidPeriods, $tab, $myRecords, $schoolName, $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_school_expert/index', $viewData);
    }

    public function on() {
        $tab = 'on';
        $check = $this->checkBidLevel();
        if ($check!==true) {
            $page_text = "您升级至&nbsp;<span style='color:green;'>{$check}</span>&nbsp;级就可以使用此功能哦 ！<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先去升级吧，加油！";
            $this->jump('/', $page_text, 4000);
            return;
        }


        $cBidPeriods = $this->getCBidPeriods();
        //有竞投期次 
        $myRecords = $this->getMyRecords($cBidPeriods);
        $schoolName = $this->input->get('schoolName');
        $data = $this->getViewData($cBidPeriods, $tab, $myRecords, $schoolName, $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_school_expert/index', $viewData);
    }

    public function history() {
        $tab = 'history';
        $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;        
        $row_perpage = 8; //每页显示数量
        //我参与的竞投 的历史记录
        $page = $this->input->get('page');//intval($_GET['pg']);
        $page = $page ? $page : 1;
        $limit = $row_perpage * ($page - 1) . "," . $row_perpage;
        $schoolName = $this->input->get('schoolName');//$_GET['blockName'];
        $myrecords = $growthBrokerBidSchoolExpert->findBidHistoryRecord(0, $schoolName, "utime desc", $limit);
        $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');
        //print_r($myrecords);exit;
        //$blocks = $growthBrokerBidSchoolExpert->get_valid_bid_block ($myrecords,$tab);
        //分页
        $rows_all = $growthBrokerBidSchoolExpert->findBidHistoryRecordNumber('', $schoolName);
        $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['schoolName'] = $schoolName;
        $viewData['list'] = $growthBrokerBidSchoolExpert->get_bid_school_expert_history_list($myrecords);
        $viewData['schoolName'] = $schoolName;
        $queryArray = array();
        if ($schoolName) {
            $queryArray['schoolName'] = $schoolName;
        }
        $queryString = http_build_query($queryArray);
        $base_url = '/market_bid_school_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_school_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;
            }
            $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
            $re = $growthBrokerBidSchoolExpert->checkAttention($bidId);
            $data = array();
            if ($re) {
                //关注
                $cBidPeriods = $this->getCBidPeriods();
                $attentionId = $growthBrokerBidSchoolExpert->attent($bidId, $cBidPeriods['id']);
                $data['result'] = 1;
                $data['attention_id'] = $attentionId;
            } else {
                $data['result'] = 0;
                $bidError = $growthBrokerBidSchoolExpert->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']);
        $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
        $growthBrokerBidSchoolExpert->bid($bidId, $score);
        $error = $growthBrokerBidSchoolExpert->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';

        $schoolName = $this->input->get('schoolName');
        if ($schoolName) {
            $schoolName = iconv('UTF-8', 'GBK', $schoolName);
        }
        $myRecords = $this->getMyRecords($cBidPeriods);
        $viewData = $this->getViewData($cBidPeriods, $tab, $myRecords, $schoolName, $this->perPage);
        
        $data = $this->load->view('market_bid_school_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, $schoolName, $row_perpage) {
        $bidPeriodsStatus = $cBidPeriods['status'];
        $schools = $this->getValidBidSchool($cBidPeriods, $tab, $myRecords, $schoolName);
       
        $rows_all = count($schools);
        $viewData = array();
        $viewData['bidPeriodsStatus'] = $bidPeriodsStatus;
        $viewData['list'] = $this->getList($cBidPeriods, $schools, $myRecords, $row_perpage);
        $viewData['growthBrokerBidSchoolExpert'] = $this->growthBrokerBidSchoolExpert;

        $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['schoolName'] = $schoolName;
        $queryArray = array();
        if ($schoolName) {
            $queryArray['schoolName'] = $schoolName;
        }
        $queryString = http_build_query($queryArray);
        if($tab=='on'){
            $base_url = '/market_bid_school_expert/'.$tab.'/?' . $queryString;
        } else {
            $base_url = '/market_bid_school_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 $schoolName  学校名字
     * @param type $row_perpage 数据条数
     * @return array
     */
    private function getList($cBidPeriods, $schools, $myrecords, $row_perpage = 4) {
        //分页
        $rows_all = count($schools);
        $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;
        }
        $schools = array_slice($schools, $row_perpage * ($page - 1), $row_perpage);
        //当前竞投期次状态
        $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
        $list = $growthBrokerBidSchoolExpert->get_bid_school_expert_list($schools, $cBidPeriods, $myrecords);
        return $list;
    }

    /**
     * 返回所有可用小区
     * @param type $cBidPeriods 竞投期次
     * @param type $tab 'on' or 'all'
     * @param type $myrecords
     * @param type $schoolName 学区名称
     * @return type
     */
    private function getValidBidSchool($cBidPeriods, $tab, $myrecords, $schoolName) {
        $cBidPeriodsId = $cBidPeriods['id'];
        $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
		
        $schools = $growthBrokerBidSchoolExpert->get_valid_bid_school($cBidPeriodsId, $myrecords, $tab, $schoolName);
		
        return $schools;
    }

    /**
     * 
     * @param type $cBidPeriods
     * @return type
     */
    private function getMyRecords($cBidPeriods) {
        $cBidPeriodsId = $cBidPeriods['id'];
        $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
        $myrecords = $growthBrokerBidSchoolExpert->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 GrowthBidSchoolExpert();
        $bid = $growthBid->findById($bidId);
        if ($bid) {
            $cBidPeriods = $this->getCBidPeriods();
            $cBidPeriodsId = $cBidPeriods['id'];
            $bidPeriodsStatus = $cBidPeriods['status'];
            $growthBrokerBidSchoolExpert = $this->growthBrokerBidSchoolExpert;
            if ($growthBrokerBidSchoolExpert->checkViewAuth($cBidPeriodsId, $bid)) {
                $number = "<input type='hidden' class='bid_number' value='" . $bid['number'] . "' />";
                //我的竞投记录
                $myrecords = $growthBrokerBidSchoolExpert->findBidRecord($cBidPeriodsId);
                $myrecords = SqlCombinHelper::changeToKeyArray($myrecords, 'bid_id');
                $myrecord = $myrecords[$bidId];
                $records = $growthBrokerBidSchoolExpert->findTempWinnerRecord($bidId);
                $list = $growthBrokerBidSchoolExpert->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 = $growthBrokerBidSchoolExpert->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 initGrowthBrokerBidSchoolExpert() {
        $growthConfig = $this->config->item('growth');
        $mode = $growthConfig['mode'];
        $this->growthBrokerBidSchoolExpert = new GrowthBrokerBidSchoolExpert($this->broker, $this->growthBrokerCredit, $mode);
        //$this->growthBrokerBidHouse->setCheckStar(true);
        $additionalScore = $growthConfig['additionalScore']['school'];//最低加分
        $this->growthBrokerBidSchoolExpert->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(4);
        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':
                $data = array('info' => $this->info, 'introUrl' => 'http://zsb.house365.com/help/nj/?p=876');
                $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_school_expert/index/', 'name' => '我可以参与的学区');
        $tabData['on'] = array('url' => '/market_bid_school_expert/on/', 'name' => '本期我参与的学区');
        $tabData['history'] = array('url' => '/market_bid_school_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;
        }
    }



}
