<?php

namespace App\Http\Middleware;

use App\Exceptions\ControllerException;
use App\Exceptions\DatabaseException;
use App\Model\LogModel;
use App\Model\MediaCategoryModel;
use App\Model\UserModel;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class ApiMiddleware
{
    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\RedirectResponse|mixed
     * @throws \Exception
     */
    public function handle($request, Closure $next)
    {
        $url = $request->path();

        $except_url = [
            'web/login',
            'web/logout',
        ];

        if (in_array($url,$except_url)){
            return $next($request);
        }

        $ajax = $request->ajax();
        $user = Auth::user();

        if (empty($user)){
            if ($ajax){
                return error(Response::HTTP_UNAUTHORIZED);
            }
            return Redirect::to("web/logout");
        }


        if ($request->category_id){
            $mediaCatg = MediaCategoryModel::where("_id",$request->category_id)->first();
            if (empty($mediaCatg)){
                return error("类别不存在");
            }
            $request->replace(array_merge($request->all(),['catetory_name'=>$mediaCatg->name]));
        }


        if ($user->mis_uid){
            $request->replace(array_merge($request->all(),[
                'mis_uid'=>$user->mis_uid,
            ]));
        }else{

            $username = $user->name;
            $staffNo = substr($username,strrpos($username,"-"));
            $request->replace(array_merge($request->all(),["staffNo"=>$staffNo]));


            /**
             * 获取mis用户信息
             */
            $userInfo = UserModel::getMisInfo($request);

            $userid = $userInfo['userId'];

            $flag = UserModel::where("_id",$user->_id)->update(['mis_uid'=>$userid]);
            if (!$flag){
                LogModel::addlog(['更新用户mis_uid失败'=>json_encode(['mis_uid'=>$userid])]);
                return error("更新用户mis_uid失败");
            }

            $request->replace(array_merge($request->all(),['mis_uid'=>$user->mis_uid]));

        }

        return $next($request);
    }
}
