<?php

namespace App\Http\Controllers;

use App\Http\Resources\PermissionResource;
use App\Http\Requests\UsersRequest;
use App\Http\Resources\UserResource;
use App\Laravue\JsonResponse;
use App\Laravue\Models\Device;
use App\Laravue\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use Validator;
class HomepageController extends Controller
{
    //返回用户数量 设备数量, 报警数量 ,
    public function homepagecount()
    {
        $usercount = Users::count();
        $devicecount = Device::count();
        $devicepolice = Device::where('devicepolice', '>', '1')->count();
        $t = time();//当前时间
        $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));//今天的开始
        $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));//今天的结束
        $timedevicepolice = DB::table('reportpolice')->where('status', '=', '1')->whereBetween('starttime',[$start,$end])->count();
        return $this->jsonSuccessData(['usercount' => $usercount, 'devicecount' => $devicecount, 'devicepolice' => $devicepolice,'timedevicepolice'=>$timedevicepolice]);
    }

    //返回一年当前月份
    public function devicemonthcount(){
        $year_start=strtotime(date("Y")."-01-01"); // 获取当前的1月份的时间戳
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y')); //获取当月的时间戳
        $devicedata = Device::whereBetween('deviceaddtime',[$year_start,$endThismonth])
            ->selectRaw('from_unixtime(deviceaddtime,"%Y-%m") as date,COUNT(id) as value')
            ->groupBy('date')
            ->get()
            ->toArray();
        $policedata = Users::whereBetween('add_time',[$year_start,$endThismonth])
            ->selectRaw('from_unixtime(add_time,"%Y-%m") as date,COUNT(id) as value')
            ->groupBy('date')
            ->get()
            ->toArray();

        $devicepolice = Device::whereBetween('deviceaddtime',[$year_start,$endThismonth])
            ->where('devicepolice','>',1)
            ->selectRaw('from_unixtime(deviceaddtime,"%Y-%m") as date,COUNT(id) as value')
            ->groupBy('date')
            ->get()
            ->toArray();
        return $this->jsonSuccessData(['devicedata'=>$this->datamonth($devicedata),'policedata'=>$this->datamonth($policedata),'devicepolice'=>$this->datamonth($devicepolice)]);
    }

    private function datamonth($monthdata = []) :array{
        $year = date('Y',time());
        $month = date('m',time());
        $data = [];
        foreach ($monthdata as $value) {
            $data[$value['date']] = $value['value'];
        }
        $out = [];
        for ($i = 1; $i <= $month; $i++) {
            $mont = $i < 10 ? "0{$i}" : $i;
            $val = isset($data["{$year}-{$mont}"]) ? $data["{$year}-{$mont}"] : 0;
            array_push($out, $val);
        }
        return $out;
    }
}