<?php

namespace Source\Lib;

use Dever;

class Core
{
    private $key = 'source';

    /**
     * 记录用户信息
     *
     * @return mixed
     */
    public function saveUser($vid, $uid, $source_id, $account_type, $account_id)
    {
    	$data['vid'] = $vid;
    	$data['uid'] = $uid;
    	$data['source_id'] = $source_id;
    	$data['account_type'] = $account_type;
    	$data['account_id'] = $account_id;

    	$info = Dever::db('source/user')->one($data);

    	if (!$info) {
    		Dever::db('source/user')->insert($data);
    	}

        return true;
    }

    /**
     * 日志记录
     *
     * @return mixed
     */
    public function save($uid, $type, $source_id, $log = array())
    {
        return;
    	$log += Dever::input();
        $url = Dever::url();

        $log['uid'] = $uid;
        $log['source_id'] = $source_id;
        $log['url'] = $url;
        $log['ip'] = Dever::ip();

        Dever::log($log, $this->key . '/' . $source_id . '/' . $type);

        return true;
    }

    public function get($day, $type, $source_id, $start = 0, $end = 0)
    {
        $log = Dever::getLog($day, $this->key . '/' . $source_id . '/' . $type);
        $source = array();
        $source['pv'] = 0;
    	$source['uv'] = 0;
    	$source['user_num'] = 0;
    	$source['user_yes_num'] = 0;
        if ($log) {
        	$result = array();
        	$pv = $uv = 0;
        	$user = array();
        	foreach ($log as $k => $v) {
        		if ($v) {
        			$temp = explode('dever&', $v);
        			$info = explode(' ', $temp[0]);
        			$result[$k]['time'] = $info[0];
        			$result[$k]['project'] = $info[1];
        			$result[$k]['app'] = $info[2];
        			parse_str($temp[1], $result[$k]['param']);
        			$pv++;
        			if (isset($result[$k]['param']['uid']) && $result[$k]['param']['uid'] > 0) {
        				$user[$result[$k]['param']['uid']] = 1;
        			} else {
        				$user[$result[$k]['param']['ip']] = 1;
        			}
        		}
        	}
        	$source['pv'] = $pv;
        	$source['uv'] = count($user);

        	if ($start && $end) {
        		$where['source_id'] = $source_id;
	        	$where['start'] = $start;
	        	$where['end'] = $end;
	        	$source['user_num'] = Dever::db('source/user')->getTotal($where);
	        	$source['user_yes_num'] = $source['user_num'];
        	}
        }
        return $source;
    }
}