<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Http\Controllers\Controller;
use App\Models\Assets;
use Illuminate\Http\Request;

class EAMController extends Controller
{
    public function assets(Request $request)
    {
        $assets = Assets::query();
        $type = $request->input('type');
        if ($type) {
            $assets = $assets->where('type', $type);
        }
        $keyword = $request->input('keyword');
        if ($keyword) {
            $assets = $assets->where("name", 'like', '%'.$keyword.'%');
        }
        $assets = $assets->orderByDesc('id')->paginate();
        return $this->success('ok', $assets);
    }

    public function storeAssets(Request $request)
    {
        $type = $request->input('type');
        $name = $request->input('name');
        $file = $request->input('file');
        $assets = Assets::create([
            'name'=>$name,
            'file'=>$file,
            'type'=>$type,
        ]);

        //操作记录
        OperationLoggedEvent::dispatch("创建了资产. ID:$assets->id");

        return $this->success('ok');
    }

    public function updateAssets(Request $request, Assets $assets)
    {
        $name = $request->input('name');
        if ($name != $assets->name) {
            $assets->name = $name;
        }
        $file = $request->input('file');
        if ($file != $assets->file) {
            $assets->file = $file;
        }
        $assets->save();

        //操作记录
        OperationLoggedEvent::dispatch("更新了资产. ID:$assets->id");
        return $this->success('ok');
    }

    public function deleteAssets(Request $request, Assets $assets)
    {
        $assets->delete();
        //操作记录
        OperationLoggedEvent::dispatch("删除了资产. ID:$assets->id");
        return $this->success('ok');
    }
}
