<?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;
use MongoDB\BSON\UTCDateTime;

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用户信息
                         */
                        $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])]);
                            throw new \Exception("更新用户mis_uid失败");
                        }

                    }


                }else{

                    $userInfo = UserModel::getMisInfo($request);
                    $mis_uid = $userInfo["userId"];

                    $shops = UserModel::getUserPrivilege($request,['mis_uid'=>$mis_uid]);

                    if (empty($shops)){
                        LogModel::addlog(["用户不存在业务线，请联系管理员","params"=>$request->all()]);
                        throw new \Exception("用户不存在业务线，请联系管理员");
                    }

                    $data_arr = [
                        'name'      => $userInfo['nickName'],
                        'password'  => md5($request->password),
                        'organization_id'   => 0,
                        'status'    => 0,
                        'mis_uid'        => $mis_uid,
                        'user_type' => 0,
                        'create_time' => new UTCDateTime(time() * 1000),
                    ];

                    $_id = UserModel::insertGetId($data_arr);
                    if (!$_id){
                        LogModel::addlog(['添加用户失败'=>json_decode($data_arr)]);
                        throw new \Exception("添加用户失败");
                    }
                    $user = UserModel::where("_id",$_id)->first();

                }

                Auth::login($user);
                return $user;

            });

            return success($user);

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

    private function getUserInfo($request){

        $password = strtolower($request->password);
        $username = $request->username;

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


        if (empty($user)|| !isset($user['mis_uid'])){
            /**
             * 获取mis用户基本信息
             */

            $userInfo = UserModel::getMisInfo($request);

            $userid = $userInfo['userId'];
            //$result = self::getUserPrivilege($request,['mis_uid'=>$userid]);


            if (empty($user)){


                //杨帆-yf18512-yf60144-8086
                $data_arr = [
                    'name'          => $userInfo['nickName'],
                    'password'      => md5($password),
                    'organization_id'=> 0,
                    'status'        => 0,
                    'mis_uid'       => $userid,
                    'user_type'     => 0,
                    'create_time'   => new UTCDateTime(time() * 1000),
                ];


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

        }else{

            if ($user['password'] != md5($password)){
                throw new \Exception("用户名称或者密码错误");
            }

            if ($user['status']){
                throw new \Exception("用户已被限制，请联系管理员");
            }

            $_id = $user->_id;

        }

        return  UserModel::where("_id",$_id)->first();

    }

    /**
     * 退出
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->flush();
        return Redirect('/web/login');

    }
}