<?php

namespace App\Http\Controllers\Auth\Admin;

use App\Http\Controllers\Controller;
use App\Services\Auth\UserService;
use App\Services\Auth\UserOnlineService;
use App\Services\Auth\ImportExportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class User extends Controller
{
    protected $userService;
    protected $userOnlineService;
    protected $importExportService;

    public function __construct(
        UserService $userService,
        UserOnlineService $userOnlineService,
        ImportExportService $importExportService
    ) {
        $this->userService = $userService;
        $this->userOnlineService = $userOnlineService;
        $this->importExportService = $importExportService;
    }

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

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

    /**
     * 获取用户详情
     */
    public function show(Request $request, $id)
    {
        $result = $this->userService->getById($id);

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

    /**
     * 创建用户
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'username' => 'required|string|max:50|unique:auth_user,username',
            'password' => 'required|string|min:6',
            'real_name' => 'required|string|max:50',
            'email' => 'nullable|email|unique:auth_user,email',
            'phone' => 'nullable|string|max:20',
            'department_id' => 'nullable|integer|exists:auth_departments,id',
            'role_ids' => 'nullable|array',
            'role_ids.*' => 'integer|exists:auth_roles,id',
            'status' => 'nullable|integer|in:0,1',
        ]);

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

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

    /**
     * 更新用户
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'username' => 'nullable|string|max:50|unique:auth_user,username,' . $id,
            'password' => 'nullable|string|min:6',
            'real_name' => 'nullable|string|max:50',
            'email' => 'nullable|email|unique:auth_user,email,' . $id,
            'phone' => 'nullable|string|max:20',
            'avatar' => 'nullable|string|max:500',
            'department_id' => 'nullable|integer|exists:auth_departments,id',
            'role_ids' => 'nullable|array',
            'role_ids.*' => 'integer|exists:auth_roles,id',
            'status' => 'nullable|integer|in:0,1',
        ]);

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

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

    /**
     * 删除用户
     */
    public function destroy(Request $request, $id)
    {
        $this->userService->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->userService->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->userService->batchUpdateStatus($validated['ids'], $validated['status']);

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

    /**
     * 批量分配部门
     */
    public function batchAssignDepartment(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'department_id' => 'nullable|integer|exists:auth_departments,id',
        ]);

        $count = $this->userService->batchAssignDepartment($validated['ids'], $validated['department_id']);

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

    /**
     * 批量分配角色
     */
    public function batchAssignRoles(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer',
            'role_ids' => 'nullable|array',
            'role_ids.*' => 'integer|exists:auth_roles,id',
        ]);

        $count = $this->userService->batchAssignRoles($validated['ids'], $validated['role_ids'] ?? []);

        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->exportUsers($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->importUsers($filename, $realPath);

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

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

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

    /**
     * 获取在线用户数量
     */
    public function getOnlineCount()
    {
        $count = $this->userOnlineService->getOnlineCount();

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

    /**
     * 获取在线用户列表
     */
    public function getOnlineUsers(Request $request)
    {
        $limit = $request->get('limit', 100);
        $users = $this->userOnlineService->getOnlineUsers($limit);

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

    /**
     * 获取用户的所有会话
     */
    public function getUserSessions($userId)
    {
        $sessions = $this->userOnlineService->getUserSessions($userId);

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

    /**
     * 强制用户下线（单个会话）
     */
    public function setUserOffline($userId, Request $request)
    {
        $validated = $request->validate([
            'token' => 'nullable|string',
        ]);

        if (!empty($validated['token'])) {
            $this->userOnlineService->setOffline($userId, $validated['token']);
        }

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

    /**
     * 强制用户所有设备下线
     */
    public function setUserAllOffline($userId)
    {
        $this->userOnlineService->setAllOffline($userId);

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