<?php

namespace App\Modules\Admin\Services;

use App\Base\BaseService;
use App\Exceptions\ClientException;
use App\Models\Cart;
use App\Models\User\User;
use App\Models\User\UserFav;
use Illuminate\Support\Facades\Auth;

class AuthService extends BaseService
{
    public function login($data)
    {
        $u = User::wherePhone($data['username'])->orWhere("email", $data['username'])->first();
        if (is_null($u)) {
            throw new ClientException("账号或密码错误,请重新输入");
        }
        if (!$u->checkPassword($data['password'])) {
            throw new ClientException("账号或密码错误,请重新输入!");
        }

        if ($u->status != User::STATUS_OK) {
            throw new ClientException("当前用户被禁用,请联系管理员");
        }

        if (!$u->group_id) {
            throw new ClientException("无权限");
        }

        return [
            "admin_token" => $this->encryptToken($u->id),
        ];
    }

    public function profile()
    {
        $u = Auth::user();
        return [
            "id" => $u->id,
            "phone" => $u->phone,
            "email" => $u->email,
            "group" => $u->group->name,
        ];
    }

    public function changePassword($data)
    {
        $u = Auth::user();
        if (!$u->checkPassword($data['old_password'])) {
            throw  new ClientException("原密码错误");
        }

        $u->password = $u->hashPassword($data['password']);
        $u->save();

        return true;
    }

    public function encryptToken($uid)
    {
        return md5($uid) . $uid;
    }

    public function decryptToken($token)
    {
        return substr($token, 32);
    }
}