<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Configuration;
use App\Filters\ConfigurationFilters;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class ConfigurationController extends Controller
{
    use AsyncResponse;
    private $procurement_configuration_cache_key='procurement_configuration_cache_key_';
    public function index(Request $request,ConfigurationFilters $filters)
    {
        $this->gate('系统配置');
        $configurations = Configuration::query()->orderBy('id')->filter($filters)->paginate($request['paginate'] ?? 50);
        return view('/maintenance/configuration/index',compact('configurations'));
    }

    public function storeApi(Request $request)
    {
        $this->gate('系统配置-编辑');
        $params = $request->all();
        $params['operator'] = Auth::user()['id'];
        $configuration = Configuration::query()->create($params);
        Cache::put($this->procurement_configuration_cache_key.$params['name'],$configuration['value']);
        if($configuration)$this->success($configuration->loadMissing('operator'));
        $this->error('创建失败');
    }

    public function updateApi(Request $request)
    {
        $this->gate('系统配置-编辑');
        $configuration = Configuration::query()->find($request['id']);
        if(!$configuration)$this->error('更新异常');
        $params = $request->only(['name','value','description']);
        $params['operator'] = Auth::user()['id'];
        $configuration->update($params);
        Cache::put($this->procurement_configuration_cache_key.$params['name'],$configuration['value']);
        $this->success($configuration->loadMissing('operator'));
    }

    public function destroyApi($id)
    {
        $this->gate('系统配置-删除');
        Configuration::query()->where('id',$id)->delete();
        $this->success();
    }
}
