<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use http\Env\Request;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

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

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

    protected $primaryKey = '_id';

    /*
     * 获取用户列表
     */
    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();

        }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;
    }


}
