<?php

namespace App\Http\Controllers\Api\Client;

use App\Exceptions\ControllerException;
use App\Exceptions\DatabaseException;
use App\Model\LogModel;
use App\Model\MediaCategoryModel;
use App\Model\MediaModel;
use App\Model\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\UTCDateTime;

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

            return UserModel::checkUserRole($request);

        });

        return success($response);

    }

    /**
     * 获取用户业务信息
     * @param $request
     * @param $params
     * @return mixed
     * @throws ControllerException
     */
    private function getUserPrivilege($request,$params){

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

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

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

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

        if (empty($tmp)){
            LogModel::addlog(["暂无业务权限，请联系管理员",$request->all()]);
            throw new ControllerException('暂无业务权限，请联系管理员',403);
        }

        return $tmp;
    }


    /**
     *  生成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;
    }
}
