<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\adminapi\logic\auth;

use app\common\cache\AdminAuthCache;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\Admin;
use app\common\model\AdminSession;
use app\common\cache\AdminTokenCache;
use app\common\service\FileService;
use think\Exception;
use think\facade\Config;
use think\facade\Db;

class AdminLogic extends BaseLogic
{
    /**
     * @notes 添加管理员
     * @param $params
     */
    public static function add($params)
    {
        $time = time();
        $passwordSalt = Config::get('project.unique_identification');
        $password = create_password($params['password'], $passwordSalt);
        $avatar = isset($params['avatar']) && !empty($params['avatar']) ? FileService::setFileUrl($params['avatar']) : config('project.default_image.admin_avatar');
        $data = [
            'name' => $params['name'],
            'account' => $params['account'],
            'avatar' => $avatar,
            'password' => $password,
            'role_id' => $params['role_id'],
            'create_time' => $time,
            'disable' => $params['disable'],
            'multipoint_login' => $params['multipoint_login'],
        ];

        Admin::create($data);
    }

    /**
     * @notes 编辑管理员
     * @param $params
     * @return bool
     */
    public static function edit($params)
    {
        Db::startTrans();
        try {
            // admin账号不允许被禁用
            if ($params['account'] == 'admin' && $params['disable'] == YesNoEnum::YES) {
                throw new \Exception("超级管理员不允许被禁用");
            }
            $avatar = isset($params['avatar']) && !empty($params['avatar']) ? FileService::setFileUrl($params['avatar']) : '';
            $admin = Admin::find($params['id']);
            $roleId = $params['role_id'];
            //超级管理员不允许修改菜单权限
            if(1 == $admin['root']){
                $roleId = $admin['role_id'];
            }
            $data = [
                'id' => $params['id'],
                'name' => $params['name'],
                'account' => $params['account'],
                'role_id' => $roleId,
                'disable' => $params['disable'],
                'avatar' => $avatar,
                'multipoint_login' => $params['multipoint_login']
            ];

            if (!empty($params['password'])) {
                $passwordSalt = Config::get('project.unique_identification');
                $data['password'] = create_password($params['password'], $passwordSalt);
            }

            $role_id = Admin::where('id', $params['id'])->value('role_id');
            if ($params['disable'] == 1 || $role_id != $params['role_id']) {
                // 禁用或更换角色后，让之前登录的token都过期(无论是否支持多处登录)
                $tokenArr = AdminSession::where('admin_id', $params['id'])->select()->toArray();
                foreach ($tokenArr as $token) {
                    self::expireToken($token['token']);
                }
            }
            // dd($data);
            Admin::update($data);
            (new AdminAuthCache($params['id']))->clearAuthCache();


            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 删除管理员
     * @param $params
     * @return bool
     */
    public static function delete($params)
    {
        Db::startTrans();
        try {
            $admin = Admin::findOrEmpty($params['id']);
            if ($admin->root == YesNoEnum::YES) {
                throw new \Exception("超级管理员不允许被删除");
            }
            Admin::destroy($params['id']);

            // 删除后，让之前登录的token都过期(无论是否支持多处登录)
            $tokenArr = AdminSession::where('admin_id', $params['id'])->select()->toArray();
            foreach ($tokenArr as $token) {
                self::expireToken($token['token']);
            }
            (new AdminAuthCache($params['id']))->clearAuthCache();
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * @notes 将token变为无效
     * @param $token
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function expireToken($token)
    {
        $adminSession = AdminSession::where('token', '=', $token)
            ->with('admin')
            ->find();

        if (empty($adminSession)) {
            return false;
        }

        $time = time();
        $adminSession->expire_time = $time;
        $adminSession->update_time = $time;
        $adminSession->save();

        (new  AdminTokenCache())->deleteAdminInfo($token);
    }

    /**
     * @notes 查看管理员详情
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($params)
    {
        return Admin::field('account,root,name,role_id,disable,multipoint_login,avatar')->find($params['id'])->toArray();
    }

    /**
     * @notes 获取管理员基本信息
     * @param $params
     * @return Admin
     * @author lgp
     * @date 2022/4/21 15:05
     */
    public static function getAdminInfo($adminIid){
        return Admin::field('id,name,avatar')->find($adminIid)->toArray();
    }

    /**
     * @notes 修改管理员密码
     * @param $params
     * @param $adminId
     * @return bool|string
     * @author lgp
     * @date 2022/4/21 15:16
     */
    public static function resetPassword($params,$adminId){
        try{

            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password($params['password'], $passwordSalt);
            Admin::update(['password'=>$password],['id'=>$adminId]);
            return true;

        }catch (Exception $e) {
            return $e->getMessage();
        }
    }
}