<?php

namespace App\Http\Controllers\Auth\Admin;

use App\Http\Controllers\Controller;
use App\Services\Auth\PermissionService;
use App\Services\Auth\ImportExportService;
use Illuminate\Http\Request;

class Permission extends Controller
{
    protected $permissionService;
    protected $importExportService;

    public function __construct(
        PermissionService $permissionService,
        ImportExportService $importExportService
    ) {
        $this->permissionService = $permissionService;
        $this->importExportService = $importExportService;
    }

    /**
     * 获取权限列表
     */
    public function index(Request $request)
    {
        $params = $request->all();
        $result = $this->permissionService->getList($params);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $result,
        ]);
    }

    /**
     * 获取权限树
     */
    public function tree(Request $request)
    {
        $params = $request->all();
        $result = $this->permissionService->getTree($params);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $result,
        ]);
    }

    /**
     * 获取菜单树
     */
    public function menu(Request $request)
    {
        $result = $this->permissionService->getMenuTree();

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $result,
        ]);
    }

    /**
     * 获取权限详情
     */
    public function show($id)
    {
        $result = $this->permissionService->getById($id);

        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => $result,
        ]);
    }

    /**
     * 创建权限
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:50',
            'name' => 'required|string|max:100|unique:auth_permissions,name',
            'type' => 'required|in:menu,api,button',
            'route' => 'nullable|string|max:200',
            'component' => 'nullable|string|max:200',
            'parent_id' => 'nullable|integer|min:0',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
            'meta' => 'nullable|array',
        ], [], [
            'parent_id.exists' => '父级权限不存在',
        ]);

        // 额外验证：如果 parent_id 不为 0，则必须存在
        if (!empty($validated['parent_id']) && $validated['parent_id'] != 0) {
            $parent = \App\Models\Auth\Permission::find($validated['parent_id']);
            if (!$parent) {
                return response()->json([
                    'code' => 422,
                    'message' => '验证失败',
                    'data' => [
                        'parent_id' => ['父级权限不存在']
                    ]
                ], 422);
            }
        }

        $result = $this->permissionService->create($validated);

        return response()->json([
            'code' => 200,
            'message' => '创建成功',
            'data' => ['id' => $result->id],
        ], 201);
    }

    /**
     * 更新权限
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'title' => 'nullable|string|max:50',
            'name' => 'nullable|string|max:100|unique:auth_permissions,name,' . $id,
            'type' => 'nullable|in:menu,api,button',
            'route' => 'nullable|string|max:200',
            'component' => 'nullable|string|max:200',
            'parent_id' => 'nullable|integer|min:0',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
            'meta' => 'nullable|array',
        ], [], [
            'parent_id.exists' => '父级权限不存在',
        ]);

        // 额外验证：如果 parent_id 不为 0，则必须存在
        if (isset($validated['parent_id']) && !empty($validated['parent_id']) && $validated['parent_id'] != 0) {
            $parent = \App\Models\Auth\Permission::find($validated['parent_id']);
            if (!$parent) {
                return response()->json([
                    'code' => 422,
                    'message' => '验证失败',
                    'data' => [
                        'parent_id' => ['父级权限不存在']
                    ]
                ], 422);
            }
        }

        $result = $this->permissionService->update($id, $validated);

        return response()->json([
            'code' => 200,
            'message' => '更新成功',
            'data' => ['id' => $result->id],
        ]);
    }

    /**
     * 删除权限
     */
    public function destroy($id)
    {
        $this->permissionService->delete($id);

        return response()->json([
            'code' => 200,
            'message' => '删除成功',
            'data' => null,
        ]);
    }

    /**
     * 批量删除权限
     */
    public function batchDelete(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
        ]);

        $count = $this->permissionService->batchDelete($validated['ids']);

        return response()->json([
            'code' => 200,
            'message' => "成功删除 {$count} 条数据",
            'data' => ['count' => $count],
        ]);
    }

    /**
     * 批量更新权限状态
     */
    public function batchUpdateStatus(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'status' => 'required|integer|in:0,1',
        ]);

        $count = $this->permissionService->batchUpdateStatus($validated['ids'], $validated['status']);

        return response()->json([
            'code' => 200,
            'message' => "成功更新 {$count} 条数据",
            'data' => ['count' => $count],
        ]);
    }

    /**
     * 导出权限
     */
    public function export(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'nullable|array',
            'ids.*' => 'integer',
        ]);

        $filename = $this->importExportService->exportPermissions($validated['ids'] ?? []);

        $filePath = $this->importExportService->getExportFilePath($filename);

        return response()->download($filePath, $filename)->deleteFileAfterSend();
    }

    /**
     * 导入权限
     */
    public function import(Request $request)
    {
        $validated = $request->validate([
            'file' => 'required|file|mimes:xlsx,xls',
        ]);

        $file = $request->file('file');
        $realPath = $file->getRealPath();
        $filename = $file->getClientOriginalName();

        $result = $this->importExportService->importPermissions($filename, $realPath);

        return response()->json([
            'code' => 200,
            'message' => "导入完成，成功 {$result['success_count']} 条，失败 {$result['error_count']} 条",
            'data' => $result,
        ]);
    }

    /**
     * 下载权限导入模板
     */
    public function downloadTemplate()
    {
        $filename = $this->importExportService->downloadPermissionTemplate();
        $filePath = $this->importExportService->getExportFilePath($filename);

        return response()->download($filePath, $filename)->deleteFileAfterSend();
    }
}
