<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Menu\StoreMenuRequest;
use App\Http\Requests\Menu\UpdateMenuRequest;
use App\Http\Responses\ApiResponse;
use App\Models\AdminMenuTerminal;
use App\Services\MenuService;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    protected $menuService;

    public function __construct(MenuService $menuService)
    {
        $this->menuService = $menuService;
    }

    public function index(Request $request)
    {
        $result = $this->menuService->index($request->all());

        return response()->json($result);
    }

    public function tree(Request $request)
    {
        $terminalType = $request->input('terminal_type');
        $result = $this->menuService->tree($terminalType);

        return response()->json($result);
    }

    public function user()
    {
        $result = $this->menuService->userMenus();

        return response()->json($result);
    }

    public function store(StoreMenuRequest $request)
    {
        $result = $this->menuService->store($request->validated());

        return response()->json($result);
    }

    public function show($id)
    {
        $result = $this->menuService->show((int) $id);

        return response()->json($result);
    }

    public function update(UpdateMenuRequest $request, $id)
    {
        $result = $this->menuService->update($id, $request->validated());

        return response()->json($result);
    }

    public function destroy($id)
    {
        $result = $this->menuService->destroy($id);

        return response()->json($result);
    }

    public function updateVisible(Request $request, $id)
    {
        $request->validate([
            'visible' => 'required|in:0,1',
        ]);

        $result = $this->menuService->updateVisible($id, $request->visible);

        return response()->json($result);
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:0,1',
        ]);

        $result = $this->menuService->updateStatus($id, $request->status);

        return response()->json($result);
    }

    public function saveSort(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'sorts' => 'required|array',
            'sorts.*' => 'integer',
        ]);

        $result = $this->menuService->saveSort($request->ids, $request->sorts);

        return response()->json($result);
    }

    public function terminals(Request $request)
    {
        $query = AdminMenuTerminal::query();

        if (isset($request->keyword) && ! empty($request->keyword)) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->keyword}%")
                    ->orWhere('type', 'like', "%{$request->keyword}%");
            });
        }

        if (isset($request->status) && $request->status !== '') {
            $query->where('status', $request->status);
        }

        $perPage = $request->per_page ?? 20;
        $terminals = $query->orderBy('sort', 'asc')->orderBy('id', 'desc')->paginate($perPage);

        return response()->json(ApiResponse::paginate($terminals));
    }

    public function storeTerminal(Request $request)
    {
        $request->validate([
            'type' => 'required|string|max:50|unique:admin_menu_terminals,type',
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $terminal = AdminMenuTerminal::create([
            'type' => $request->type,
            'name' => $request->name,
            'description' => $request->description ?? '',
            'sort' => $request->sort ?? 0,
            'status' => $request->status ?? 1,
        ]);

        return response()->json(ApiResponse::success($terminal, '创建成功'));
    }

    public function updateTerminal(Request $request, $id)
    {
        $terminal = AdminMenuTerminal::find($id);

        if (! $terminal) {
            return response()->json(ApiResponse::error(40401, '终端不存在'));
        }

        $request->validate([
            'type' => 'required|string|max:50|unique:admin_menu_terminals,type,'.$id,
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $terminal->update([
            'type' => $request->type,
            'name' => $request->name,
            'description' => $request->description ?? '',
            'sort' => $request->sort ?? 0,
            'status' => $request->status ?? 1,
        ]);

        return response()->json(ApiResponse::success($terminal, '更新成功'));
    }

    public function destroyTerminal($id)
    {
        $terminal = AdminMenuTerminal::find($id);

        if (! $terminal) {
            return response()->json(ApiResponse::error(40401, '终端不存在'));
        }

        $terminal->delete();

        return response()->json(ApiResponse::success(null, '删除成功'));
    }

    public function updateTerminalStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|boolean',
        ]);

        $terminal = AdminMenuTerminal::find($id);

        if (! $terminal) {
            return response()->json(ApiResponse::error(40401, '终端不存在'));
        }

        $terminal->update(['status' => $request->status ? 1 : 0]);

        return response()->json(ApiResponse::success(null, '更新成功'));
    }

    public function homeMenus()
    {
        $result = $this->menuService->homeMenus();

        return response()->json($result);
    }

    public function saveTerminalSort(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'sorts' => 'required|array',
            'sorts.*' => 'integer',
        ]);

        foreach ($request->ids as $index => $id) {
            AdminMenuTerminal::where('id', $id)->update([
                'sort' => isset($request->sorts[$index]) ? intval($request->sorts[$index]) : 0,
            ]);
        }

        return response()->json(ApiResponse::success(null, '排序保存成功'));
    }
}
