<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class UtilService 
{
    public static function isMobileBrower()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = array ('iphone','android','phone','mobile','wap','netfront','java','opera mobi',
            'opera mini','ucweb','windows ce','symbian','series','webos','sony','blackberry','dopod',
            'nokia','samsung','palmsource','xda','pieplus','meizu','midp','cldc','motorola','foma',
            'docomo','up.browser','up.link','blazer','helio','hosin','huawei','novarra','coolpad',
            'techfaith','alcatel','amoi','ktouch','nexian','ericsson','philips','sagem','wellcom',
            'bunjalloo','maui','smartphone','iemobile','spice','bird','zte-','longcos','pantech',
            'gionee','portalmmm','jig browser','hiptop','benq','haier','^lct','320x320','240x320',
            '176x220','windows phone','cect','compal','ctl','lg','nec','tcl','daxian','dbtel','eastcom',
            'konka','kejian','lenovo','mot','soutec','sgh','sed','capitel','panasonic','sonyericsson',
            'sharp','panda','zte','acer','acoon','acs-','abacho','ahong','airness','anywhereyougo.com',
            'applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','bilbo',
            'bleu','cdm-','danger','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess',
            'gradiente','grundig','hedy','hitachi','htc','hutchison','inno','ipad','ipaq','ipod',
            'jbrowser','kddi','kgt','kwc','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-',
            'lge9','maemo','mercator','meridian','micromax','mini','mitsu','mmm','mmp','mobi','mot-',
            'moto','nec-','newgen','nf-browser','nintendo','nitro','nook','obigo','palm','pg-',
            'playstation','pocket','pt-','qc-','qtek','rover','sama','samu','sanyo','sch-','scooter',
            'sec-','sendo','sgh-','siemens','sie-','softbank','sprint','spv','tablet','talkabout',
            'tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','utec','utstar','verykool','virgin',
            'vk-','voda','voxtel','vx','wellco','wig browser','wii','wireless','xde','pad','gt-p1000',
            'wechat', 'alipay',
        );
        $ismobile = false;
        foreach ($mobile_agents as $device) {
            if (stristr($user_agent, $device)) {
                $ismobile = true;
                break;
            }
        }
        return $ismobile;
    }
    
    
    public static function isAppleEquip() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = array("iphone", "ipad", "ios");
        $isAppleEquip = false;
        foreach ($mobile_agents as $device) {
            if (stristr($user_agent, $device)) {
                $isAppleEquip = true;
                break;
            }
        }
        return $isAppleEquip;
    }
    
    
    public static function transformMobile($mobile)
    {
        if (empty($mobile)) {
            return '';
        }
        $prefix = substr($mobile, 0, 3);
        $posfix = substr($mobile, 7, 4);
        return $prefix . "****" . $posfix;
    }
    
    
    public static function getKefuURL($openid=0)
    {
        $uid = $openid;
        
        $time = time();
        $level = 0;
        $user_id = 0;
        if ($uid) {
            $signInfo = md5('platform=mg&openid=' . $uid . '&time=' . $time . '&GV49_4=HXjJpd|b6');
            $url = 'http://39.108.116.227:59365/query_account?platform=mg&openid=' . $uid . '&time=' . $time . '&sign=' . $signInfo;
            $result = self::get_http_request($url);
            Log::info("查询MG账号信息: " . $result, ['url' => $url]);
            $result = json_decode($result, true);
            if (isset($result['result']) && $result['result'] == 0) {
                $user_id = $result['accid'];
                $level = 1;
            } 
        } 
        
        if (empty($user_id)) {
            $user_id = 'visitor_' . base_convert(uniqid(), 16, 10) . mt_rand(10000, 99999);
        }
        
        $data = array(
            'app_id'=>138,
            'jobs_id'=>2,
            'level'=>$level,
            'plat_id'=>3,
            'plat_name'=>'橙橙用户中心',
            'server_id'=>1,
            'server_name'=>'用户中心',
            'channel_id'=>-1,
            'channel_name'=>'d',
            'timestamp'=>time(),
            'user_id'=>$user_id,
            'user_name'=>'游客',
            'ouid'=>$user_id
        );
        $customer_key = 'WUYO49KqmE$fia*L3g*W1Sdt8hmo5ygQV';
        $sign_info = self::getSign($data,$customer_key);
        return "https://kefu.srccwl.com/?" . $sign_info['str'].'&sign='.$sign_info['sign'];
    }
    
    public static function getSign($data,$key)
    {
        ksort($data);
        $str = '';
        $str_sign = '';
        foreach ($data as $k=>$v){
            $str .= "$k=" . urlencode($v) . "&";
            $str_sign .= "$k=" . urlencode($v) . "&";
        }
        $str = substr($str, 0, - 1);
        $str_sign = substr($str_sign, 0, - 1);
        $sign = hash_hmac('sha256', $str_sign, $key);
        return array('sign'=>$sign,'str'=>$str);
    }
    
    public static function get_http_request($url, $post_string='',$method="post", $connectTimeout=10, $readTimeout=10)
    {
        $method = strtolower($method);
        if($method == "get" && $post_string) {
            $url = $url."?".$post_string;
        }
        $result = "";
        if (function_exists('curl_init'))
        {
            $timeout = $connectTimeout + $readTimeout;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connectTimeout);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            if($method == "post") {
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if($http_code != 200)
            {
                curl_close($ch);
                return $result;
            }
            curl_close($ch);
        }
        else {
            return false;
        }
        return $result;
    }
    
    public static function genSafeSign($params, $prikey, &$query_string2=null)
    {
        if(!$params) {
            $params = array();
        }
        ksort($params);
        $query_string = array();
        $query_string2 = array();
        foreach ($params as $key => $val)
        {
            if($key == "sig" || $key == "sign") {
                continue;
            }
            array_push($query_string, $key . '=' . $val);
            array_push($query_string2, $key . '=' . rawurlencode($val));
        }
        $query_string = join('&', $query_string);
        $query_string2 = join('&', $query_string2);
        $sign = md5($prikey . $query_string);
        $query_string2 .= "&sign=".$sign;
        return $sign;
    }
    
    public static  function isPhoneNum($phone) {
        if (preg_match('/^1[0-9]{10}$/', $phone)) {
            return true;
        }else {
            return false;
        }
    }


    public static function getIsWx($httpUserAgent)
    {
        return true;
        if (strpos($httpUserAgent, 'MicroMessenger') !== false) {
            return true;
        } else {
            return false;
        }
    }

    public static function postCurlJson($url, $data,$headers = [], $timeout = 30){
        try {
            $requestHeader[] = "API-RemoteIP: ";
            $requestHeader[] = "Content-type: application/json";
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_HTTPHEADER,$requestHeader);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            $timeout = intval ( $timeout ) ? intval ( $timeout ) : 30;
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            $result = curl_exec($curl);
            curl_close($curl);
            return $result;
        } catch (exception $e) {
            throw new Exception($e->getMessage());
        }
    }
    
}