<?php
namespace catchAdmin\report\model;

use catcher\base\CatchModel;
use catcher\exceptions\FailedException;
use catcher\Utils;
use catchAdmin\permissions\model\DataRangScopeTrait;

use catchAdmin\device\model\Station as StationModel;
use catchAdmin\device\model\Device as DeviceModel;
use catchAdmin\school\model\KqBuilding as BuildingModel;
use catchAdmin\permissions\model\Users as UsersModel;
use catchAdmin\permissions\model\Department as DepartmentModel;
use catchAdmin\permissions\model\Roles;
use catchAdmin\system\model\SysDictData as SysDictDataModel;
use catchAdmin\system\model\SysDictType as SysDictTypeModel;
use catchAdmin\permissions\model\SysConfig;

class Report extends CatchModel
{
    //权限过滤
    use DataRangScopeTrait;

    protected $name = 'report';

    protected $field = [];

    /**
     * 获取所有基站类型
     */
    public function getStationType()
    {
        return (new SysDictDataModel())->getTypesByCode('StationType');
    }

    /**
     * 获取所有用户设备类型
     */
    public function getDeviceType()
    {
        return (new SysDictDataModel())->getTypesByCode('DeviceType');
    }

    /**
     * 基站数量数据
     */
    public function getStationCountData()
    {
        $station_type_arr = []; // 基站类型数组
        $total_count = 0; // 基站总数量
        $online_count = 0; // 基站总在线数量
        $yesterday_add_count = 0; // 基站昨日新增总数
        $today_add_count = 0; // 基站今日新增总数
        $station_type_data = [];
        $time = time();
        $today_time = strtotime(date('Y-m-d'));

        // 基站离线时间间隔
        $offline_interval = SysConfig::getConfigValueBy('station_offline_interval', 'station_config') ?? 86400;
        // 基站总数据
        $cursor = (new StationModel)->dataRange()->field('mac, online_time, created_at')->cursor();
        foreach ($cursor as $station) {
            $total_count++;
            
            // 昨日新增
            $create_time = $station->getData('created_at');
            if ($today_time - $create_time > 0 && $today_time - $create_time < 86400) {
                $yesterday_add_count++;
                
            } 
            // 今日新增
            if ($today_time - $create_time <= 0) {
                $today_add_count++;
               
            }
            // 在线数
            if ($time - intval(strtotime($station['online_time'])) > $offline_interval) { // 离线时间,秒
                $online_count++;
               
            }

        }


        return [
            'station_total_count' => $total_count,
            'station_online_count' => $online_count,
            'station_offline_count' => $total_count - $online_count,
            'station_yesterday_add_count' => $yesterday_add_count,
            'station_today_add_count' => $today_add_count,
        ];
    }
    
    /**
     * 基站设备增长趋势数据
     */
    public function getStationGrowthTrendData($start_time = '', $end_time = '')
    {
        // 默认最近1周
        if (!$start_time) {
            $start_time = date('Y-m-d', strtotime('-6 day'));
        }
        if (!$end_time) {
            $end_time = date('Y-m-d');
        }
        // 获取基站类型
        $station_types = $this->getStationType();

        $data = [];
        $station_model = new StationModel();
        while ($start_time <= $end_time) {

            foreach($station_types as $type) {
                if (!isset($data[$type['text']]['name'])) {
                    $data[$type['text']]['name'] = $type['text'];
                }
                
                $count = $station_model->dataRange()
                                    ->where('station_type', $type['value'])
                                    ->whereBetweenTime('created_at', 0, date('Y-m-d 23:59:59', strtotime($start_time)))
                                    ->count();
                // var_dump($station_model->getLastSql());
                $data[$type['text']]['data'][$start_time] = $count;
            }

            $start_time = date('Y-m-d', strtotime($start_time . ' +1 day'));
        }

        return array_values($data);
    }

    /**
     * 用户设备增长趋势数据
     */
    public function getDeviceGrowthTrendData($start_time = '', $end_time = '')
    {
        // 默认最近1周
        if (!$start_time) {
            $start_time = date('Y-m-d', strtotime('-6 day'));
        }
        if (!$end_time) {
            $end_time = date('Y-m-d');
        }
        // 获取设备类型
        $device_types = $this->getDeviceType();

        $data = [];
        $device_model = new DeviceModel();
        while ($start_time <= $end_time) {

            foreach($device_types as $type) {
                if (!isset($data[$type['text']]['name'])) {
                    $data[$type['text']]['name'] = $type['text'];
                }
                
                $count = $device_model->dataRange()
                                    ->where('device_type', $type['value'])
                                    ->whereBetweenTime('created_at', 0, date('Y-m-d 23:59:59', strtotime($start_time)))
                                    ->count();
                // var_dump($device_model->getLastSql());
                $data[$type['text']]['data'][$start_time] = $count;
            }

            $start_time = date('Y-m-d', strtotime($start_time . ' +1 day'));
        }

        return array_values($data);
    }

    /**
     * 部门数量数据:统计含本部门、及子部门数量
     */
    public function getDepartmentCountData()
    {
        $depart_ids = DepartmentModel::getChildrenDepartmentIds(request()->user()->department_id);
        // 去掉部门为0的
        $depart_ids = array_filter($depart_ids);
        return [
            'department_count' => count($depart_ids),
        ];
    }

    /**
     * 设备用户数量统计
     */
    public function getDeviceUserCountData()
    {
        // 当前时间
        $now_time = time();
        // 离线时间间隔
        $offline_interval = SysConfig::getConfigValueBy('card_offline_interval', 'basic_config') ?: 86400;
        $offline_time = date('Y-m-d H:i:s', $now_time - $offline_interval); // 离线时间
  

        $deviceModel = (new \catchAdmin\device\model\Device());
        $devices = $deviceModel->dataRange()
                    ->field('id,alarm_state,online_time,wifi_online_time')
                    ->append(['last_online_time'])
                    ->select();

        // 总设备数
        $totle = $devices->count();
        // 总在线设备数 
        $totle_online = $devices->where('last_online_time', '>', $offline_time)->count();



        return [
            'device_total_count' => $totle,
            'device_online_count' => $totle_online,
 
        ];
    }

}