<?php

namespace App\Services;

use App\Http\Responses\ApiResponse;
use App\Models\User;
use App\Models\UserGroup;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class FrontUserService
{
    public function index(array $params)
    {
        $query = User::with('group');

        if (isset($params['keyword']) && ! empty($params['keyword'])) {
            $query->where(function ($q) use ($params) {
                $q->where('username', 'like', "%{$params['keyword']}%")
                    ->orWhere('nickname', 'like', "%{$params['keyword']}%")
                    ->orWhere('email', 'like', "%{$params['keyword']}%")
                    ->orWhere('phone', 'like', "%{$params['keyword']}%");
            });
        }

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

        if (isset($params['group_id']) && $params['group_id'] !== '') {
            $query->where('group_id', $params['group_id']);
        }

        $perPage = $params['per_page'] ?? config('cmspro.pagination.per_page', 15);
        $users = $query->orderBy('id', 'desc')->paginate($perPage);

        return ApiResponse::paginate($users);
    }

    public function store(array $data)
    {
        $usernameExists = User::where('username', $data['username'])->exists();
        if ($usernameExists) {
            return ApiResponse::error(60201, '用户名已存在');
        }

        if (! empty($data['email'])) {
            $emailExists = User::where('email', $data['email'])->exists();
            if ($emailExists) {
                return ApiResponse::error(60202, '邮箱已存在');
            }
        }

        if (! empty($data['phone'])) {
            $phoneExists = User::where('phone', $data['phone'])->exists();
            if ($phoneExists) {
                return ApiResponse::error(60203, '手机号已存在');
            }
        }

        $groupId = $data['group_id'] ?? $this->getDefaultGroupId();

        $user = User::create([
            'username' => $data['username'],
            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'password' => Hash::make($data['password']),
            'nickname' => $data['nickname'] ?? null,
            'avatar' => $data['avatar'] ?? null,
            'gender' => $data['gender'] ?? 0,
            'birthday' => $data['birthday'] ?? null,
            'signature' => $data['signature'] ?? null,
            'group_id' => $groupId,
            'status' => $data['status'] ?? 1,
        ]);

        // 保存扩展数据
        if (isset($data['ext_fields']) && is_array($data['ext_fields'])) {
            app(UserExtFieldService::class)->saveUserExtData($user->id, $data['ext_fields']);
        }

        return ApiResponse::success($user->load('group'), '创建成功');
    }

    public function show(int $id)
    {
        $user = User::with('group')->find($id);

        if (! $user) {
            return ApiResponse::error(60204, '用户不存在');
        }

        // 附加扩展数据
        $user->ext_fields = app(UserExtFieldService::class)->getUserExtData($id);

        return ApiResponse::success($user);
    }

    public function update(int $id, array $data)
    {
        $user = User::find($id);

        if (! $user) {
            return ApiResponse::error(60204, '用户不存在');
        }

        if (! empty($data['email']) && $data['email'] !== $user->email) {
            $emailExists = User::where('email', $data['email'])
                ->where('id', '!=', $id)
                ->exists();
            if ($emailExists) {
                return ApiResponse::error(60202, '邮箱已存在');
            }
        }

        if (! empty($data['phone']) && $data['phone'] !== $user->phone) {
            $phoneExists = User::where('phone', $data['phone'])
                ->where('id', '!=', $id)
                ->exists();
            if ($phoneExists) {
                return ApiResponse::error(60203, '手机号已存在');
            }
        }

        $updateData = [
            'email' => $data['email'] ?? $user->email,
            'phone' => $data['phone'] ?? $user->phone,
            'nickname' => $data['nickname'] ?? $user->nickname,
            'avatar' => $data['avatar'] ?? $user->avatar,
            'gender' => $data['gender'] ?? $user->gender,
            'birthday' => $data['birthday'] ?? $user->birthday,
            'signature' => $data['signature'] ?? $user->signature,
            'group_id' => $data['group_id'] ?? $user->group_id,
        ];

        if (isset($data['password']) && ! empty($data['password'])) {
            $updateData['password'] = Hash::make($data['password']);
        }

        if (isset($data['status'])) {
            $updateData['status'] = $data['status'];
        }

        $user->update($updateData);

        // 保存扩展数据
        if (isset($data['ext_fields']) && is_array($data['ext_fields'])) {
            app(UserExtFieldService::class)->saveUserExtData($id, $data['ext_fields']);
        }

        return ApiResponse::success($user->load('group'), '更新成功');
    }

    public function destroy(int $id)
    {
        $user = User::find($id);

        if (! $user) {
            return ApiResponse::error(60204, '用户不存在');
        }

        DB::transaction(function () use ($user) {
            $user->thirdPartyBindings()->delete();
            $user->delete();
        });

        return ApiResponse::success(null, '删除成功');
    }

    public function updateStatus(int $id, int $status)
    {
        $user = User::find($id);

        if (! $user) {
            return ApiResponse::error(60204, '用户不存在');
        }

        $user->update(['status' => $status]);

        return ApiResponse::success($user, $status === 1 ? '启用成功' : '禁用成功');
    }

    public function resetPassword(int $id, string $password)
    {
        $user = User::find($id);

        if (! $user) {
            return ApiResponse::error(60204, '用户不存在');
        }

        $user->update(['password' => Hash::make($password)]);

        return ApiResponse::success(null, '重置密码成功');
    }

    public function batchDelete(array $ids)
    {
        DB::transaction(function () use ($ids) {
            $users = User::whereIn('id', $ids)->get();
            foreach ($users as $user) {
                $user->thirdPartyBindings()->delete();
                $user->delete();
            }
        });

        return ApiResponse::success(null, '批量删除成功');
    }

    private function getDefaultGroupId(): ?int
    {
        $defaultGroup = UserGroup::default()->enabled()->first();

        return $defaultGroup?->id;
    }
}
