<?php

namespace App\Laravue\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Auth;

class Device extends Authenticatable
{
    use Notifiable, HasRoles, HasApiTokens;
    protected $table = "device";
    public $timestamps = false;

    //用户添加设备
    public function adddevice($datadevice = [], $type): string
    {
        foreach ($datadevice as $k => $value) {
            if (is_null($k)) {
                return '用户提交表单参数错误';
            }
        }
        $datadevice['deviceaddtime'] = time();
        $datadevice['deviceuuid'] = $this->guid();
        $type == 1 ? '' : $datadevice['uid'] = Auth::id();
        $datadevice['ipaddr'] = $this->get_client_ip();
        return $this->insertGetId($datadevice);
    }

    //生成uid
    private function guid(): string
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000);
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
                . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12)
                . chr(125);// "}"
            return $uuid;
        }
    }

    private function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }
}
