<?php
/**
 * Created by PhpStorm
 * User：林志杰
 * Email：598287049@qq.com
 * Motto：纵有疾风起，人生不言弃！
 * Time：2020/1/10 20:46
 */

namespace app\admin\business;

use app\common\model\mysql\AdminUser as AdminUserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class AdminUser
{
    public static function login($data)
    {
        $adminUser = self::getAdminUserByUsername($data['username']);
        if (empty($adminUser)) {
            throw new Exception('不存在该用户');
        }
        // 判断密码是否正确
        if ($adminUser['password'] !== md5($data['password'] . '_singwa_abc')) {
            throw new Exception('密码错误');
            // return show(config('status.error'), '密码错误');
        }

        $adminUserObj = new AdminUserModel();
        // 记录信息到mysql中
        $updateData = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'update_time' => time(),
        ];
        $res = $adminUserObj->updateById($adminUser['id'], $updateData);
        if (empty($res)) {
            throw new Exception('登陆失败');
            // return show(config('status.error'), '登陆失败');
        }
        // 记录session
        session(config('admin.session_admin'), $adminUser);
        return true;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAdminUserByUsername($username)
    {
        $adminUserObj = new AdminUserModel();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);

        if (empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')) {
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}