<?php

namespace App\Admin\Controllers;

use App\Models\AdminUsers;
use App\Services\SmsService;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    protected $view = 'admin.login';

    public function getLogin(Content $content)
    {
        // 获取角色参数
        $role = request()->get('role');

        // 根据角色参数决定登录页面
        if ($role === 'store') {
            $this->view = 'admin.loginstore'; // 店铺管理员登录页面
        } else {
            $this->view = 'admin.login'; // 默认管理员登录页面
        }

        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }

        return $content->full()->body(view($this->view));
    }

    /**
     * Handle a login request.
     *
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $role = $request->input('role'); // 获取角色参数
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username() => 'required',
            'password' => 'required_with:role',
            'verification_code' => 'required_if:role,store',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        $user = AdminUsers::with('roles')->where(['username' => $credentials['username']])->first();
        if (isset($user->is_block) && $user->is_block) {
            return $this->validationErrorsResponse([
                $this->username() => '账号异常，请联系管理员！',
            ]);
        }
        // 检查用户角色是否为 pharmacy
        $isPharmacy = $user->roles->pluck('slug')->contains('pharmacy');
        if ($role === 'store' && $user && $isPharmacy) {
            // 验证短信验证码
            $verificationCode = $request->input('verification_code');
            // 假设您有一个方法来验证短信验证码
            if ($this->verifySmsCode($user->username, $verificationCode)) {
                $this->guard()->login($user, $remember);

                // 登录成功后，删除缓存中的短信验证码
                cache()->forget("sms_verification_code_{$user->username}");

                return $this->sendLoginResponse($request);
            } else {
                return $this->validationErrorsResponse([
                    'verification_code' => '验证码错误或已过期！',
                ]);
            }

            // 短信验证码验证通过，执行登录
            return $this->guard()->login($user, $remember) ? $this->sendLoginResponse($request) : $this->sendFailedLoginResponse($request);
        }

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    /**
     * User logout.
     *
     * @return Redirect|string
     */
    public function getLogout(Request $request)
    {
        $isPharmacy = Admin::user() ? Admin::user()->isRole('pharmacy') : false;
        $this->guard()->logout();

        $request->session()->invalidate();

        $path = admin_url('auth/login');
        // 如果是店铺角色，则追加参数，跳转到店铺登录页
        if ($isPharmacy) {
            $path = admin_url('auth/login?role=store');
        }
        if ($request->pjax()) {
            return "<script>location.href = '$path';</script>";
        }

        return redirect($path);
    }

    // 药店管理员角色登录使用
    public function getLoginSmsCode(Request $request)
    {
        // 验证手机号是否存在
        $phone = $request->input('username');
        if (! $phone) {
            return response()->json(['error' => '手机号不能为空']);
        }

        // 验证手机号格式
        if (! preg_match('/^1[3-9]\d{9}$/', $phone)) {
            return response()->json(['error' => '手机号格式不正确']);
        }

        // 检查手机号在管理员表中是否存在
        $user = AdminUsers::where('username', $phone)->first();
        if (! $user) {
            return response()->json(['error' => '该药店手机号未注册，请联系管理员~']);
        }

        // 检查当天发送次数
        $today = date('Y-m-d');
        $smsCountKey = "sms_count_{$phone}_{$today}";
        $smsCount = cache()->get($smsCountKey, 0);
        if ($smsCount >= 10) {
            return response()->json(['error' => '今天该手机号已达到发送次数上限']);
        }

        // 生成短信验证码
        $verificationCode = rand(100000, 999999); // 生成6位随机验证码

        // 存储验证码和有效期（10分钟）
        cache()->put("sms_verification_code_{$phone}", $verificationCode, 600); // 600秒 = 10分钟
        // 设置当天发送次数的过期时间为当天结束
        cache()->put($smsCountKey, $smsCount + 1, strtotime('tomorrow') - time()); // 设置为明天0点过期

        $templateName = 'verification_code';
        $templateData = ['code' => $verificationCode];
        $smsService = new SmsService();
        $response = $smsService->sendSms($phone, $templateName, $templateData);

        return response()->json(['success' => true, 'message' => '验证码已发送']);
    }

    /**
     * 验证短信验证码
     *
     * @param  string  $username
     * @param  string  $code
     * @return bool
     */
    protected function verifySmsCode($username, $code)
    {
        $cachedCode = cache()->get("sms_verification_code_{$username}");

        return $cachedCode && $cachedCode === $code;
    }
}
