<?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){
                        /**
                         * 获取mis用户信息
                         */
                        $request->replace(array_merge($request->all(),['mis_uid'=>'000000']));

                        $url = getRbac($request,"api/mis/userinfo",'','mis_user');

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

                        $userInfo = json_decode($result,true);


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

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


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


                    }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;
                }else{
                    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)
    {
        Auth::logout();
        $request->session()->flush();
        return Redirect('/web/login');

    }
}