<?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 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 DevicesController extends Controller
{
    //设备列表
    /*
     * 设备类型
     * type 不传默认是第一个
     * @type 设备类型id
     * */
    public function devicelist(Request $request){
        $type = $request->input('type');//设备类型id
        $pagenNum=$request->input('page')-1;//页数
        $limit = $request->input('limit');
        if($pagenNum === '' || $limit == ''){
            return $this->jsonErrorData(105,'页数或limit不能为空');
        }
        return $this->jsonSuccessData($this->whertype($type==''? '1':$type,$pagenNum,$limit));
    }

    //用户设备列表
    /*
     * 设备类型
     * type 不传默认是第一个
     * @type 设备类型id
     * */
    public function userdevicelist(Request $request){
        $type = $request->input('type');//设备类型id
        $pagenNum=$request->input('page')-1;//页数
        $limit = $request->input('limit');
        if($pagenNum === '' || $limit == ''){
            return $this->jsonErrorData(105,'页数或limit不能为空');
        }
        return $this->jsonSuccessData($this->userdevice($type==''? '1':$type,$pagenNum,$limit));
    }
    /*
     * 删除设备
     * type 1==逻辑删除
     * type 2== 物理删除
     * */
    public function deletedecice(Request $request){
        $type =  (int)$request->input('type');
        $deviceid = (int)$request->input('deviceid');//设备id
        if ($type == '' || $deviceid == ''){
            return $this->jsonErrorData(105,'参数不能为空');
        }
        if ($type == 1){//逻辑删除
            $dete  = Device::where('id','=',$deviceid)
                ->value('delete');
            if ($dete != 1){
                $update = Device::where('id','=',$deviceid)
                    ->update(['delete'=>1]);
                return $this->jsonSuccessData($update);
            }else{
                return $this->jsonErrorData(105,'数据异常');
            }

        }else if ($type == 2){//物理删除
            $dete  = Device::where('id','=',$deviceid)
                ->value('delete');
            if ($dete != 2){
                $delete = Device::where('id','=',$deviceid)
                    ->delete();
                return $this->jsonSuccessData($delete);
            }else{
                return $this->jsonErrorData(105,'数据异常');
            }
        }
    }

    //返回逻辑删除的设备和修复设备
    public function physicsdelete(Request $request){
        $deviceid = $request->input('deviceid');
        $databadevice = DB::table('device');
        if($_POST){
            $up = $databadevice
                ->where('id','=',$deviceid)
                ->update(['delete'=>2]);
            return $this->jsonSuccessData($up);
        }else{
            //返回物理删除设备列表
            $type =  (int)$request->input('type');//设备类型
            $pagenNum=$request->input('page')-1;//页数
            $limit = $request->input('limit');//条数
            if($pagenNum === '' || $limit == ''){
                return $this->jsonErrorData(105,'页数或limit不能为空');
            }
            $devicelist = $databadevice
                ->where('dtype','=',$type == '' ? '1':$type)
                ->where('delete','=','1')//设备逻辑删除状态
                ->join('device_type as dy',"device.dtype",'=','dy.tid')
                ->join('gas as g',"device.status",'=','g.id')
                ->select('dy.tname','g.gas','device.*')
                ->orderBy('device.id', 'desc')
                ->offset($pagenNum)
                ->limit($limit)
                ->get()->toArray();
            return $this->jsonSuccessData($devicelist);
        }

    }

    //添加设备
    public  function  adddevice(Request $request){
        //验证用户提交表单
        $validator = Validator::make($request->all(), $this->getValidationRulesdevice(false));
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 403);
        }
        $type = new Device();
        return $this->jsonSuccessData($type->adddevice($request->all()));
    }


 //编辑设备
    public function updatedevice(Request $request){
        $deid = $request->input('deid');
        $data = $request->all();
        if(is_null($deid)){
           return $this->jsonErrorData(105,'设备ID不能为空');
        }
        if ($_POST){
            $validator = Validator::make($request->all(), $this->getValidationRulesupdevice(false));
            if ($validator->fails()) {
                return response()->json(['errors' => $validator->errors()], 403);
            }
            foreach ($data as $k=>$v){
                if ($k == 'deid') {
                    unset($data[$k]);
                }
            }
            return $this->jsonSuccessData(Device::where('id','=',$deid)->update($data));
        }else{
            $devi = DB::table('device as de')
                ->where('de.id','=',$deid)
                ->leftjoin('device_type as dt','de.dtype','=','dt.tid')
                ->leftjoin('gas','de.status','=','gas.id')
                ->leftjoin('danwei as da','de.devicemonad','=','da.id')
                ->select('dt.*','gas.*','da.*','de.*')
                ->first();
            return $this->jsonSuccessData($devi);
        }
    }
    //返回设备类型和单位和介质
    public function devicetype(){
        $databadevice = DB::table('device_type')->get();
        $gas = DB::table('gas')->get();
        $danwei = DB::table('danwei')->get();
            return $this->jsonSuccessData(['devicetype'=>$databadevice,'gas'=>$gas,'danwei'=>$danwei]);
    }
    //返回设备列表
    private function whertype($type,$pagenNum,$limit) : array {
        $databadevice = DB::table('device');
        $devicelist = $databadevice
            ->where('dtype','=',$type)
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->leftjoin('device_type as dy',"device.dtype",'=','dy.tid')
            ->leftjoin('gas as g',"device.status",'=','g.id')
            ->leftjoin('status as p',"device.devicepolice",'=','p.id')
            ->select('dy.tname','g.gas','device.*','p.status_name')
            ->orderBy('device.id', 'desc')
            ->offset($pagenNum)
            ->limit($limit)
            ->get()->toArray();
        $count = $databadevice
            ->where('dtype','=',$type)
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->count();
        return ['devicelist'=>$devicelist,'count'=>$count];
    }

    //返回用户设备列表
    private function userdevice($type,$pagenNum,$limit) : array {
        $databadevice = DB::table('device');
        $devicelist = $databadevice
            ->where('dtype','=',$type)
            ->where('uid','=',Auth::id())
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->leftjoin('device_type as dy',"device.dtype",'=','dy.tid')
            ->leftjoin('gas as g',"device.status",'=','g.id')
            ->leftjoin('status as p',"device.devicepolice",'=','p.id')
            ->select('dy.tname','g.gas','device.*','p.status_name')
            ->orderBy('device.id', 'desc')
            ->offset($pagenNum)
            ->limit($limit)
            ->get()->toArray();
        $count = $databadevice
            ->where('dtype','=',$type)
            ->where('uid','=',Auth::id())
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->count();
        return ['devicelist'=>$devicelist,'count'=>$count];
    }
    private function deviceDataSearchData($devicenum,$pagenNum,$limit) : array {
        $databadevice = DB::table('device');
        $devicelist = $databadevice
            ->where('devicenum','=',$devicenum)
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->leftjoin('device_type as dy',"device.dtype",'=','dy.tid')
            ->leftjoin('gas as g',"device.status",'=','g.id')
            ->leftjoin('status as p',"device.devicepolice",'=','p.id')
            ->select('dy.tname','g.gas','device.*','p.status_name')
            ->orderBy('device.id', 'desc')
            ->offset($pagenNum)
            ->limit($limit)
            ->get()->toArray();
        $count = $databadevice
            ->where('dtype','=',$devicenum)
            ->where('delete','=','2')//设备不是删除状态
            ->where('devicestatus','=','1')//
            ->count();
        return ['devicelist'=>$devicelist,'count'=>$count];
    }
    //批量上传设备
    public function batchdevice(){

    }
    //获取设备详情信息
    public function deviceDataInfo($id){
        $devicedata =  Device::where('device.id','=',$id)
        ->leftjoin('contactsuser as c','c.contactsid','=','device.contactsid')
        ->select('c.*','device.deviceuuid','device.devicelinkman','device.devicephone','device.devicecoord')
        ->get();
        $devicedatainfo =  Device::where('id','=',$id)
            ->select('deviceuuid','devicelinkman','devicephone','devicecoord')
            ->get();
        return $this->jsonSuccessData(['devicedata'=>$devicedata,'devicedatainfo'=>$devicedatainfo]);
    }

    //搜索设备账号
    public function deviceDataSearch(Request $request){
        $data = $request->input('deviceName');
        $pagenNum=$request->input('page')-1;//页数
        $limit = $request->input('limit');
        if($pagenNum === '' || $limit == '' || $data == ''){
            return $this->jsonErrorData(105,'请求参数不能为空');
        }
        return $this->jsonSuccessData($this->deviceDataSearchData($data,$pagenNum,$limit));
    }
    //推送获取数据监测数据
    public function equipment(){
        $dalen =  Redis::llen('Devicesdata');//返回队列长度
        if ($dalen > 0){
            return  $this->jsonSuccessData(unserialize(Redis::lpop('Devicesdata')));
        }else{
            return  $this->jsonErrorData(105,'暂无数据');
        }
    }

    //返回设备当前报警
    public function police(){
        return DB::table('reportpolice as r')
            ->where('r.status','=','1')
            ->join('status as s','r.policestatus','=','s.id')
            ->select('r.*','s.status_name')
            ->get()->toArray();
    }
    /**
     * @param bool $isNew
     * @return array
     * 用户添加设备表单验证
     */
    private function getValidationRulesdevice($isNew = true)
    {
        return [
            'devicenum'=>'required|between:2,25|unique:device,devicenum',//设备编号
            'username'=>'required|unique:device,username|max:40',//设备名称
            'devicephone'=> 'sometimes|required|regex:/^1[3465789]\d{9}$/|max:11',//联系人手机号
            'devicelinkman'=>'sometimes|required|max:15',
            'dtype'=>'required',
            'status'=>'required',
            'devicemonad'=>'required',
            'deviceremark'=>'sometimes|required|max:15',
            'devicecoord'=>'sometimes|required',
            'contactsid'=>'sometimes|required',//绑定联系人id
            'deviceinfo'=>'sometimes|required',
            'devicenumber'=>'required|unique:device,devicenumber|max:40'
        ];
    }
    //更新设备列表
    private function getValidationRulesupdevice($isNew = true)
    {
        return [
            'username'=>'sometimes|required|unique:device,username|max:40',//设备名称
            'devicephone'=> 'sometimes|required|regex:/^1[3465789]\d{9}$/|max:11',//联系人手机号
            'devicelinkman'=>'sometimes|required|max:15',
            'dtype'=>'sometimes|required',
            'status'=>'sometimes|required',
            'devicemonad'=>'sometimes|required',
            'deviceremark'=>'sometimes|required|max:15',//备注
            'devicecoord'=>'sometimes|required',
            'contactsid'=>'sometimes|required',//绑定联系人id
            'deviceinfo'=>'sometimes|required',
            'devicenumber'=>'sometimes|required|unique:device,devicenumber|max:40'
        ];
    }

}