<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Exceptions\Exception;
use App\Filters\OwnerMaterialFilters;
use App\Http\Requests\OwnerMaterial\OwnerMaterialRequest;
use App\Material;
use App\OwnerMaterial;
use App\Services\OwnerService;
use App\file;
use App\UploadFile;
use Faker\Provider\Uuid;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;

class OwnerMaterialController extends Controller
{
    use AsyncResponse;
    public function index(Request $request,OwnerMaterialFilters $filters)
    {
        $this->gate('项目耗材');
        $ownerMaterials = OwnerMaterial::query()->with(['owner','material','initiator','file'])->orderByDesc('id')->filter($filters)->paginate($request['paginate'] ?? 50);
        $owners = app(OwnerService::class)->getAuthorizedOwners();
        $materials = Material::all();
        return view('/maintenance/ownerMaterial/index',compact('ownerMaterials','owners','materials'));
    }

    public function storeApi(OwnerMaterialRequest  $request):array
    {
        $this->gate('项目耗材-编辑');
        $params = $request->all(['owner_id', 'material_id', 'material_code', 'size', 'special', 'specification']);
        $params['initiator'] = Auth::user()['id'];
        try {
            $material = OwnerMaterial::query()->create($params);
            if ($material) return ['success' => true,'data' => $material->loadMissing(['owner','material','initiator','file'])];
            else return ['success' => false, 'message' => '添加失败'];
        } catch (\Exception $e) {
            return ['success' => false,'message' => $e->getMessage()];
        }
    }

    public function updateApi(OwnerMaterialRequest $request)
    {
        $this->gate('项目耗材-编辑');
        $material = OwnerMaterial::query()->find($request['id']);
        if(!$material)$this->error("对应的项目耗材没有找到");
        $bool = $material->update($request->all(['owner_id', 'material_id', 'material_code', 'size', 'special', 'specification']));
        if($bool==0)$this->error("更新异常");
        $this->success($material->loadMissing(['owner','material','initiator','file']));
    }

    public function destroyApi($id)
    {
        $this->gate('项目耗材-删除');
        $ownerMaterial = OwnerMaterial::query()->find($id);
        if(!$ownerMaterial)$this->error('对应的项目耗材没有找到');
        $ownerMaterial->delete();
        $this->success();
    }

    public function fileApi(Request $request)
    {
        $this->gate('项目耗材-文件上传');
        $ownerMaterial = OwnerMaterial::query()->find($request['id']);
        if(!$ownerMaterial)$this->error('项目耗材不存在');
        try {
            $file = $request->file('file');
            if(!$file)$this->error('请选择上传文件');
            $fileType = $file->getMimeType();// 文件类型
            $fileName = strtolower($file->getClientOriginalExtension());// 文件名
            $path = $file->storeAs("ownerMaterial", Uuid::uuid() . "." . $fileName/*,'public'*/);
            $file = UploadFile::query()->create([
                'table_name' => 'owner_material',
                'table_id' => $ownerMaterial['id'],
                'url' => $path,
                'type' => $fileType,
                "file_name" => $file->getClientOriginalName()
            ]);
            $ownerMaterial->loadMissing(['owner', 'material', 'initiator', 'file']);
            $this->success($ownerMaterial);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function downFile(Request $request)
    {
        if(!Gate::allows('项目耗材'))return ['success'=>false,"data"=>"无权操作"];
        $file = $request->input("file");
        $name = $request->input("name");
//        return response()->file(storage_path().'/app/public/'.$file);
        return Storage::download($file,$name);
    }
}
