<?php

namespace App\Components;

use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;

trait AsyncResponse{

    protected function gate(string $authorityName)
    {
        if(!Gate::allows($authorityName)){
            echo json_encode(["success"=>false,"data"=>"无权操作"]);
            exit();
        }
    }

    public function error(string $message)
    {
        echo json_encode(["success"=>false,"data"=>$message]);
        exit();
    }

    public function success($message = null)
    {
        $result = ["success"=>true];
        if ($message)$result["data"] = $message;
        echo json_encode($result);
        exit();
    }

    public function importExcel(object $class)
    {
        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        $file = request()->file();
        if (!$file)$this->error("文件不存在");
        $file = reset($file);
        $fileSuffix=strtolower($file->getClientOriginalExtension());
        $types = ["xlsx",'xls','csv'];
        if (!in_array($fileSuffix,$types)) $this->error("不支持该文件类型");
        $fileSuffix = ucwords($fileSuffix);
        Excel::import($class,$file->path(),null,$fileSuffix);
    }
}
