<?php

namespace App\Http\Middleware;

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

class CheckWorkWechat
{
    /**
     * 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)
    {
        //微信信息
        if (config('app.env') == 'production') {
            $service_user_id = $request->input('service_user_id');
            if($service_user_id){
                $service_user = ServiceUser::where('user_id',$service_user_id)->first();
            }else{
                //有token则验证token
                $user = auth()->user();
                if($user){
                    //服务人员信息
                    $service_user = ServiceUser::where('user_id', $user->id)->first();
                }else{
                    $work_wechat_user = session('work_wechat_user');
                    if (empty($work_wechat_user)) throw new \Exception("未授权企业微信");
                    //用户企业微信信息
                    $work_wechat_user = session('work_wechat_user');
                    $work_user_id = $work_wechat_user['raw']['userid'];
                    //服务人员信息
                    $service_user = ServiceUser::where('work_user_id', $work_user_id)->first();
                }
            }
        }else {
            $work_wechat_user = ['id'=>'hankin','name'=>"Hankin", 'raw'=>[
                'userid'=>'hankin',
            ]];
            session(['work_wechat_user'=>$work_wechat_user]);
            $service_user = ServiceUser::where('work_user_id', "hankin")->first();
        }
        $request->service_user = $service_user;
        return $next($request);
    }
}
