<?php
/**
 * Created by PhpStorm.
 * User: vanshao
 * Date: 2019-05-10
 * Time: 10:20
 */

namespace App\Http\Controllers\Admin\User;

use App\Http\Controllers\Controller;
use App\Http\Models\Site;
use App\Http\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    public function __construct()
    {
    }

    public function index(Request $request)
    {

        if ($siteId = $request->input('siteId')) {
            $site = Site::query()->where(['id' => $siteId])->first();
            $view = 'admin/user/user_for_site';
            $btn['closeBtn'] = 1;
//            dd($siteId,$site);
        } else {
            $user = auth()->user();
            $site = $user->sites->first();
            $view = 'admin/user/user';
            $btn['closeBtn'] = 0;
        }


        if (!$site) {
            if($siteId) {
                return view('admin/site/tips', [
                    'tips' => '站点信息不存在',
                    'siteId' => $siteId
                ]);
            }
           return view('admin/errors/tips', $btn);
        }

        //访问地区数据
        $area = 'SELECT country AS region, SUM(pv) AS pv,SUM(uv) AS uv,SUM(ip) AS ip,SUM(duration) AS duration,SUM(bounces) AS bounces FROM `scn_traffic_report_region` GROUP BY `country` ORDER BY `pv` DESC limit 10';
        ////访问量数据//流量趋势 行为趋势
        $access = sprintf('SELECT FROM_UNIXTIME(timestamp, "%%Y-%%m-%%d") AS lt,
				SUM(pv) AS pv,
				SUM(uv) AS uv,
				SUM(ip) AS ip,
				SUM(duration) AS duration,
				SUM(bounces) AS bounces FROM `scn_traffic_report_hourly` WHERE timestamp <= %s GROUP BY `lt` ORDER BY `lt` desc LIMIT 14 ', time());
        //总访问量
        $totalAccess = 'SELECT 
				SUM(pv) AS pv,
				SUM(uv) AS uv,
				SUM(duration) AS duration,
				SUM(bounces) AS bounces FROM `scn_traffic_report_hourly` limit 1';
        //top10url
//        $top10Url = sprintf('SELECT url, SUM(pv) AS pv FROM `scn_traffic_report_url` WHERE timestamp <= %s GROUP BY `url` ORDER BY `pv` DESC limit 100 ', strtotime('-30 days'));
        $top10Url = sprintf('SELECT url, SUM(pv) AS pv FROM `scn_traffic_report_url` WHERE timestamp >= %s GROUP BY `url` ORDER BY `pv` DESC limit 100 ', strtotime('-30 days'));

        ////top10入口
        $top10Entrance = sprintf('SELECT ref_host, SUM(pv) AS pv FROM `scn_traffic_report_referrer` WHERE timestamp >= %s GROUP BY `ref_host` ORDER BY `pv` DESC limit 100', strtotime('-30 days'));
        $content = 'select count(1) from scn_content';

        $http = new Client();

        try {
            $response = $http->post($site->api_url . 'api / getdata', [
                'form_params' => [
                    $area,
                    $access,
                    $totalAccess,
                    $top10Url,
                    $top10Entrance,
                    $content
                ]
            ]);
            $data = json_decode($response->getBody(), true);
            $country_data = array_reverse($data['0']);
//            $pv_data = array_reverse($data['1']);
            $pv_data = $data['1'];

            $total_pv_data = $data['2']['0'];
            $top_url = $data['3'];
            $top_host = $data['4'];
            $total_content = $data['5']['0']['count(1)'];
            //访问地区数据
            foreach ($country_data as $value) {
                $country_data['country'][] = $value['region'];
                $country_data['pv'][] = $value['pv'];
                $country_data['uv'][] = $value['uv'];
                $country_data['duration'][] = round($value['duration'] / $value['pv'] / 60) . '.' . ($value['duration'] / $value['pv']) % 60;
//                dd( $value['uv'] );
//                $country_data['bounces'][] = round($value['bounces'] / $value['uv'] * 100) > 100 ? 100 : round($value['bounces'] / $value['uv'] * 100);

                if (empty($value['uv'])) {
                    $country_data['bounces'][] =0;
                } else {
                    $country_data['bounces'][] = round($value['bounces'] / $value['uv'] * 100) > 100 ? 100 : round($value['bounces'] / $value['uv'] * 100);
                }

//                dd($country_data);
                $country_data['pie'][] = array(
                    'value' => $value['pv'],
                    'name' => $value['region']
                );

            }
            $country_data['pie_country'] = array_reverse($country_data['country']);//饼图国家倒叙

            //平均在线时长
            $total_pv_data['avg_duration'] = round($total_pv_data['duration'] / $total_pv_data['pv'] / 60) . ':' . ($total_pv_data['duration'] / $total_pv_data['pv']) % 60;


//            $pv_data['xAxis'] = $this->getDescDayTime(13);
            $pv_data_day = $this->getDescDayTime(13);

            foreach ($pv_data_day as $day_key=>$day_value){

                $is_in=0;

                foreach ($pv_data as $value){

                    if(substr($value['lt'],5)==$day_value){
                        $pv_data2['pv'][] = $value['pv'];
                        $pv_data2['uv'][] = $value['uv'];
                        $pv_data2['duration'][] = round($value['duration'] / $value['pv'] / 60) . '.' . ($value['duration'] / $value['pv']) % 60;
                        $pv_data2['bounces'][] = round($value['bounces'] / $value['uv'] * 100) > 100 ? 100 : round($value['bounces'] / $value['uv'] * 100);
                        $is_in=1;
                    }

                }
                if($is_in==0){
                    $pv_data2['pv'][] = '0';
                    $pv_data2['uv'][] = '0';
                    $pv_data2['duration'][] = '0';
                    $pv_data2['bounces'][] = '100';
                }

            }

            $pv_data=$pv_data2;
            $pv_data['xAxis']=$pv_data_day;

            //访问量数据
//            foreach ($pv_data as $value) {
//                $pv_data['pv'][] = $value['pv'];
//                $pv_data['uv'][] = $value['uv'];
//                $pv_data['duration'][] = round($value['duration'] / $value['pv'] / 60) . '.' . ($value['duration'] / $value['pv']) % 60;
//                $pv_data['bounces'][] = round($value['bounces'] / $value['uv'] * 100) > 100 ? 100 : round($value['bounces'] / $value['uv'] * 100);
//            }

            $addition = [
                'pv_data' => $pv_data,
                'country_data' => $country_data,
                'total_pv_data' => $total_pv_data,
                'top_url' => $top_url,
                'top_host' => $top_host,
                'total_content' => $total_content,
            ];
//
//
        } catch (\Throwable $throwable) {
            Log::info(var_export($throwable->getMessage(), 1));

            if($siteId) {
                return view('admin/site/tips', [
                    'tips' => '站点信息不存在',
                    'siteId' => $siteId
                ]);
            }

            return view('admin/errors/tips', [
                    'tips' => '请求错误'
                ] + $btn);
        }


        return view($view, ['site' => $site, 'siteId' => $site->id] + $addition);
    }

    //获取倒序日期时间
    public function getDescDayTime($days)
    {

        for ($i = $days; $i >= 0; $i--) {
            $return_data[] = date("m-d", strtotime("-$i day"));
        }

        return $return_data;
    }


}