<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\Device;
use App\Models\DeviceName;
use App\Models\Spec;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class DeviceController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new Device();
    }

    public function get(Request $request)
    {
        if($request->input('type') == 'drop_menu') {
            $items = $this->model->select('name as text', 'id as value')->get();
            $items = $items->prepend(collect(['text' => '设备类型', 'value' => '']));
            return $this->success(['data' => $items]);
        }
        $items = $this->model->get();
        return $this->success(['data' => $items]);
    }

    public function transObject($items)
    {
        return json_decode(json_encode($items));
    }

    public function getThreeLevel(Request $request)
    {
        if($request->input('type') == 'drop_menu') {
            $items = $this->model->select('name as text', 'id as value')->get();
            $items = $items->prepend($this->transObject(['text' => '设备类型', 'value' => '']));
            foreach ($items as $item) {
                $names = DeviceName::where('device_id', $item->value)->select('name as text', 'id as value')->get();
                $item->names = $names->prepend($this->transObject(['text' => '设备名称', 'value' => '']));
                foreach($item->names as $name) {
                    $specs  = Spec::where('device_name_id', $name->value)->select('name as text', 'id as value')->get();
                    $name->specs = $specs->prepend($this->transObject(['text' => '规格型号', 'value' => '']));
                }
            }
            return $this->success(['data' => $items]);
        }
        $items = $this->model->select(['id', 'name'])->get();
        foreach($items as $item) {
            $item->names = DeviceName::where('device_id', $item->id)->select(['id', 'name'])->get();
            foreach($item->names as $name) {
                $name->specs = Spec::where('device_name_id', $name->id)->select(['id', 'name'])->get();
            }
        }
        return $this->success(['data' => $items]);
    }
}
