<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\DeviceName;
use App\Models\Spec;
use Illuminate\Http\Request;

class DeviceNameController extends BaseController
{
    protected $model;

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

    public function get(Request $request)
    {
        if($request->input('type') == 'drop_menu') {
            $items = $this->model;
            if($request->input('device_ids')) {
                $device_ids = $request->input('device_ids');
                $device_ids = array_filter($device_ids, function($item) {
                    return $item;
                });
                if(count($device_ids) > 0) {
                    $items = $items->whereIn('device_id', $device_ids);
                }
            }
            $items = $items->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 getNamesAndSpecs(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) {
                $specs  = Spec::where('device_name_id', $item->value)->select('name as text', 'id as value')->get();
                $item->specs = $specs->prepend($this->transObject(['text' => '规格型号', 'value' => '']));
            }
            return $this->success(['data' => $items]);
        }
        $items = $this->model->select(['id', 'name'])->get();
        foreach($items as $name) {
            $name->specs = Spec::where('device_name_id', $name->id)->select(['id', 'name'])->get();
        }
        return $this->success(['data' => $items]);
    }

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