<?php


namespace App\Http\helper;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\Types\Self_;

class Helper
{

    // 游戏配置
    const Games = [1005, 2010, 2030, 2050, 2060, 2061, 3000, 3010, 3050];

    // rummy 配置
    const RUMMY_SERVER_IDS = [29, 30, 34, 35, 36, 37, 40, 41, 42, 43, 44, 45, 46, 48];
    // tp 配置
    const TEEN_PATTI_SERVER_IDS = [18, 19, 20, 31];

    public static function return_time(Request $request)
    {
        $start_time = str_replace('T', ' ', $request->start_time ?: '');
        $end_time = str_replace('T', ' ', $request->end_time ?: '');
        return compact('start_time', 'end_time');
    }

    public static function time($start_time, $end_time)
    {
        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);
        return compact('start_time');
    }

    // 获取毫秒
    public static function millisecond()
    {
        // 微妙时间戳
        list($msec, $sec) = explode(' ', microtime());
        $millisecond = (int)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $millisecond;
    }

    // 时间转换
    public static function timeChange($time)
    {
        !empty($time) && $time = date('Y-m-d', strtotime($time)) . 'T' . date('H:i:s', strtotime($time));

        return $time;
    }

    public static function str_replace($str = '')
    {
        if (strpos($str, '代付失败')) {
            $str = str_replace("代付失败", "Payment failed", $str);
        }
        if (strpos($str, '代付人信息不合法')) {
            $str = str_replace("代付人信息不合法", "Illegal payer information", $str);
        }

        if (strpos($str, '调用第三方渠道异常')) {
            $str = str_replace("调用第三方渠道异常", "Exception calling third-party channel", $str);
        }

        if (strpos($str, '请求三方通道异常')) {
            $str = str_replace("请求三方通道异常", "Request for third-party channel exception", $str);
        }

        if (strpos($str, '提交失败:订单重复')) {
            $str = str_replace("提交失败:订单重复", "Failed to submit: duplicate order", $str);
        }

        if (strpos($str, '订单重复')) {
            $str = str_replace("订单重复", "duplicate order", $str);
        }

        return $str;
    }

    public static function str_replaceCode($code = '')
    {
        switch ($code) {
            case '000218':
                $msg = '';
                break;
            case '000215':
                $msg = '';
                break;
            case '900000':
                $msg = '';
                break;
            case '000801':
                $msg = '';
                break;
            case '100301':
                $msg = '';
                break;
            case '999999':
                $msg = '';
                break;

        }
    }

    // 生成随机手机号
    public static function randPhone($UserID, $flag = false)
    {
        $prefix = '7436';
        if ($flag)
            $prefix = '+917436';

        $phone = $prefix . str_pad(array_random([7, 9]) . substr(time(), 5), 6);

        $first = DB::connection('write')->table('agent.dbo.PaymentSimulation')->where('UserID', $UserID)->first();

        if ($first) {
            $phone = $first->Phone;
        } else {
            DB::connection('write')->table('agent.dbo.PaymentSimulation')
                ->updateOrInsert(['UserID' => $UserID], [
                    'Phone' => $phone
                ]);
        }
        return $phone;
    }

    // 获取用户手机号
    public static function getPhone($UserID, $phone, $userName = '', $email = '')
    {


//        $AccountsInfo = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $UserID)->select('WebLogonTimes')->first();

        $AccountPhone = DB::connection('write')->table('QPAccountsDB.dbo.AccountPhone')->where('UserID', $UserID)->select('PhoneNum')->first()->PhoneNum ?? '';

        // 是否提现过
//        $AccountWithDrawInfo = DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')->where('UserID', $UserID)->select('PhoneNumber', 'BankUserName', 'EmailAddress')->first();

//        if ($AccountWithDrawInfo && !empty($AccountWithDrawInfo->BankUserName) && !empty($AccountWithDrawInfo->EmailAddress) && !empty($AccountWithDrawInfo->PhoneNumber)) {
//            $userName = $AccountWithDrawInfo->BankUserName;
//            $email = $AccountWithDrawInfo->EmailAddress;
//            $phone = $AccountWithDrawInfo->PhoneNumber;
//        }


        $userPayInfo = self::userPayInfo($UserID);

        // 绑定过手机号
        if (!empty($AccountPhone)) {

//            if (!$AccountWithDrawInfo || empty($AccountWithDrawInfo->PhoneNumber)) { # 没有绑定过提现信息
            $phone = trim($AccountPhone);

            $userName = $userPayInfo['userName'];
            $email = $userPayInfo['email'];
//            }
        }

        $phone = str_replace('+91', '', $phone);


        if (empty($phone) || $phone == 'undefined') {
            $phone = $userPayInfo['phone'];
        }
        if (empty($userName) || $userName == 'undefined') {
            $userName = $userPayInfo['userName'];
        }
        if (empty($email) || $email == 'undefined') {
            $email = $userPayInfo['email'];
        }

        return compact('phone', 'userName', 'email');
    }

    // 用户支付信息模拟
    public static function userPayInfo($UserID, $userName = '', $email = '')
    {

        $PaymentSimulation = DB::connection('read')->table('agent.dbo.PaymentSimulation')
            ->where('UserID', $UserID)
            ->first();

        $mt_rand = mt_rand(1, 6719);
        $PayUserNames = DB::connection('read')->table('agent.dbo.PayUserNames')->where('id', $mt_rand)->first();
        if (!$PayUserNames) {
            $PayUserNames = DB::connection('read')->table('agent.dbo.PayUserNames')->where('id', 1)->first();
        }
        // Log::info('用户姓名:'.$userName);

        // 用户输入  》 用户提现的信息  》 随机模拟值
        if (empty($userName) || empty($email) || $userName == 'undefined' || $email == 'undefined') {
            $first = DB::connection('read')->table('QPAccountsDB.dbo.AccountWithDrawInfo')
                ->where('UserID', $UserID)
                ->select('BankUserName', 'EmailAddress')
                ->first();

            if (!$first || empty($first->BankUserName) || empty($first->EmailAddress)) {
                if (!$PaymentSimulation) {
                    $userName = $PayUserNames->user_name;
                    $email = $userName . mt_rand(1, 9999) . self::rand_email();
                } else {
                    $userName = empty($PaymentSimulation->UserName) ? $PayUserNames->user_name : $PaymentSimulation->UserName;
                    $email = empty($PaymentSimulation->Email) ? $userName . mt_rand(1, 9999) . self::rand_email() : $PaymentSimulation->Email;
                }
            } else {
                $userName = empty($first->BankUserName) ? $PayUserNames->user_name : $first->BankUserName;
                $email = empty($first->EmailAddress) ? $userName . mt_rand(1, 9999) . self::rand_email() : $first->EmailAddress;

            }
        }


        if (!$PaymentSimulation) {
            $phone = self::randPhone($UserID);
        } else {
            $phone = $PaymentSimulation->Phone;
        }

        DB::connection('write')->table('agent.dbo.PaymentSimulation')
            ->updateOrInsert(['UserID' => $UserID], [
                'Phone' => $phone,
                'UserName' => $userName,
                'Email' => $email,
                'LastTime' => date('Y-m-d H:i:s')
            ]);
        return compact('userName', 'email', 'phone');
    }


    // 获取随机邮箱后缀
    public static function rand_email()
    {
        $rand_email = array(
            '0' => array('id' => 1, 'email' => '@169.cb', 'v' => 2),
            '1' => array('id' => 2, 'email' => '@1236.com', 'v' => 3),
            '2' => array('id' => 3, 'email' => '@gmail.com', 'v' => 95),
        );
        $arr = [];
        foreach ($rand_email as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }

        $rid = self::get_rand($arr); //根据概率获取奖项id

        $email = $rand_email[$rid - 1]['email']; //中奖项
        return $email;
    }

    // 获取随机数
    public static function get_rand($proArr)
    {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }


    // 生成随机手机号
    public static function round_phone($flag = true)
    {
        $prefix = '7436';
        if ($flag)
            $prefix = '+917436';

        $phone = $prefix . str_pad(array_random([7, 9]) . substr(time(), 5), 6);
        return $phone;
    }

    // 获取IP所在地址
    public static function get_ip_city($ip)
    {
        $ch = curl_init();
        $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
        //用curl发送接收数据
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求为https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $location = curl_exec($ch);
        curl_close($ch);
        //转码
        $location = mb_convert_encoding($location, 'utf-8', 'GB2312');
        //var_dump($location);
        //截取{}中的字符串
        $location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
        //将截取的字符串$location中的‘，’替换成‘&’   将字符串中的‘：‘替换成‘=’
        $location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
        //php内置函数，将处理成类似于url参数的格式的字符串  转换成数组
        parse_str($location, $ip_location);
        return $ip_location['addr'];
    }

    // 获取IP所在地址 -- 阿里
    public static function getIPCity($ip)
    {

        $config = config('api.aliyun');

        AlibabaCloud::accessKeyClient($config['accessKeyID'], $config['accessKeySecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('geoip')
                // ->scheme('https') // https | http
                ->version('2020-01-01')
                ->action('DescribeIpv4Location')
                ->method('POST')
                ->host('geoip.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'Ip' => $ip,
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        }
    }
}
