<?php

class Analytics extends CI_Controller
{

    private $view_data = array();

    function __construct()
    {
        parent::__construct();
        $this->permission->is_admin();
//        $this->output->enable_profiler(TRUE);
        // 载入Model
        $this->load->model("Analytics_visits_model");
        $this->load->model("Analytics_pages_model");
        $this->load->model('Analytics_historys_model');
        
        $this->load->model('Orders_model');

        // 载入helper
        $this->load->helper('url');

        // 所有该类页面都使用了菜单栏
        $this->_menu();
    }

//    public function test(){
//        $this->load->model('Analytics_visits_model');
//        $this->load->model('Analytics_historys_model');
//        $this->load->model('Analytics_pages_model');
//        $this->Analytics_vists_model->test();
//        $this->Analytics_pages_model->test();
//        var_dump('OK');
//    }

    public function index()
    {
        $page = $this->input->get('per_page');
        $site_code = $this->input->get('site_code');
        $author = $this->input->get('author');
        $order = $this->input->get('order');
        $url = $this->input->get('url');
        // 时间段
        $start = $this->input->get('start');
        if (strpos($start, '-') > 0)
        {
            $start = strtotime($start);
        }
        $end = $this->input->get('end');
        if (strpos($end, '-') > 0)
        {
            $end = strtotime($end);
        }
        // 获取订单最多的页面ID数组
        $rs = $this->Analytics_visits_model->get_pids_order_top($page, $site_code, $author, $start, $end);

        if (!empty($rs))
        {
            // 数据存在的话继续查询
            // 输出数据
            $this->view_data['count'] = $rs->count;
            $this->view_data['count_all'] = $rs->count_all;
            // 获取页面列表
            $this->view_data['list'] = $this->Analytics_pages_model->get_by_ids($rs->page_ids, $site_code, $author, $order, $url);
//            var_dump($this->view_data['list'][0]);exit();

            $this->view_data['cur_page'] = $page;

            // 加载配置
            $sites_config = $this->config->item('site');
            $authors = array();
            foreach ($sites_config as $value)
            {
                $sites[] = $value['site_code'];
                $authors = array_merge($authors, $value['site_authors']);
            }
            $this->view_data['authors'] = $authors;
            $this->view_data['sites'] = $sites;

            // 分页
            $page_url = site_url('analytics/index') . "?site_code=$site_code&start=$start&end=$end&author=$author&order=$order&url=$url";
            $this->view_data['pages'] = $this->_page($page_url, $this->view_data['count_all']);
        }
//        var_dump($rs);exit;
        // 参数传递
        $this->load->view('header', array('meta_title' => '统计分析'));

        $this->load->view('analytics/index', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 订单列表 
     */
    public function order()
    {
        $url = $this->input->get('url');
        $page = $this->Analytics_pages_model->get_one_page($url);

        $this->view_data['page'] = $page;
        $this->view_data['list'] = '';
        if (!empty($page))
        {
            $this->view_data["list"] = $this->Analytics_visits_model->get_page_orders($page->p_id);
        }
        $this->load->view('header');
        $this->load->view('analytics/order', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 订单信息
     * @param type $order_num 
     */
    public function order_detail($order_num = '')
    {
        if (!$order_num)
        {
            show_404();
        }

        $detail = $this->Analytics_visits_model->get_order_detail($order_num);
        if ($detail === FALSE)
        {
            show_404();
        }

        // 更多的信息
//        $this->output->enable_profiler(TRUE);
        $confirm_info = $this->Orders_model->get_detail_confirm($order_num);
        $this->view_data['confirm_info'] = $confirm_info;

        $this->view_data['detail'] = $detail;

        // 页面信息
        $this->view_data['page'] = $this->Analytics_pages_model->get_one($detail->v_first_page_id);

        // 访问记录
        $this->view_data['history'] = $this->Analytics_historys_model->get_visit_history($detail->v_id);

        $this->load->view('header');
        $this->load->view('analytics/order_detail', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 生成统计代码 
     */
    public function code()
    {
        $sites_config = $this->config->item('site');
        foreach ($sites_config as $value)
        {
            $sites[] = $value['site_code'];
        }
        $this->view_data['sites'] = $sites;
        $this->view_data['cur_site'] = $this->input->get('site');

        if (in_array($this->view_data['cur_site'], $this->view_data['sites']))
        {
            // 生成代码
//            $url = site_url();
            $url = 'http://i.chtcdn.com/info.php';
            $this->view_data['code'] = <<<EOF
<script language="javascript">
    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = '{$url}/website_analytics?'+'site_code={$this->view_data['cur_site']}&page_title='+document.title+'&page_referer='+escape(document.referrer);
        var s = document.getElementsByTagName('script')[0]; 
        s.parentNode.insertBefore(ga, s);
    })();
</script>
EOF;
        }
        $this->load->view('header');
        $this->load->view('analytics/code', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 最近访客列表
     */
    public function visit()
    {
        $page = $this->input->get('per_page');
        $page = $page ? $page : 0;
        $site_code = $this->input->get('site_code');
        $order_status = $this->input->get('order_status');
        // 时间段
        $start = intval(strtotime($this->input->get('start')));
        $end = intval(strtotime($this->input->get('end')));

        // 获取访客列表
        $visits_list = $this->Analytics_visits_model->get_visits($page, $site_code, $start, $end, $order_status);
        if ($visits_list === FALSE || empty($visits_list))
        {
            // 居然乱码...
            header('content-type:text/html;charset=utf-8');
            show_error('数据不存在或查询数据过大(超过10W)');
        }

        $this->view_data['list'] = $visits_list['list'];
        $this->view_data['count'] = $visits_list['count'];

        $this->view_data['cur_site_code'] = $site_code;
        $this->view_data['cur_start'] = $start ? date('Y-m-d', $start) : '';
        $this->view_data['cur_end'] = $end ? date('Y-m-d', $end) : '';
        $this->view_data['cur_order_status'] = $order_status;
        $this->view_data['cur_page'] = $page;

        // 加载配置
        $sites_config = $this->config->item('site');
        $authors = array();
        foreach ($sites_config as $value)
        {
            $sites[] = $value['site_code'];
            $authors = array_merge($authors, $value['site_authors']);
        }
        $this->view_data['authors'] = $authors;
        $this->view_data['sites'] = $sites;

        // 分页
        $page_url = site_url('analytics/visit') . "?site_code=$site_code&start=$start&end=$end&order_status=$order_status";
        $this->view_data['pages'] = $this->_page($page_url, $visits_list['count']);

        $this->load->view('header');
        $this->load->view('analytics/visit', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 常见的退出界面 
     */
    public function leave()
    {
        $this->view_data['list'] = array();

        $page_ids = $this->Analytics_visits_model->get_top_leave_pids();
        if ($page_ids !== FALSE)
        {
            $this->view_data['list'] = $this->Analytics_pages_model->get_by_ids($page_ids);
        }
        $this->load->view('header');
        $this->load->view('analytics/leave', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 显示某个访客的访问历史
     * @param type $id 
     */
    public function history($id)
    {
        $id = intval($id);
        // 获取访客信息
        $visit = $this->Analytics_visits_model->get_visit($id);
        if ($visit == FALSE)
        {
            show_404();
        }

        // 访问记录
        $history = $this->Analytics_historys_model->get_visit_history($id);

        $this->view_data['visit'] = $visit;
        $this->view_data['history'] = $history;

        $this->load->view('header');
        $this->load->view('analytics/history', $this->view_data);
        $this->load->view('footer');
    }

    /**
     * 我的统计 
     */
    public function mine()
    {
        $admin_info = $this->session->userdata('session_admin');
        $my_code = $admin_info['OPI_Code'];

        $year = date("Y");
        $month = date("m");
        $day = date("d");

        $data = array(
            'author' => $my_code,
            'count_order_day' => 0,
            'count_order_month' => 0,
            'count_order_year' => 0,
            'day_begin' => mktime(0, 0, 0, $month, $day, $year),
            'day_end' => mktime(0, 0, 0, $month, $day + 1, $year),
            'month_begin' => mktime(0, 0, 0, $month, 1, $year),
            'month_end' => mktime(0, 0, 0, $month + 1, 1, $year),
            'year_begin' => mktime(0, 0, 0, 1, 1, $year),
            'year_end' => mktime(0, 0, 0, 1, 1, $year + 1),
        );

        $auhor_analytics = $this->Analytics_visits_model->get_auhor_analytics($my_code);

        $data = array_merge($data, $auhor_analytics);
        $this->view_data = array_merge($this->view_data, $data);

        $this->load->view('header');

        $this->load->view('analytics/mine', $this->view_data);
        $this->load->view('footer');
    }

    private function _menu()
    {
        $data['cur_site_code'] = $this->input->get('site_code');
        $data['cur_author'] = $this->input->get('author');
        $data['cur_order'] = $this->input->get('order');
        $data['cur_url'] = $this->input->get('url');
        $data['cur_start'] = $this->input->get('start');
        $data['cur_end'] = $this->input->get('end');

        // 加载配置
        $sites_config = $this->config->item('site');
        $sites = array();
        $authors = array();
        if (!empty($sites_config))
        {
            foreach ($sites_config as $value)
            {
                $sites[] = $value['site_code'];
                $authors = array_merge($authors, $value['site_authors']);
            }
        }

        $data['authors'] = $authors;
        $data['sites'] = $sites;

        $this->view_data['menu'] = $this->load->view('analytics/menu', $data, TRUE);

        return $data;
    }

    /**
     * 分页
     * @param type $page_url
     * @param type $total_rows
     * @param type $per_page
     * @return type 
     */
    private function _page($page_url, $total_rows, $per_page = 50)
    {
        // 分页
        $this->load->library('pagination');             #加载分页的对象

        $config['base_url'] = $page_url;  #前后页链接
        $config['total_rows'] = $total_rows;  #辅助函数的一个方法
        $config['per_page'] = $per_page;
        $config['page_query_string'] = TRUE;
        $config['anchor_class'] = "class='btn' ";
        $config['first_link'] = '第一页';
        $config['last_link'] = FALSE;       // 由于最后的分页查询可能达到7-9s, 且查询意义不大, 隐藏分页last链接

        $this->pagination->initialize($config);

        return $this->pagination->create_links();   #丢到数组里面呆会渲染用
    }

}