<?php
/**
 * Created by PhpStorm.
 * User: yangx
 * Date: 2020/6/23
 * Time: 下午12:19
 */

namespace App\Http\Controllers\Web;


use App\Exceptions\ControllerException;
use App\Exceptions\DatabaseException;
use App\Http\Controllers\Controller;


use App\Model\LogModel;
use App\Model\MediaCategoryModel;
use App\Model\MediaModel;
use App\Model\UserModel;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function login(Request $request)
    {
        if (request()->isMethod('post')) {

            $user = handler_drive(function () use($request){


                if (!$request->password) {
                    throw new ControllerException(400, '口令不能为空');
                }
                if (!$request->username) {
                    throw new ControllerException(400, '昵称必须填写');
                }

                /**
                 * 用户名称是有四部分组成，姓名-新账号-旧账号-mis_uid
                 */
                $user = UserModel::where('name', 'regexp', '/^.*?'.$request->username.'/')->first();


                if (!empty($user)){

                    if (md5($request->password) != $user->password ){
                        throw new \Exception('用户名或者密码有误');
                    }

                    if (!$user->mis_uid){

                        $staffNo = $request->username;
                        $url = 'http://api-mis.offcn.com/index.php/applogin/isworking';
                        $data = sign($staffNo);
                        $data['type'] = 6;
                        $data['username'] = $staffNo;

                        $result = http_request_code($url,
                            null,
                            'POST',
                            $data
                        );

                        $userInfo = json_decode($result,true);

                        if (!isset($userInfo['data'])){
                            LogModel::addlog(["获取用户信息失败",$request->all(),'userInfo'=>$userInfo,'data'=>$data]);
                            throw new \Exception("获取用户信息失败");
                        }

                        $userid = $userInfo['data']['userid'];
                        $mis_uid = $userid;

                    }else{
                        $mis_uid = $user->mis_uid;
                    }


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

                    $catgList = MediaCategoryModel::get()->toArray();

                    $tmp = [];
                    foreach ($catgList as $key => $catg){

                        $request->replace(array_merge($request->all(),['category_id'=>$catg['media_category_id']]));

                        $url = getRbac($request,'api/open/check',$catg['media_category_id']);

                        $data['appid'] = $catg['media_category_id'];
                        $data['uid'] = $request->mis_uid;
                        $data['tree'] = 1;

                        $result = http_request_code($url,
                            null,
                            'GET',
                            $data
                        );

                        $privilege = json_decode($result,true);

                        if (!empty($privilege['data'])){
                            array_push($tmp,$catg);
                        }

                    }

                    if (empty($tmp)){
                        LogModel::addlog(["暂无业务权限，请联系管理员",$request->all()]);
                        throw new \Exception("暂无业务权限，请联系管理员");
                    }

                    Auth::login($user);

                    return $user;
                }

                throw new \Exception('用户验证失败');

            });

            return success($user);

        } else {
            return view('admin.login');
        }
    }

    /**
     * 退出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        Session::remove('user');
        return Redirect('/web/login');

    }
}