<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Facades\UserService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\Admin;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    use ResponseJson;
    public function mobileLogin(Request $request)
    {
        $mobile = $request->input('mobile');
        $password = $request->input('password');
        $admin = Admin::where("mobile", $mobile)->first();
        if (empty($admin)) return $this->failure("登录失败，未找到对应账号");
        $res = Hash::check($password, $admin->password);
        if (!$res) return $this->failure("登录失败，密码错误");
        //登录token
//        if (!$admin->expire_at || $admin->expire_at < date('Y-m-d H:i:s')){
//            $carbon_expire_at = Carbon::now()->addDays(30);
//            $expire_at = $carbon_expire_at->toDateTimeString();
//            $api_token = $admin->createToken('admin_'.$admin->id, ['*'], $carbon_expire_at)->plainTextToken;
//            Admin::where('id',$admin->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
//            $admin->api_token = $api_token;
//        }
        $admin->api_token = UserService::apiJwtToken($admin);
        $admin->makeVisible('api_token');
        $admin->makeVisible('mobile');
        $admin->is_administrator = $admin->type == "SUPER";
        $admin->menu = json_decode($admin->menu,true);

        return $this->success('ok', $admin);
    }

    public function resetPassword(Request $request)
    {
        $user = auth()->user();
        $password = $request->input('password');
        $conf_password = $request->input("password");
        if ($password !== $conf_password) return $this->failure("密码不一致");
        $user->password = Hash::make($password);
        $user->save();

        //操作记录
        OperationLoggedEvent::dispatch("重置了密码");
        return $this->success('ok', $user);
    }
}
