<?php

/**
 * 访客表模型
 * 
 * @author LJQ
 * 
 * @property CI_DB_active_record $FV
 */
class Analytics_visits_model extends CI_Model
{

    // 字段属性
    private $v_id = false;
    private $v_site_code = false;
    private $v_user_ip = false;
    private $v_first_page_id = false;
    private $v_page_author = false;
    private $v_leave_page_id = false;
    private $v_referer_url = false;
    private $v_order_num = false;
    private $v_order_type = false;
    private $v_datetime = false;
    // 
    private $limit = false;
    private $order_by = false;
    private $group_by = false;
    private $my_fields = false;

    function __construct()
    {
        parent::__construct();

        $this->FV = $this->load->database('mysql', TRUE);
        // $this->load->model('Analytics_pages_model');
        $this->load->model('Analytics_historys_model');
    }

    /**
     * 重置查询
     */
    private function reset()
    {
        $this->v_id = false;
        $this->v_site_code = false;
        $this->v_user_ip = false;
        $this->v_first_page_id = false;
        $this->v_page_author = false;
        $this->v_leave_page_id = false;
        $this->v_referer_url = false;
        $this->v_order_num = false;
        $this->v_order_type = false;
        $this->v_datetime = false;

        $this->my_fields = false;
        $this->order_by = false;
        $this->group_by = false;
        $this->limit = false;
    }

    /**
     * 获取指定访客的信息
     * @param type $id
     * @return boolean 
     */
    public function get_visit($v_id)
    {
        if (!empty($v_id) && is_numeric($v_id))
        {
            $this->reset();
            $this->v_id = ' AND v_id = ' . $this->FV->escape($v_id);
            $this->limit = 1;
            return $this->get_list();
        }
        return FALSE;
    }

    /**
     * 根据site_code和ip获取用户,返回当天最近的那位
     * @param type $site_code
     * @param type $ip 
     */
    public function get_order_visit($site_code, $ip)
    {
        if ($site_code && $ip)
        {
            $this->reset();
            $this->v_site_code = ' AND v_site_code = ' . $this->FV->escape($site_code);
            $this->v_user_ip = ' AND v_user_ip = ' . $this->FV->escape($ip);
            $this->limit = 1;
            return $this->get_list();
        }
        return FALSE;
    }

    /**
     * 绑定订单号
     * @param type $v_id
     * @param type $order_num 
     * @param type $order_type 
     */
    public function bing_order_num($id, $order_num, $order_type = 't')
    {
        if ($id && $order_num)
        {
            $sql = "UPDATE analytics_visits
                    SET    v_order_num = ?,
                           v_order_type = ?
                    WHERE  v_id = ?";
            return $this->FV->query($sql, array($order_num, $order_type, $id));
        }
        return FALSE;
    }

    /**
     * 添加
     * @param type $site_code
     * @param type $page_id
     * @param type $author
     * @param type $user_ip
     * @param type $page_referer
     * @return boolean
     */
    public function add($site_code, $page_id, $author = '', $user_ip = '', $page_referer = '')
    {
        if ($site_code && $page_id)
        {
            $v_order_num = 0;
            $v_datetime = time();
            $sql = "INSERT INTO analytics_visits
                              ( v_site_code,
                                v_user_ip,
                                v_first_page_id,
                                v_page_author,
                                v_referer_url,
                                v_order_num,
                                v_datetime)
                    VALUES    ( ?,?,?,?,?,?,? )";
            $this->FV->query($sql, array($site_code, $user_ip, $page_id, $author, $page_referer, $v_order_num, $v_datetime));
            return $this->FV->insert_id();
        }
        return FALSE;
    }

    /**
     * 获取最近的访客
     * @param type $page
     * @param type $site_code
     * @param type $start
     * @param type $end
     * @param type $order_status 订单状态
     * @param type $limit
     * @return type 
     */
    public function get_visits($page = 0, $site_code = '', $start = 0, $end = 0, $order_status = 0, $limit = 50)
    {
        // 太后面意义不大
        if ($page > 100000)
        {
            return FALSE;
        }

        $this->reset();

        $page = empty($page) ? 0 : $page;

        if (!empty($site_code))
        {
            $this->v_site_code = ' AND v_site_code = ' . $this->FV->escape($site_code);
        }
        if ($start && $end)
        {
            $this->v_datetime = " AND v_datetime >= '$start' AND v_datetime <= '$end'";
        }

        if (empty($order_status))
        {
            $order_status = 0;
        }
        $this->v_order_num = ' AND v_order_num = ' . $this->FV->escape($order_status);

        $rs = array();
        $this->my_fields = 'count(*) c';
        $this->limit = 1;
        $count = $this->get_list();
        if (!empty($count))
        {
            $count = $count->c;
            // 大于总数的话可能会引起效率问题
            if ($page > $count)
            {
                return FALSE;
            }
        } else
        {
            return FALSE;
        }

        $this->my_fields = false;
        $this->order_by = ' ORDER BY v_id DESC';
        $this->limit = $page . ',' . $limit;

        $rs['count'] = $count;
        $rs['list'] = $this->get_list();
        return $rs;
    }

    /**
     * 获取某个页面的所有订单
     * @param type $page_id
     * @return boolean 
     */
    public function get_page_orders($page_id)
    {
        if (!empty($page_id))
        {
            $this->reset();
            $this->v_first_page_id = ' AND v_first_page_id = ' . $this->FV->escape($page_id);
            return $this->get_list();
        }
    }

    /**
     * 获取指定订单的详细信息
     * @param type $order_num 
     */
    public function get_order_detail($order_num)
    {
        if (!empty($order_num))
        {
            $this->reset();
            $this->v_order_num = ' AND v_order_num = ' . $this->FV->escape($order_num);
            $this->limit = 1;
            return $this->get_list();
        }
    }

    /**
     * 获取用户统计
     * 列出今日、本月、本年订单、访问量统计
     * @param type $author_code 
     */
    public function get_auhor_analytics($author_code)
    {
        if (empty($author_code))
        {
            return FALSE;
        }

        $this->reset();

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

        // 查询条件
        $this->v_order_num = ' AND v_order_num != 0';
        $this->v_page_author = ' AND v_page_author = ' . $this->FV->escape($author_code);

        // 当天的
        $day_begin = mktime(0, 0, 0, $month, $day, $year); //当天开始时间戳
        $day_end = mktime(0, 0, 0, $month, $day + 1, $year); //当天结束时间戳
        // 今天订单数
        $result = $this->get_author_date_analytics($day_begin, $day_end);
        $rs['count_order_day'] = $result['count_order'];
        $rs['count_visit_day'] = $result['count_visit'];


        // 本月订单数
        $month_begin = mktime(0, 0, 0, $month, 1, $year);
        $month_end = mktime(0, 0, 0, $month + 1, 1, $year);
        $result = $this->get_author_date_analytics($month_begin, $month_end);
        $rs['count_order_month'] = $result['count_order'];
        $rs['count_visit_month'] = $result['count_visit'];

        $year_begin = mktime(0, 0, 0, 1, 1, $year - 1); //当年开始时间戳
        $year_end = mktime(0, 0, 0, 1, 1, $year + 1); //当年结束时间戳
        $result = $this->get_author_date_analytics($year_begin, $year_end);
        $rs['count_order_year'] = $result['count_order'];
        $rs['count_visit_year'] = $result['count_visit'];

        return $rs;
    }

    private function get_author_date_analytics($begin, $end)
    {
        $this->v_datetime = " AND v_datetime > $begin AND v_datetime < $end";
        $result = $this->get_list();
        $count = empty($result) ? 0 : count($result);
        $rs['count_order'] = $count;

        // 本年访问
        $rs['count_visit'] = 0;
        if (!empty($result))
        {
            foreach ($result as $value)
            {
                $lv_ids[] = $value->v_id;
            }
            $rs['count_visit'] = $this->Analytics_historys_model->get_visit_count($lv_ids);
        }
        return $rs;
    }

    /**
     * 获取离开页面最多前100个page_id
     */
    public function get_top_leave_pids()
    {
        $this->reset();
        $this->my_fields = 'v_leave_page_id, count(v_leave_page_id) count_on';
        $this->v_leave_page_id = ' AND v_leave_page_id != 0';
        $this->group_by = ' GROUP BY v_leave_page_id';
        $this->order_by = ' ORDER BY count_on DESC';
        $this->limit = 100;
        $result = $this->get_list();
        if (empty($result))
        {
            return FALSE;
        }
        foreach ($result as $value)
        {
            $page_ids[] = $value->v_leave_page_id;
        }
        return $page_ids;
    }

    /**
     * 获取订单最多的
     * @param type $num 
     * 
     */
    public function get_pids_order_top($page, $site_code = '', $author = '', $start_time = 0, $end_time = 0)
    {
        $this->reset();

        if (empty($page))
        {
            $page = 0;
        }
//        $this->v_order_num = ' AND v_order_num !=0';
        
        if (!empty($site_code))
        {
            $this->v_site_code = ' AND v_site_code =' . $this->FV->escape($site_code);
        }
        
        if (!empty($author))
        {
            $this->v_page_author = ' AND v_page_author =' . $this->FV->escape($author);
        }
        
        if ($start_time && $end_time)
        {
            $this->v_datetime = " AND v_datetime >= $start_time AND v_datetime <= $end_time";
        }

        // 获取列表
        // 注: mysql比较特殊的用法 SQL_CALC_FOUND_ROWS -- 在查询时就能获取总数, 不需要两次查询
        $this->my_fields = 'SQL_CALC_FOUND_ROWS v_first_page_id, ';
        // TODO 这里的子查询在大数量时可能出现效率问题, 最好是将订单总数放pages表..
        $this->my_fields .= '( SELECT count( * ) FROM analytics_visits av WHERE av.v_order_num !=0 AND av.v_id = analytics_visits.v_id ) count_on';
        $this->order_by = ' ORDER BY count_on DESC,v_id DESC';
        $this->group_by = ' GROUP BY v_first_page_id';
        $this->limit = $page . ',50';
        $result = $this->get_list();
        
        $rs = array();
        // 获取总数的方法
        $all_query = $this->FV->query('SELECT found_rows();');
        $all_rs = $all_query->row_array();
        $rs['count_all'] = $all_rs['found_rows()'];
        // 大于总数的话...
        if ($page > $rs['count_all'])
        {
            return FALSE;
        }

        $where_page_ids = array();
        $count_on = array();

        // 没有数据
        if (empty($result))
        {
            return FALSE;
        }

        foreach ($result as $value)
        {
            $page_id = $value->v_first_page_id;
            $where_page_ids[] = $page_id;
            $count_on[$page_id] = $value->count_on;
        }
        $rs['page_ids'] = $where_page_ids;
        $rs['count'] = $count_on;

        return (object) $rs;
    }

    /**
     * 更新离开页面ID
     * @param type $lv_visit_id
     * @param type $site_code
     * @param type $page_id 
     */
    public function update_leave_page($v_id, $site_code, $page_id)
    {
        if ($v_id && $site_code && $page_id)
        {
            $sql = "UPDATE analytics_visits
                    SET    v_site_code = ?,
                           v_leave_page_id = ?
                    WHERE  v_id = ?";
            return $this->FV->query($sql, array($site_code, $page_id, $v_id));
        }
        return FALSE;
    }

    /**
     * 获取数据集
     */
    private function get_list()
    {
        $sql = "SELECT ";
        if ($this->my_fields === false)
        {
            $sql .= "v_id,
                    v_site_code,
                    v_user_ip,
                    v_first_page_id,
                    v_page_author,
                    v_leave_page_id,
                    v_referer_url,
                    v_order_num,
                    v_order_type,
                    v_datetime ";
        } else
        {
            $sql .= $this->my_fields . ' ';
        }
        $sql .= "FROM analytics_visits ";
        $sql .= "WHERE 1=1 ";

        $this->v_id ? $sql .= $this->v_id : false;
        $this->v_site_code ? $sql .= $this->v_site_code : false;
        $this->v_user_ip ? $sql .= $this->v_user_ip : false;
        $this->v_first_page_id ? $sql .= $this->v_first_page_id : false;
        $this->v_page_author ? $sql .= $this->v_page_author : false;
        $this->v_leave_page_id ? $sql .= $this->v_leave_page_id : false;
        $this->v_referer_url ? $sql .= $this->v_referer_url : false;
        $this->v_order_num ? $sql .= $this->v_order_num : false;
        $this->v_order_type ? $sql .= $this->v_order_type : false;
        $this->v_datetime ? $sql .= $this->v_datetime : false;

        $this->group_by ? $sql.=$this->group_by : false;
        $this->order_by ? $sql.=$this->order_by : false;
        $this->limit ? $sql.= ' LIMIT ' . $this->limit : false;

//        var_dump($sql);
        $query = $this->FV->query($sql);
        if ($this->limit == 1)
        {
            if ($query->num_rows() > 0)
            {
                $row = $query->row();
                return $row;
            } else
            {
                return FALSE;
            }
        } else
        {
            return $query->result();
        }
    }

}