<?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
     * @throws ControllerException
     */
    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, '昵称必须填写');
                }

                $len = strlen($request->username);
                if ($len < 5){
                    throw new \Exception('用户名称长度不能小于5个字符');
                }

                /**
                 * 用户名称是有三部分组成，姓名-新账号-旧账号
                 * user用户名称有两种类型的账号，早期账号用户名称只有员工旧账户，二期项目用户名称由三部分组成
                 **/
                $user = UserModel::where('name', 'regexp', '/^.*?'.$request->username.'/')->first();

                if (!empty($user)){
                    //1.处理二期之后新用户名称
                    $temp = explode("-",$user["name"]);
                    if (count($temp)>1){
                        if (!in_array($request->username,array_slice($temp,1))){
                            throw new \Exception("用户名或者密码有误");
                        }
                    }else{
                        if ($request->username != $user->name){
                            throw new \Exception("用户名或者密码有误");
                        }
                    }

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

                    //为了媒资新旧账号统一，需要以员工mis编号作为用户唯一标识符
                    if (!$user->mis_uid){
                        $request->replace(array_merge($request->all(),["staffNo"=>$request->username]));

                        #获取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{

                    //新用户第一次登录，直接往媒资注册
                    $request->replace(array_merge($request->all(),["staffNo"=>$request->username]));
                    $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');

    }
}