<?php
namespace app\model;


class Onlines extends base{
    
    //在线时长
    public function online($admin = '', $times = []) {
        if(!empty($times) && is_array($times) && count($times) >= 2) {
            $start = strtotime($times[0]);
            $end = strtotime($times[1]);
        }else{
            $start = strtotime(date('Y-m-01'));
            $end = strtotime(date('Y-m-d 23:59:59'));
        }

        if($admin) {
            $admins = Admins::where('username', $admin)->select();
        }else{
            $admins = Admins::where('status', 1)->select();
        }
        $_list = [];
        foreach($admins as $_admin) {
            $list = self::whereBetween('start',[$start, $end])->where('admin_id', $_admin->id)->order('start', 'asc')->select();
            $_list[$_admin->id]['name'] = $_admin->getData('name');
            $_list[$_admin->id]['avatar'] = $_admin->avatar;
            $_list[$_admin->id]['nickname'] = $_admin->nickname;
            $_list[$_admin->id]['days'] = [];
            for($i = 0; $i <= date('d', $end) - date('d', $start); $i++) {
                
                $day = date('m-d', $start + $i*24*3600);
                $_list[$_admin->id]['days'][$day] = 0;

                foreach($list as $l) {
                    if(date('m-d', $l->start) == $day) {
                        $_list[$_admin->id]['days'][$day] += $l->end > 0 ? $l->end - $l->start: 0;
                    }
                }
                
            }

        }
        return array_values($_list);
    }

    public function admins()
    {
        return $this->hasOne(Admins::class,'id','admin_id');
    }
}