<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use MongoDB\BSON\UTCDateTime;

class UserModel extends Authenticatable
{
    /**
     * mongodb collection 名字
     */
    protected $collection = 'users';

    protected $connection = 'mongodb';  //使用mongodb

    protected $primaryKey = '_id';


    use Notifiable;


    protected $fillable = [
        'name',  'password',
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];

    /*
     * 获取用户列表
     */
    public static function getUserList($request){


        try{
            $where = [];

            if ($request->name){
                $where['name'] = $request->name;
            }

            $users = DB::connection('mongodb')->collection('users')->where($where)
                ->paginate(10);



//            foreach ( $users as $user){
//                $idArr = ($user['_id'])->jsonSerialize();
//                $user['_id'] = $idArr['$oid'];
//            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }

        return $users;
    }

    /**
     * 更新用户状态
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function updateUserStatus($request){

        $id = $request->id;

        try{
            $user = UserModel::find($id);
            if (empty($user)){
                throw new \Exception('用户不存在');
            }
            $isshow=$user->status==1?0:1;
            $flag = UserModel::where('_id',$id)->update(['status'=>$isshow]);
            if (!$flag){
                throw new \Exception("更新失败");
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $flag;
    }

    /**
     * 获取用户基本信息
     * @param $id
     * @return mixed
     * @throws DatabaseException
     */
    public static function getUserInfoById($id){
        try{
            $user = DB::connection("mongodb")->collection("users")->find($id);

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $user;
    }

    /**
     * 更新用户信息
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function createOrUpdateUser($request){

        $id = $request->id;

        try{
            $user = UserModel::find($id);
            if (empty($user)){
                throw new \Exception('用户不存在');
            }

            $flag = UserModel::where('_id',$id)->update(array_merge([
                'status'    => $request->status? 1 :0,
            ],$request->all()));

            if (!$flag){
                throw new \Exception("更新失败");
            }
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $flag;
    }

    /**
     * 根据id删除用户
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public static function deleteUserById($id){
        try{
            $user = UserModel::find($id);

            if (empty($user)){
                throw new \Exception('用户不存在');
            }
            $flag = UserModel::where('_id',$id)->delete();

            RecycleModel::addRecycle($id,"users");

        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage());
        }
        return $flag;

    }

    /**
     * 添加用户
     * @param $request
     * @return mixed
     * @throws DatabaseException
     */
    public static function createUser($request){

        try{
            $user = UserModel::where("name",$request->name)->first();
            if (!empty($user)){
                throw new \Exception("用户已存在");
            }

            $data = [
                'name'      => $request->name,
                'password'  => md5($request->password),
                'organization_id'   => 0,
                'status'    => 0,
                'create_time' => date('Y-m-d H:i:s',time()),
                'user_type' => 1
            ];

            $idArr = UserModel::insertGetId($data);
            if (empty($idArr)){
                throw new \Exception("添加用户失败");
            }

            $_id = $idArr['$oid'];
            $token = generateRandomNum();
            $newtoken = encrypt($_id.'|'.$token."|1ZGHd3pCc87AsQFBLLJeMjM4t57cli6Ar78qowe7");
            $data['token'] = $newtoken;


            $flag = UserModel::where("_id",$_id)->update($data);


            if (!$flag){
                throw new \Exception("用户添加失败");
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $flag;
    }

    /**
     * 检测用户权限信息
     * @param $request
     * @throws DatabaseException
     */
    public static function checkUserRole($request){

        try{

            $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用户基本信息
                 */
//                $staffNo = $username;
//                $url = 'http://api-mis.offcn.com/index.php/applogin/isworking';
//                $data = sign($staffNo);
//                $data['type'] = 6;
//                $data['username'] = $staffNo;

                $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 (empty($userInfo['data'])){
                    LogModel::addlog(["获取用户信息失败",$request->all()]);
                    throw new \Exception("获取用户信息失败");
                }

                $userInfo = $userInfo['data'];

                $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($result)]);
                        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{

                //$result = self::getUserPrivilege($request,['mis_uid'=>$user->mis_uid]);

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

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


                $_id = $user->_id;
                $userid = $user->mis_uid;

            }

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


            $token = generateRandomNum();

            $tmp['token'] = $newtoken = encrypt($userid."|".$token."|1ZGHd3pCc87AsQFBLLJeMjM4t57cli6Ar78qowe7");

            $flag = DB::connection('mongodb')->collection('users')->where('_id',$_id)->update($tmp);

            if (!$flag){
                throw new DatabaseException('用户名信息更新失败');
            }

            $tmp['categories'] = $result;


        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }

        return $tmp;


    }

    /**
     * 获取用户业务信息
     * @param $request
     * @param $params
     * @return array
     * @throws DatabaseException
     */
    public static function getUserPrivilege($request,$params){

        try{

            $request->replace(array_merge($request->all(),$params));

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

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

                $request->replace(array_merge($request->all(),['appid'=>$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);
                }

            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }

        return $tmp;
    }

    /**
     * 获取mis系统用户信息
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public static function getMisInfo($request){

        try{

            /**
             * 获取mis用户基本信息
             */
            /*$staffNo = $username; //工号
            $url = 'http://api-mis.offcn.com/index.php/applogin/isworking';
            $data = sign($staffNo);
            $data['type'] = 6;
            $data['username'] = $staffNo;*/

            $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 (empty($userInfo['data']['userId'])){
                LogModel::addlog(["用户不存在",$request->all()]);
                throw new \Exception("用户不存在");
            }

            $userInfo = $userInfo['data'];

        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage());
        }

        return $userInfo;
    }

}
