<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Filters\SupplierFilters;
use App\Http\Requests\Supplier\SupplierRequest;
use App\Material;
use App\MaterialSupplier;
use App\Supplier;
use Illuminate\Http\Request;

class SupplierController extends Controller
{
    use AsyncResponse;

    public function index(Request $request, SupplierFilters $filters)
    {
        $this->gate('供应商');
        $suppliers = Supplier::query()->with('material')->orderByDesc('id')->filter($filters)->paginate($request['paginate'] ?? 50);
        $materials = Material::query()->select('id', 'name')->get();
        return view('/maintenance/supplier/index', compact('suppliers', 'materials'));
    }

    public function storeApi(SupplierRequest $request)
    {
        $this->gate('供应商-编辑');
        $supplier = Supplier::query()->create($request->all());
        $material_supplier = [];
        foreach ($request['material_id'] as $item) {
            $material_supplier[] = [
                'material_id' => $item,
                'supplier_id' => $supplier['id'],
            ];
        }
        MaterialSupplier::query()->insert($material_supplier);
        $supplier->loadMissing('material');
        $this->success($supplier);
    }

    public function updateApi(SupplierRequest $request)
    {
        $this->gate('供应商-编辑');
        $material_suppliers = MaterialSupplier::query()->where('supplier_id', $request['id'])->get();
        $this->updateMaterial($material_suppliers, $request['material_id'], $request['id']);
        /** @var Supplier $supplier */
        $supplier = Supplier::query()->find($request['id']);
        $bool = $supplier->update($request->all());
        if ($bool) $this->success($supplier->loadMissing('material'));
        $this->error('更新异常');
    }

    public function destroyApi($id)
    {
        $this->gate('供应商-删除');
        /** @var Supplier $supplier */
        $supplier = Supplier::query()->find($id);
        $supplier->delete();
        $this->success();
    }

    private function updateMaterial($material_suppliers, $material_ids, $supplier_id)
    {
        $exist = [];
        $adds = [];
        $addMaterial = [];
        foreach ($material_suppliers as $material_supplier) {
            $exist[] = $material_supplier['material_id'];
        }
        $deletes = array_diff($exist, $material_ids);
        foreach ($material_ids as $id) {
            if (empty($material_suppliers->where('material_id', $id)->first())) $adds[] = $id;
        }
        foreach ($adds as $add) {
            $addMaterial[] = [
                'material_id' => $add,
                'supplier_id' => $supplier_id,
            ];
        }
        if (count($addMaterial) > 0) MaterialSupplier::query()->insert($addMaterial);
        foreach ($deletes as $delete) {
            MaterialSupplier::query()->where('material_id', $delete)->where('supplier_id', $supplier_id)->delete();
        }
    }
}
