<?php

namespace app\admin\controller\Flow;

use app\Request;
use app\common\model\Flow\Flow as ModelFlow;
use think\db\Where;
use think\facade\Validate;
use app\BaseController;
use app\exception\ErrorMsg;
use think\facade\Filesystem;

class Flow extends BaseController
{

    // (new ModelFlow)->track();

    /**
     * 查询流量访问记录
     * @throws \think\db\exception\DbException
     */
    public function getFlowRecord(Request $request): array
    {
        $query = ModelFlow::where([]);
        $select = self::pageWrapper($query)
            ->field([
                'flow_id',
                'flow_record_no',
                'flow_visitor_ip',
                'flow_location',
                'flow_create_time',
                'flow_source',
                'flow_target',
                'flow_os',
                'flow_browser'
            ])
            ->order('flow_id', 'desc')
            ->select();

        $count = $query->count();
        return [
            'msg' => '查询成功',
            'code' => 0,
            'data' => $select,
            'count' => $count
        ];
    }

    /**
     * 查询流量来源统计
     */
    public function getFlowSourceCount(): array
    {
        $query = ModelFlow::where([]);
        $count = $query->count();
        $select = $query->field([
            'flow_id',
            'flow_source',
        ])->select();
        $GDP = $query->field([

            'flow_source',
        ])->group('flow_source')->select();
        foreach ($GDP as $k => &$i) {
            $i['number'] = 0;
            $i['percentage'] = 0;
        }
        foreach ($select as $key => &$item) {
            foreach ($GDP as $k => &$i) {
                if ($item['flow_source'] === $i['flow_source']) {
                    $i['number'] += 1;
                }
            }
        }
        foreach ($GDP as $k => $i) {
            $i['percentage'] = round($i['number'] / $count  * 100);
        }
        return [
            'msg' => '查询完成',
            'code' => 0,
            'count' => $count,
            'data' => [
                'GDP' => $GDP,
                'select' => $select
            ]
        ];
    }

    /**
     * 查询流量浏览器统计
     */
    public function getFlowBrowserCount(): array
    {
        $query = ModelFlow::where([]);
        $count = $query->count();
        $select = $query->field([
            'flow_id',
            'flow_browser',
        ])->select();
        $GDP = $query->field([

            'flow_browser',
        ])->group('flow_browser')->select();
        foreach ($GDP as $k => &$i) {
            $i['number'] = 0;
            $i['percentage'] = 0;
        }
        foreach ($select as $key => &$item) {
            foreach ($GDP as $k => &$i) {
                if ($item['flow_browser'] === $i['flow_browser']) {
                    $i['number'] += 1;
                }
            }
        }
        foreach ($GDP as $k => $i) {
            $i['percentage'] =   round($i['number'] / $count  * 100);
        }
        return [
            'msg' => '查询完成',
            'code' => 0,
            'count' => $count,
            'data' => [
                'select' => $select,
                'GDP' => $GDP
            ]
        ];
    }

    /**
     * 查询流量月统计
     */
    public function getFlowMonthCount(Request $request): array
    {
        $current_year = input('post.current_year') ?? 0;
        $query = ModelFlow::where([]);
        $current_year = date('Y', strtotime("$current_year year"));
        $count = $query->whereYear('flow_create_time', $current_year)
            ->field([
                'flow_create_time',
            ])
            ->select()->count();
        $select = $query->whereYear('flow_create_time', $current_year)
            ->field([
                'flow_id',
                'flow_record_no',
                'flow_visitor_ip',
                'flow_location',
                'flow_create_time',
                'flow_source',
                'flow_target',
                'flow_os',
                'flow_browser'
            ])
            ->order('flow_id', 'desc')
            ->select()->toArray();
        $res_select  = [];
        for ($i = 1; $i <= 12; $i++) {
            array_push($res_select, [
                'flow_Date' => $current_year .
                    '-' .
                    date('m', strtotime($current_year . '-' . $i)),
                'number' => 0,
                'percentage' => 0
            ]);
        }
        foreach ($select as $key => &$item) {
            $date_format = explode('-', explode(' ', $item['flow_create_time'])[0]);

            $item['flow_Date'] = $date_format[0] . '-' . $date_format[1];
            foreach ($res_select as $k => &$it) {
                if ($item['flow_Date'] == $it['flow_Date']) {
                    $it['number'] += 1;
                }
            }
            foreach ($res_select as $k => &$it) {
                $it['percentage'] = round($it['number'] / $count * 100);
            }
        };
        foreach ($res_select as $k => &$it) {
            foreach ($select as $key => &$item) {
                if ($it['flow_Date'] === $item['flow_Date']) {
                    $it = array_merge($it, $item);
                }
            }
        }
        return [
            'code' => 0,
            'msg' => '查询成功',
            'count' => $count,
            'data' => [
                'current_date' => ['y' => $current_year],
                'select' => $res_select
            ]
        ];
    }

    /**
     * 查询流量日统计
     */
    public function getFlowDayCount(Request $request)
    {
        $current_month = input('post.current_month') ?? 0;
        //        return ['a'=>$current_month];
        $query = ModelFlow::where([]);
        $current_month_date = date('Y-m', strtotime(date('Y-m-01') . "$current_month month"));
        //        return ['a'=>$current_month_date];
        $count = $query->whereMonth('flow_create_time', $current_month_date)
            ->field([
                'flow_create_time',
            ])
            ->select()->count();
        // $select = $query->whereMonth('flow_create_time', $current_month_date)
        //     ->field([
        //         'flow_create_time',
        //     ])
        //     ->order('flow_id', 'desc')
        //     ->select()->toArray();
          $select = $query->whereMonth('flow_create_time', $current_month_date)
            ->field([
                'flow_create_time',
            ])
            ->buildSql();
            return $select;
        $GDP = [];
        $res_select  = [];
        for ($i = 1; $i <= date('t', strtotime(date('Y-m-01') . "$current_month month")); $i++) {

            array_push($res_select, [
                'week' => $this->getWeek(date('Y-m', strtotime(date('Y-m-01') . "$current_month month"))
                    . '-'
                    . date('d', strtotime(date('Y-m', strtotime(date('Y-m-01') . "$current_month month")) . "-$i"))),
                'flow_Date' => date('Y-m', strtotime(date('Y-m-01') . "$current_month month"))
                    . '-'
                    . date('d', strtotime(date('Y-m', strtotime(date('Y-m-01') . "$current_month month")) . "-$i")),
                'number' => 0, 'percentage' => 0
            ]);
        }
        foreach ($select as $key => &$item) {

            $item['flow_Date'] = explode(' ', $item['flow_create_time'])[0];
            foreach ($res_select as $k => &$it) {
                if ($item['flow_Date'] == $it['flow_Date']) {
                    $it['number'] += 1;
                }
            }
            foreach ($res_select as $k => &$it) {
                $it['percentage'] = round($it['number'] / $count * 100);
            }
        };
        foreach ($res_select as $k => &$it) {
            foreach ($select as $key => &$item) {
                if ($it['flow_Date'] === $item['flow_Date']) {
                    $it = array_merge($it, $item);
                }
            }
        }
        return [
            'code' => 0,
            'msg' => '查询成功',
            'count' => $count,
            'data' => [
                'current_date' => ['y' => date('Y', strtotime(date('Y-m-01') . "$current_month month")), 'm' => date('m', strtotime(date('Y-m-01') . "$current_month month"))],
                'select' => $res_select
            ]
        ];
    }

    /**
     * @param $date
     * @return string
     * @descript 获取指定日期星期
     */
    private function getWeek($date): string
    {
        //强制转换日期格式
        $date_str = date('Y-m-d', strtotime($date));

        //封装成数组
        $arr = explode("-", $date_str);

        //参数赋值
        //年
        $year = $arr[0];

        //月，输出2位整型，不够2位右对齐
        $month = sprintf('%02d', $arr[1]);

        //日，输出2位整型，不够2位右对齐
        $day = sprintf('%02d', $arr[2]);

        //时分秒默认赋值为0；
        $hour = $minute = $second = 0;

        //转换成时间戳
        $strap = mktime($hour, $minute, $second, $month, $day, $year);

        //获取数字型星期几
        $number_wk = date("w", $strap);

        //自定义星期数组
        $weekArr = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");

        //获取数字对应的星期
        return $weekArr[$number_wk];
    }
    
}
