<?php

namespace App\Http\Controllers\Api\Client;

use App\Exceptions\ControllerException;
use App\Exceptions\DatabaseException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UsersController extends Controller
{
    /**
     * 第三方验权
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ControllerException
     */
    public function store(Request $request){


        $response = handler_drive(function () use ($request) {


            if (!$request->password) {
                throw new ControllerException('口令不能为空',400);
            }
            if ($request->filled('username')) {
                if (mb_strlen($request->username)>=20) {
                    $request->username = mb_substr($request->username,0,20,"UTF-8").'...';
                }
            } else {
                throw new ControllerException('昵称必须填写',400);
            }


            if (preg_match("['|\"|\/|\\\|\.|:]", $request->uuid)) {
                throw new ControllerException('uuid含有非法字符',400);
            }
            $password = strtolower($request->password);
            $username = $request->username;

            /**
             * 用户为offcn，不走第三方认证
             */
            if ($username == 'offcn'){

                $user = DB::connection('mongodb')       //选择使用mongodb
                ->collection('users')->where('name',$username)->first();


                if (empty($user)){
                    $data = [
                        'name'      => $username,
                        'password'  => md5(123123),
                        'organization_id'   => 0,
                        'status'    => 0,
                        'create_time' => date('Y-m-d H:i:s',time()),
                        'user_type' => 1
                    ];
                    $id = DB::connection("mongodb")->collection("users")->insertGetId($data);

                    if (!$id){
                        $result = false;
                    }else{
                        $result = true;
                    }

                }else{

                    if ($user['password'] == md5($password)){
                        $result = true;
                    }else{
                        $result = false;
                    }
                }

            }else{

                $url = "http://test-live.offcncloud.com/api/login";
                $result = http_request_code($url,
                    ['Content-Type'=>'application/x-www-form-urlencoded'],
                    'POST',
                    ['username' => $username,'password' => $password],
                    200
                );
                $result = json_decode($result,true);
                if ($result['code']!=200){
                    $result = false;
                }
            }

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

                $user = DB::connection('mongodb')       //选择使用mongodb
                ->collection('users')->where('name',$username)->first();
                $token = $this->generateToken();

                if ($user){
                    $idArr = ($user['_id'])->jsonSerialize();
                }else{
                    $id = DB::connection("mongodb")->collection("users")->insertGetId($data);

                    if (!$id){
                        throw new DatabaseException('用户存储失败');
                    }

                    $idArr = ($id)->jsonSerialize();
                }

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

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

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

                return $newtoken;

            }else{
                throw new DatabaseException('用户名称或者密码错误');
            }

        });

        return success($response);

    }


    /**
     *  生成UUID标识并检测UUID是否重复
     */
    private function generateToken( $len = 32, $md5 = true ) {
        # Seed random number generator
        # Only needed for PHP versions prior to 4.2
        mt_srand( (double)microtime()*1000000 );
        # Array of characters, adjust as desired
        $chars = array(
            'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
            'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
            '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
            'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
            '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
            '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
            'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
        );
        # Array indice friendly number of chars;
        $numChars = count($chars) - 1; $token = '';
        # Create random token at the specified length
        for ( $i=0; $i<$len; $i++ )
            $token .= $chars[ mt_rand(0, $numChars) ];
        # Should token be run through md5?
        if ( $md5 ) {
            # Number of 32 char chunks
            $chunks = ceil( strlen($token) / 32 ); $md5token = '';
            # Run each chunk through md5
            for ( $i=1; $i<=$chunks; $i++ )
                $md5token .= md5( substr($token, $i * 32 - 32, 32) );
            # Trim the token
            $token = substr($md5token, 0, $len);
        }
        return $token;
    }
}
