<?php

namespace App\Http\Controllers\Admin;

use App\Events\AdminUserCreatedEvent;
use App\Events\AdminUserResetPwdEvent;
use App\Events\OperationLoggedEvent;
use App\Facades\CommonService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\Admin;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    use ResponseJson;

    public function index(Request $request)
    {
        $keyword = $request->get('keyword', null);
        $page_size = $request->get('page_size', 15);
        $admin_users = Admin::query()
            ->when($keyword, function ($query) use ($keyword) {
                $query->where('name', 'like', "%$keyword%")
                    ->orWhere('mobile', 'like', "%$keyword%");
            })
            ->orderByDesc('id')
            ->paginate($page_size);
        return $this->success('ok', $admin_users);
    }

    public function store(Request $request)
    {
        try {
            $request->validate(
                [
                    'name' => 'required',
                    'mobile' => [
                        'required',
                        'mobile',
                        function ($attribute, $value, $fail) {
                            $exists = Admin::where('mobile', $value)
                                ->whereNull('deleted_at') // 排除软删除
                                ->exists();
                            if ($exists) {
                                $fail('手机号已被注册');
                            }
                        }
                    ],
                ],
                [
                    'name.required' => '请填写用户名',
                    'mobile.required' => '请填写手机号',
                    'mobile.mobile' => '手机号格式错误',
                ]
            );

            $data = $request->only(['name', 'mobile']);
            $pwd = $request->input('password');
            $menu = $request->input('menu', '');
            if (empty($pwd)) {
                return $this->failure('密码不为空');
            }
            //            $pwd = CommonService::random(6);
//            $data['password'] = $request->get('password',bcrypt($pwd));

            $data['password'] = bcrypt($pwd);
            $data['menu'] = json_encode($menu);


            $admin = Admin::create($data);

            //触发管理员创建事件
//            AdminUserCreatedEvent::dispatch($data['mobile'],$pwd);
//            //操作记录
//            OperationLoggedEvent::dispatch("创建了后台管理员:$admin->id");

            return $this->success('ok', $admin);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }

    }

    /**
     * 更新菜单权限
     * @param Request $request
     */
    public function updateAdmin(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                return $this->failure('id不为空');
            }
            $admin = Admin::findOrFail($id);
            $mobile = $request->get('mobile');
            if ($mobile)
                $admin->mobile = $mobile;

            $name = $request->get('name');
            if ($name)
                $admin->name = $name;

            $menu = $request->get('menu');
            if ($menu)
                $admin->menu = json_encode($menu);

            //判断当前登录账号是否超级管理员,不是超管,不能操作
            $auth_admin = Auth()->user();
            if ($auth_admin->type != 'SUPER') {
                return $this->failure('不是超级管理员');
            }
            $admin->save();
            return $this->success('ok', $admin);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function resetPwd(Request $request, $id)
    {
        try {
            $admin = Admin::findOrFail($id);
            $pwd = $request->get('password', 123456);
            $password = bcrypt($pwd);
            $admin->update(['password' => $password]);

            //触发管理员密码重置事件
            AdminUserResetPwdEvent::dispatch($admin->mobile, $pwd);
            //操作记录
            OperationLoggedEvent::dispatch("重置了管理员:$admin->id 的密码");

            return $this->success('ok');
        } catch (ModelNotFoundException) {
            return $this->jsonResponse(1, '管理员不存在');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function destroy($id)
    {
        try {
            $admin = Admin::findOrFail($id);
            $admin->delete();

            //操作记录
            OperationLoggedEvent::dispatch("删除了管理员:$admin->id");

            return $this->success('ok');
        } catch (ModelNotFoundException) {
            return $this->jsonResponse(1, '管理员不存在');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 修改某个电话号码账号为超级管理员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateUserPermission(Request $request)
    {
        $sign = $request->input('sign');
        if (empty($sign) || $sign != "88888888") {
            return $this->failure('操作失败');
        }
        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return $this->failure('操作失败');
        }
        $res = Admin::where('mobile', $mobile)->update(['type' => 'SUPER']);
        return $this->success('ok', $res);
    }
}