<?php

namespace App\Http\Controllers\Auth\Admin;

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

class Role extends Controller
{
    protected $roleService;
    protected $importExportService;

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

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

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

    /**
     * 获取所有角色（不分页）
     */
    public function getAll()
    {
        $result = $this->roleService->getAll();

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

    /**
     * 获取角色详情
     */
    public function show($id)
    {
        $result = $this->roleService->getById($id);

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

    /**
     * 创建角色
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|unique:auth_roles,code',
            'description' => 'nullable|string|max:200',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
            'permission_ids' => 'nullable|array',
            'permission_ids.*' => 'integer|exists:auth_permissions,id',
        ]);

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

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

    /**
     * 更新角色
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'nullable|string|max:50',
            'code' => 'nullable|string|max:50|unique:auth_roles,code,' . $id,
            'description' => 'nullable|string|max:200',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
            'permission_ids' => 'nullable|array',
            'permission_ids.*' => 'integer|exists:auth_permissions,id',
        ]);

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

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

    /**
     * 删除角色
     */
    public function destroy($id)
    {
        $this->roleService->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->roleService->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->roleService->batchUpdateStatus($validated['ids'], $validated['status']);

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

    /**
     * 分配权限
     */
    public function assignPermissions(Request $request, $id)
    {
        $validated = $request->validate([
            'permission_ids' => 'required|array',
            'permission_ids.*' => 'integer|exists:auth_permissions,id',
        ]);

        $this->roleService->assignPermissions($id, $validated['permission_ids']);

        return response()->json([
            'code' => 200,
            'message' => '权限分配成功',
            'data' => null,
        ]);
    }

    /**
     * 获取角色的权限列表
     */
    public function getPermissions($id)
    {
        $result = $this->roleService->getPermissions($id);

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

    /**
     * 复制角色
     */
    public function copy(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|unique:auth_roles,code',
            'description' => 'nullable|string|max:200',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $result = $this->roleService->copy($id, $validated);

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

    /**
     * 批量复制角色
     */
    public function batchCopy(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'name' => 'nullable|string|max:50',
            'code' => 'nullable|string|max:50',
            'description' => 'nullable|string|max:200',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|integer|in:0,1',
        ]);

        $result = $this->roleService->batchCopy($validated['ids'], $validated);

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

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

        $filename = $this->importExportService->exportRoles($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->importRoles($filename, $realPath);

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

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

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