<?php
use Illuminate\Support\Facades\Redis;

function route_class() {
	return str_replace ( '.', '-', Route::currentRouteName () );
}
function ngrok_url($routeName, $parameters = []) {
	// 开发环境，并且配置了 NGROK_URL
	if (app ()->environment ( 'local' ) && $url = config ( 'app.ngrok_url' )) {
		// route() 函数第三个参数代表是否绝对路径
		return $url . route ( $routeName, $parameters, false );
	}

	return route ( $routeName, $parameters );
}

// 默认的精度为小数点后两位
function big_number($number, $scale = 2) {
	return new \Moontoast\Math\BigNumber ( $number, $scale );
}
function getDateTime() {
	return date ( 'Y-m-d H:i:s', time () );
}
function getYesterdayDateNoHours() {
	return date ( "Y-m-d", strtotime ( "-1 day" ) );
}
function curlJavaB2cApi($functionName, $body, $token = '', $terminal = 1) {
	$data ['header'] ['time_stamp'] = getMillisecond ();
	$data ['header'] ['transaction_type'] = $functionName;
	$data ['header'] ['message_id'] = date ( "YmdHis", time () );
	$data ['header'] ['terminal'] = $terminal;

	$data ['body'] = $body;
	if ($token != '')
		$data ['header'] ['token'] = $token;
	$json = json_encode ( $data );
	$base64 = base64_encode ( $json );
	$url = env ( 'IS_BAIDUYUN' ) ? 'http://192.168.98.215:8081/leyou-gateway-services' : config ( 'app.b2c_api_url' );
	// $url = 'http://192.168.98.215:8081/leyou-gateway-services';

	$function = "/$functionName/";
	$finalStr = $url . $function . $base64;

	\Log::info ( $finalStr );
	$response = Curl::to ( $finalStr )->get ();

	return $response;
}
function curlJavaB2cJsonApi($functionName, $body, $token = '', $terminal = 1) {
	$version = '1.0.0';
	$imai = 'server';
	$message_id = date ( "YmdHis", time () );
	$time_stamp = getMillisecond ();
	$data ['header'] ['time_stamp'] = $time_stamp;
	$data ['header'] ['transaction_type'] = $functionName;
	$data ['header'] ['message_id'] = $message_id;
	$data ['header'] ['terminal'] = $terminal;
	$data ['header'] ['token'] = $token;

	$sign = md5 ( $message_id . '&' . $time_stamp . '&' . $functionName . '&' . $terminal . '&' . $token . '&' . 'ddxcx1234@webapi' );
	$str = '';
	$index = 0;
	while ( 1 ) {
		if (! isset ( $sign [$index] )) {
			break;
		}
		if ($index % 2 == 0) {
			$str .= $sign [$index];
		}
		$index ++;
	}
	$data ['header'] ['sign'] = md5 ( $str );

	if (isset ( $body ['city_id'] )) {
		$data ['header'] ['city_id'] = $body ['city_id'];
		unset ( $body ['city_id'] );
	}

	$data ['body'] = $body;

	$json = json_encode ( $data );

	$base64 = base64_encode ( $json );
	$url = env ( 'LEYOU_API' );

	$function = "/$functionName";
	$finalStr = $url . $function . "?json=" . $base64;
	$response = Curl::to ( $finalStr )->get ();

	return $response;
}
function getMillisecond() {
	$time = explode ( " ", microtime () );
	$time = $time [1] . ($time [0] * 1000);
	$time2 = explode ( ".", $time );
	$time = $time2 [0];
	return ( int ) $time;
}
function getUrlParams($url) {
	$arr = parse_url ( $url );
	$queryParts = explode ( '&', $arr ['query'] );
	$params = array ();
	foreach ( $queryParts as $param ) {
		$item = explode ( '=', $param );
		$params [$item [0]] = $item [1];
	}
	return $params;
}
function getProductId() {
	return date ( 'Ymd' ) . str_pad ( mt_rand ( 1, 99999 ), 5, '0', STR_PAD_LEFT );
}
function getUserIdByToken($token) {
	$data ['header'] ['time_stamp'] = getMillisecond ();
	$data ['header'] ['message_id'] = date ( "YmdHis", time () );
	$data ['header'] ['transaction_type'] = "default";
	$data ['header'] ['terminal'] = 9;
	$data ['header'] ['token'] = $token;
	$str = json_encode ( $data );
	$url = env ( "LEYOU_API" ) . "/user/getUserInfo/" . base64_encode ( $str );
	$response = json_decode ( Curl::to ( $url )->get (), true );

	$userId = "";
	if ($response ['header'] ['res_code'] == 0) {
		$userId = $response ['body'] ['userid'];
	}
	return $userId;
}
function getUserInfoByToken($token) {
	$data ['header'] ['time_stamp'] = getMillisecond ();
	$data ['header'] ['message_id'] = date ( "YmdHis", time () );
	$data ['header'] ['transaction_type'] = "default";
	$data ['header'] ['terminal'] = 9;
	$data ['header'] ['token'] = $token;
	$data ['header'] ['version'] = "5.1.0";
	$str = json_encode ( $data );
	$url = env ( "LEYOU_API" ) . "/my/getUserInfoIndex/" . base64_encode ( $str );
	$response = json_decode ( Curl::to ( $url )->get (), true );
	if ($response ['header'] ['res_code'] == 0)
		return $response ['body'];
	return '';
}
function lastSql() {
	$sql = \Illuminate\Support\Facades\DB::getQueryLog ();

	$query = end ( $sql );

	return $query;
}
function transCreatedAt($date) {
	return date ( "m-d H:i", strtotime ( $date ) );
}
function uploadFile($file_name, $suffix) {
	$auth = new Qiniu\Auth ( env ( 'ACCESS_KEY' ), env ( 'SECRET_KEY' ) );
	$token = $auth->uploadToken ( env ( 'BUCKET_NAME' ) );
	$key = time () . uniqid () . '.' . $suffix;
	$uploadMgr = new Qiniu\Storage\UploadManager ();
	list ( $ret, $err ) = $uploadMgr->putFile ( $token, $key, $file_name );
	if ($err !== null) {
		return $err;
	} else {
		$ret ['key'] = 'http://' . env ( 'OSS_URI' ) . $key;
		return $ret;
	}
}
function base64img_to_qiniu($post_string, $upToken) {
	$remote_server = env ( 'BASE64URI', 'http://upload.qiniu.com/putb64/-1' );
	
	$headers = array ();
	$headers [] = 'Content-Type:application/octet-stream';
	$headers [] = 'Authorization:UpToken ' . $upToken;
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $remote_server );
	// curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	// curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_string );
	curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
	$data = curl_exec ( $ch );
	curl_close ( $ch );
	dd ( $data );
	\Log::info ( $data );
	echo $data;
	return json_decode ( $data )->key;
}
function getQiniuImgUrl($key) {
	return 'http://' . env ( 'OSS_URI', 'ozpfb5509.bkt.clouddn.com/' ) . $key;
}

/**
 * 生成xml字符
 *
 * @param array $xml
 */
function get_xml($arr) {
	$xml = "<xml>";
	foreach ( $arr as $key => $val ) {
		if (is_numeric ( $val )) {
			$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
		} else {
			$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
		}
	}
	$xml .= "</xml>";
	return $xml;
}

/**
 * 将xml转为array
 *
 * @param string $xml
 */
function xml_to_arr($xml) {
	$arr = array ();
	libxml_disable_entity_loader ( true );
	$arr = json_decode ( json_encode ( simplexml_load_string ( $xml, 'SimpleXMLElement', LIBXML_NOCDATA ) ), true );
	
	return $arr;
}
function pay_get_trade_no() {
	return date ( "YmdHis" ) . mt_rand ( 10, 99 ) . mt_rand ( 10, 99 );
}

/*
 * 随机字符串
 * 参数:
 * (int)$length = 32 #随机字符长度
 * (int)$mode = 0 #随机字符类型，
 * 0为大小写英文和数字,1为数字,2为小写字母,3为大写字母,
 * 4为大小写字母,5为大写字母和数字,6为小写字母和数字
 * 返回:取得的字符串
 */
function get_code($length = 4, $mode = 1) {
	switch ($mode) {
		case '1' :
			$str = '123456789';
			break;
		case '2' :
			$str = 'abcdefghijklmnopqrstuvwxyz';
			break;
		case '3' :
			$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			break;
		case '4' :
			$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
			break;
		case '5' :
			$str = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
			break;
		case '6' :
			$str = 'abcdefghijkmnpqrstuvwxyz23456789';
			break;
		default :
			$str = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefhijkmnprstuvwxyz2345678';
			break;
	}
	$checkstr = '';
	$len = strlen ( $str ) - 1;
	for($i = 0; $i < $length; $i ++) {
		$num = mt_rand ( 0, $len ); // 产生一个0到$len之间的随机数
		$checkstr .= $str [$num];
	}
	return $checkstr;
}

/**
 * 获取用户真实IP地址
 *
 * @return string|int IP地址
 */
function http_get_real_ip($return_long = false) {
	$ip = isset ( $_SERVER ['HTTP_X_REAL_IP'] ) ? trim ( $_SERVER ['HTTP_X_REAL_IP'] ) : '';
	$ip = empty ( $ip ) ? trim ( $_SERVER ['REMOTE_ADDR'] ) : $ip;
	
	$return_long = ! ! $return_long;
	if ($return_long) {
		$ip = ip2long ( $ip );
	}
	
	return $ip;
}

/**
 * 微信 生成签名 sign
 */
function wx_make_sign($arr, $wx_key) {
	// 签名步骤一：按字典序排序参数
	ksort ( $arr );
	$buff = "";
	foreach ( $arr as $k => $v ) {
		if ($k != "sign" && $v != "" && ! is_array ( $v )) {
			$buff .= $k . "=" . $v . "&";
		}
	}
	$string = trim ( $buff, "&" );
	// 签名步骤二：在string后加入KEY
	$string = $string . "&key=" . $wx_key;
	// 签名步骤三：MD5加密
	$string = md5 ( $string );
	// 签名步骤四：所有字符转为大写
	$result = strtoupper ( $string );
	
	return $result;
}

/**
 * 用post提交xml到url
 *
 * @param string $xml
 *        	需要post的xml数据
 * @param string $url
 *        	url
 * @param int $second
 *        	url执行超时时间，默认30s
 */
function post_xml_url($xml, $url, $second = 30) {
	$ch = curl_init ();
	
	curl_setopt ( $ch, CURLOPT_TIMEOUT, $second );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, TRUE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
	curl_setopt ( $ch, CURLOPT_HEADER, FALSE );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
	curl_setopt ( $ch, CURLOPT_POST, TRUE );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $xml );
	
	$data = curl_exec ( $ch );
	
	if ($data) {
		curl_close ( $ch );
		return $data;
	} else {
		curl_close ( $ch );
		return false;
	}
}
function getImageInfoBybase64($base64) {
	if (preg_match ( '/^(data:\s*image\/(\w+);base64,)/', $base64, $result )) {
		$img ['type'] = $result ['2'];
		$img ['base64Str'] = str_replace ( $result [1], '', $base64 );
		return $img;
	}
}
function getOpenIdBySkey($skey) {
	$openid = '';
	$string = Redis::get ( $skey );
	if ($string) {
		$arr = explode ( "|", $string );
		$openid = $arr [1];
	}
	
	return $openid;
}
function getWeek($time = '', $format = 'Y-m-d') {
	$time = $time != '' ? $time : time ();
	// 获取当前周几
	$week = date ( 'w', $time );
	$date = [ ];
	for($i = 1; $i <= 7; $i ++) {
		$date [$i] = date ( $format, strtotime ( '+' . $i - $week . ' days', $time ) );
	}
	return $date;
}
function getDateTimeNoHours() {
	return date ( 'Y-m-d', time () );
}
function setSearchLabel($formAction, $columnList, $searchAction = '') {
	$label ['form_action'] = url ( $formAction );
	if ($searchAction != '')
		$label ['search_action'] = url ( $searchAction );
		foreach ( $columnList as $key => $column ) {
			$label ['column'] [$key] = $column;
		}
		return $label;
}
