<?php

namespace App\Services\Account;

use App\Consts\ErrorConst;
use App\Facade\Site;
use App\Libs\AliSMS;
use App\Libs\Utils;
use Illuminate\Support\Facades\DB;
use OSS\Core\OssException;
use OSS\OssClient;

class AccountService
{
    private $salt = 'bXBfYXVkaW8=';
    public function __construct() {}

    /**
     * @param $account
     * @param $passwd
     * @return array
     */
    public function login($account, $passwd): array
    {
        // 密码
        $pwd = md5($passwd . $this->salt);

        $user = DB::table('mp_manage_users')->where('account', $account)->where('pwd', $pwd)->first();
        if (!$user) {
            Utils::throwError('20003:用户不存在');
        }
        if ((int)getProp($user, 'is_enabled') === 0) {
            Utils::throwError('20003:用户已被禁用');
        }

        // 更新token
        $uid      = getProp($user, 'id');
        $nickname = getProp($user, 'nickname');
        $token    = getProp($user, 'token');
        if (empty($token)) {
            $token = md5(makeRandStr(32));
            DB::table('mp_manage_users')->where('id', $uid)->update([
                'token'      => $token,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }

        // 用户角色
        $role = getProp($user, 'role');
        return compact('uid', 'nickname', 'token', 'role');

    }

    /**
     * 退出登录
     *
     * @param $token
     * @return bool
     */
    public function logout($token): bool
    {
        if (empty($token)) {
            return true;
        }

        // 退出不影响多设备
        return DB::table('mp_manage_users')->where('token', $token)->update([
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }

}
