<?php

namespace App\Http\Middleware;

use App\Http\Response\ResponseJson;
use App\Models\ServiceUser;
use Closure;
use Illuminate\Http\Request;

class CheckBindServiceUser
{
    use ResponseJson;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //有token则验证token
        $user = auth()->user();
        if($user) {
            //服务人员信息
            $servicer = ServiceUser::where('user_id', $user->id)->first();
        }else{
            $wechat_user = session('work_wechat_user');
            if (empty($wechat_user)) return $this->failure("未授权企业微信");
            $work_user_id = $wechat_user['raw']['userid'];
            $servicer = ServiceUser::where('work_user_id', $work_user_id)->first();
        }
        if (empty($servicer)) return $this->failure("企业微信未绑定服务人员");
        return $next($request);
    }
}
