<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\Device;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class DeviceController extends Controller
{
    use ResponseJson;

    public function addDevice(Request $request){
        try {
            $data = $request->only(['device_data','name','type','sub_type','device_id']);
            $validated = Validator::make($data, [
                'device_id' => 'required'
            ], [
                'device_id.required' => '设备id不为空',
            ]);

            if ($validated->fails()) {
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                return $this->failure($error);
            }

            $user = auth()->user();
            $exists = Device::where('user_id',$user->id)->where('device_id',$data['device_id'])->exists();
            if($exists){
                return $this->failure('您已绑定设备,无需重复添加');
            }
            $data['user_id'] = $user->id;

            $data['device_data'] = json_encode($data['device_data']);
            Device::create($data);
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('addDevice file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("绑定失败");
        }
    }

    public function getDevice(Request $request){
        try {
            $type = $request->get('type',0);
            $user = auth()->user();
            $list = Device::where('user_id',$user->id)->where('type',$type)->orderByDesc('id')->get();
            foreach ($list as $item){
                $item->device_data = json_decode($item->device_data);
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('addDevice file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function updateDevice(Request $request,$id){
        try {
            $device = Device::find($id);
            if($request->has('name')){
                $device->name = $request->input('name');
            }
            $device->save();
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('addDevice file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }
}
