<?php

namespace App\Http\Middleware;

use App\Consts\ErrorConst;
use App\Libs\Utils;
use App\Models\Channel\Channel;
use App\Models\Channel\ChannelUser;

trait CheckTokenTrait
{
    public function checkTokenTrait($token, $channelId)
    {
        // 获取用户信息
        $user = ChannelUser::where('token', $token)->first();
        $uid  = (int)getProp($user, 'id');
        if (!$uid) {
            Utils::throwError(ErrorConst::NOT_LOGIN);
        }

        // 将数据绑定到全局
        $site           = app('siteData');
        $site->uid      = $uid;
        $site->account  = getProp($user, 'account');
        $site->phone    = getProp($user, 'phone');
        $site->nickname = getProp($user, 'nickname');
        $site->token    = $token;

        // 获取当前站点id
        $channel       = Channel::getById($channelId);
        $channelUserId = (int)getProp($channel, 'channel_user_id');

        // 判断站点权限
        if ($uid != $channelUserId) {
            Utils::throwError(ErrorConst::USER_NO_ACCESS_CHANNEL);
        }

        $site->current_channel_id   = $channelId;
        $site->current_channel_name = getProp($channel, 'name');
    }
}