<?php

namespace App\Services;

use App\Models\Admin;
use App\Models\User;
use Carbon\Carbon;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserService
{
    public function checkSymptoms($user_info)
    {
        if (empty($user_info->stomach)) return 0;
//        if (empty($user_info->heart)) return 0;
        if (empty($user_info->sleep)) return 0;
        if (empty($user_info->immunity)) return 0;
        return 1;
    }

    public function checkUserInfo($user, $user_info)
    {
        $user_params = ['name', 'sex', 'birthday', 'stature'];
        $user_info_params = ['vegan', 'egg', 'weight'];
        //个人信息
        foreach ($user_params as $param) {
            if (empty($user->$param)) return 0;
        }

        foreach ($user_info_params as $param) {
            if (empty($user_info->$param) && !is_numeric($user_info->$param)) return 0;
        }
//        $count = $user->healthLogs()->where('e_name', 'Weight')->count();
//        if (empty($count)) return 0;
        return 1;
    }

    public function apiToken($user)
    {
        if (!$user->expire_at || $user->expire_at < date('Y-m-d H:i:s')){
            $carbon_expire_at = Carbon::now()->addDays(30);
            $expire_at = $carbon_expire_at->toDateTimeString();
            $api_token = $user->createToken($user->id, ['*'], $carbon_expire_at)->plainTextToken;
            $user::class::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
            $user->api_token = $api_token;
            return $api_token;
        }
        return $user->api_token;
    }

    public function checkJwtToken($token,$is_admin = false)
    {
        $res = JWT::decode($token, new Key(config("jwt.secret"),config('jwt.algorithm') ));
        if ($res) {
            // Log::info("授权解析后的用户id: {$res->Userid}");
            // Log::info("授权解析后过期时间: {$res->ExpiredAt}". "/". date("Y-m-d H:i:s", $res->ExpiredAt));
            // Log::info("当前时间: ".time(). "/".date("Y-m-d H:i:s"));

            //用户id是否存在
            $user_id = $res->Userid;
            if (empty($user_id)) return null;
            //是否过期
            $expired_at = $res->ExpiredAt;
            if (empty($expired_at)) return null;
            if (time() > $expired_at) return null;
            if($is_admin){
                $user = Admin::find($user_id);
            }else{
                $user = User::find($user_id);
            }
            if (empty($user)) return null;
            return $user;
        }
        Log::info("授权解析后的无用户id");
        return null;
    }

    public function apiJwtToken($user)
    {
        if (!$user->expire_at || $user->expire_at < date('Y-m-d H:i:s') || empty($user->api_token)){
            $carbon_expire_at = Carbon::now()->addDays(30);
            $expire_at = $carbon_expire_at->toDateTimeString();
            $api_token = $this->createJwtToken($user, $expire_at);
            $user::class::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
            $user->api_token = $api_token;
            return $api_token;
        }else {
            try {
                $res = $this->checkJwtToken($user->api_token);
                if (!$res) {
                    $api_token = $this->refreshApiJwtToken($user);
                    return $api_token;
                }
            }catch (\Exception $e) {
                $api_token = $this->refreshApiJwtToken($user);
                return $api_token;

            }
        }
        return $user->api_token;
    }

    public function refreshApiJwtToken($user)
    {
        $carbon_expire_at = Carbon::now()->addDays(30);
        $expire_at = $carbon_expire_at->toDateTimeString();
        $api_token = $this->createJwtToken($user, $expire_at);
        $user::class::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
        return $api_token;
    }

    public function createJwtToken($user, $expire_at)
    {
        $arr =  [
            "CreatedAt"=>time(),
            "ExpiredAt"=>strtotime($expire_at),
            "Version"=>100,
            "Userid"=>$user->id,
            "exp"=>time() + 10000 * 24 * 3600,
        ];
        $token = JWT::encode($arr, config("jwt.secret"),config('jwt.algorithm'));
        return $token;
    }

}
