<?php

namespace App\Http\Controllers;

use App\OwnerContract;
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 OwnerContractController extends Controller
{
    public function store(Request $request)
    {
        if(!Gate::allows('客户-编辑')){ return ['success'=>false,"data"=>"无权操作"];  }
        $owner_id = $request->input("owner_id");
        $contract_number = $request->input("contract_number");
        if (!$owner_id || !$contract_number)return ["success"=>false,"data"=>"非法参数"];
        $remark = $request->input("remark");
        $contract = OwnerContract::query()->create([
            "owner_id" => $owner_id,
            "contract_number" => $contract_number,
            "salesman" => Auth::user()['name'],
            "remark" => $remark,
        ]);
        $files = $request->file("files");
        if ($files){
            $uploadFiles = [];
            foreach ($files as $file){
                $suffix = strtolower($file->getClientOriginalExtension());
                $path = $file->storeAs("contract",Uuid::uuid().".".$suffix);
                $uploadFiles[] = [
                    "table_name"    => "contracts",
                    "table_id"      => $contract->id,
                    "url"           => $path,
                    "type"          => $suffix,
                    "file_name"     => $file->getClientOriginalName(),
                ];
            }
            UploadFile::query()->insert($uploadFiles);
        }
        $contract->load(["owner","files"]);
        return ["success"=>true,"data"=>$contract];
    }

    public function downFile(Request $request)
    {
        if(!Gate::allows('客户-查询'))return ['success'=>false,"data"=>"无权操作"];
        $file = $request->input("file");
        $name = $request->input("name");
        return Storage::download($file,$name);
    }
}
