<?php

use App\AdminConfig;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;
use App\Http\helper\NumConfig;

function validateURL($URL)
{
    $pattern = "/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/";
    if (preg_match($pattern, $URL)) {
        return true;
    } else {
        return false;
    }
}

/**
 * @Desc: 获取配置值
 * @Author: woann <304550409@qq.com>
 * @param $key
 * @return array
 */
function getConfig($key)
{
    return AdminConfig::getValue($key);
}

//导出Excel
function downloadExcel($cellData, $title, $name)
{
    array_unshift($cellData, $title);
    Excel::create($name, function ($excel) use ($cellData) {
        $excel->sheet('score', function ($sheet) use ($cellData) {
            $sheet->rows($cellData);
            $sheet->setWidth(array('A' => 15, 'B' => 15, 'C' => 15, 'D' => 15, 'E' => 15, 'F' => 15, 'G' => 15, 'H' => 15, 'I' => 15, 'J' => 15, 'K' => 15, 'L' => 15, 'M' => 15, 'N' => 15, 'O' => 15, 'P' => 15, 'Q' => 15));
        });
    })->export('xls');
}

// 失败返回数据
function apiReturnFail($msg = '', $data = [], $code = 301)
{
    if(is_array($msg)){
        if(empty($data))$data=array_slice($msg,0,count($msg));
        $tryLang=__($msg[0]);
        if($tryLang!=$msg[0]){
            $msg=$tryLang;
        }else{
//            $msg=$msg[1];
        }
    }
    $data = ['data' => $data, 'msg' => $msg, 'code' => $code];
    return $data;
}

// 成功返回数据
function apiReturnSuc($data = [], $result = '', $msg = 'success', $code = 200)
{
    $data = ['data' => $data, 'result' => $result, 'msg' => $msg, 'code' => $code];
    return $data;
}

function number_float($val = null, $decimals = 2)
{
    return number_format($val, $decimals, '.', '');
}

// 返回角色类型
function hidden($value = 'hidden')
{
    $hidden = session($value)['is_hidden'] ?? '';
    return $hidden;
}

// 判断值在不在数组里面
function exist_array($need, $data)
{
    if (in_array($need, $data)) {
        return true;
    } else {
        return false;
    }

}

function getGameID($UserID, $InvitationUserIDs)
{
    $GameIDArr = explode(',', $InvitationUserIDs);

    $GameIDs = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
        ->whereIn('UserID', $GameIDArr)
        ->select('GameID', 'UserID')
        ->pluck('GameID', 'UserID')->toArray();

    $str = '';
    foreach ($GameIDs as $k => $val) {
        $str .= "<a href='/admin/global/id_find?UserID={$k}'>{$val},</a>";
    }
    return $str;
    return implode(',', $GameIDs);
}

// 裂变 -- 获取用户的充值 - 提现 -对局
function getUserInfo($InvitationUserIDs)
{
    $GameIDArr = explode(',', $InvitationUserIDs);

    $info = DB::connection('read')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
        ->whereIn('UserID', $GameIDArr)
        ->selectRaw('IsNull(sum(WinInning+LostInning),0) gameNum,IsNull(sum(Withdraw) / 100,0)Withdraw,IsNull(sum(Recharge),0) Recharge')
        ->first();
    return $info;
}

function CollectableScore($UserID, $Type = 1)
{
    // 注册
    $upperLimit = $info = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
        ->where('StatusName', 'UpperLimit')
        ->first();

    // 1.判断可领额度
    $StatusValue = $upperLimit->StatusValue;

    $Score = (new \App\Services\Extension())->register($UserID, $Type)['Register'];

    // 剩余额度
    $Surplus = $Score % $StatusValue;

    // 要提的额度
    $addScore = $Score - $Surplus;

    return number_float($addScore / NumConfig::NUM_VALUE);
}

// 排序Html
function sortHtml($func)
{
    return "<svg t=\"1611284352657\" class=\"icon2\" onclick=\"$func(this,'asc')\"
                                                 viewBox=\"0 0 1024 1024\" version=\"1.1\"
                                                 xmlns=\"http://www.w3.org/2000/svg\" p-id=\"4118\" width=\"14\">
                                                <path
                                                    d=\"M541.866667 285.866667l345.6 345.6c17.066667 17.066667 17.066667 42.666667 0 59.733333-8.533333 8.533333-19.2 12.8-29.866667 12.8H168.533333c-23.466667 0-42.666667-19.2-42.666666-42.666667 0-10.666667 4.266667-21.333333 12.8-29.866666l343.466666-345.6c17.066667-17.066667 42.666667-17.066667 59.733334 0z\"
                                                    p-id=\"4119\" fill=\"#707072\">

                                                </path>
                                            </svg>

                                            <svg t=\"1611283709864\" class=\"icon1\" onclick=\"$func(this,'desc')\"
                                                 viewBox=\"0 0 1024 1024\" version=\"1.1\"
                                                 xmlns=\"http://www.w3.org/2000/svg\" p-id=\"3148\" width=\"14\">
                                                <path
                                                    d=\"M482.133333 738.133333L136.533333 392.533333c-17.066667-17.066667-17.066667-42.666667 0-59.733333 8.533333-8.533333 19.2-12.8 29.866667-12.8h689.066667c23.466667 0 42.666667 19.2 42.666666 42.666667 0 10.666667-4.266667 21.333333-12.8 29.866666L541.866667 738.133333c-17.066667 17.066667-42.666667 17.066667-59.733334 0z\"
                                                    p-id=\"3149\" fill=\"#707071\">

                                                </path>
                                            </svg>";
}

// 房间搜索
function gamesButton($url = '/admin/group_control/room')
{
    $ControlModel = new \App\Models\Control();

    $GameData = $ControlModel->GameData;
    foreach ($GameData as $key => $val) {

        if (in_array($val, config('games.openKGame'))) {
            $href = $url . '?gameType=' . $val;
            $gameName = $ControlModel->GameDataText[$key];
            echo '<a href="' . $href . '" class="btn-sm btn btn-gradient-dark">' . $gameName . '</a> &nbsp;';
        }
    }
}

// 日期转换北京时间
function dateConvert($date)
{
    return \Carbon\Carbon::parse($date,env('APP_TIMEZONE','America/Argentina/Buenos_Aires'))->setTimezone('Asia/Shanghai');
}


function ipAddress($ip){
    return \App\IpLocation::getAddressByIP($ip);
}

function opensslVerify( $pubkey, $data, $sign, $signType = 'RSA' ) {
    $res = "-----BEGIN PUBLIC KEY-----\n" . wordwrap( $pubkey, 64, "\n", true ) . "\n-----END PUBLIC KEY-----";
    if ( "RSA2" == $signType ) {
        $result = (bool)openssl_verify( $data, base64_decode( $sign ), $res, OPENSSL_ALGO_SHA256 );
    } else {
        $result = (bool)openssl_verify( $data, base64_decode( $sign ), $res );
    }


//    $public_key = '-----BEGIN PUBLIC KEY-----'."\n".$public_key."\n".'-----END PUBLIC KEY-----';
//    $data = base64_decode($data);
//    $pu_key =  openssl_pkey_get_public($public_key);
//    $crypto = '';
//    foreach (str_split($data, 128) as $chunk) {
//        openssl_public_decrypt($chunk, $decryptData, $pu_key);
//        $crypto .= $decryptData;
//    }
//
//    return $crypto;


    return $result;
}

function opensslSign( $prikey, $data, $signType = "RSA" ) {
//    $res = "-----BEGIN PRIVATE KEY-----\n" . wordwrap( $prikey, 64, "\n", true ) . "\n-----END PRIVATE KEY-----";
    $prikey = '-----BEGIN PRIVATE KEY-----'."\n".$prikey."\n".'-----END PRIVATE KEY-----';
    $pi_key = openssl_pkey_get_private($prikey);
    $crypto = '';
    foreach (str_split($data, 117) as $chunk) {
        openssl_private_encrypt($chunk, $encryptData, $pi_key);
        $crypto .= $encryptData;
    }

    return base64_encode($crypto);
}


function opensslSignNew( $prikey, $data, $signType = "RSA" ) {
//    $res = "-----BEGIN PRIVATE KEY-----\n" . wordwrap( $prikey, 64, "\n", true ) . "\n-----END PRIVATE KEY-----";
    $prikey = '-----BEGIN PRIVATE KEY-----'."\n".$prikey."\n".'-----END PRIVATE KEY-----';
//    $pi_key = openssl_pkey_get_private($prikey);
//    $crypto = '';
//    foreach (str_split($data, 117) as $chunk) {
//        openssl_private_encrypt($chunk, $encryptData, $pi_key);
//        $crypto .= $encryptData;
//    }
//
//    return base64_encode($crypto);

    $merchant_private_key = openssl_get_privatekey($prikey);
    openssl_sign($data, $sign_info, $merchant_private_key, OPENSSL_ALGO_MD5);
    return  base64_encode($sign_info);
}
