<?php
// 应用公共文件
use app\model\api\City as CityModel;

function is_moblie($mobile){
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[3456789]{1}\d{9}$/', $mobile) ? true : false;
}


/**
 * 图片数组
 * @param type $imgs
 * @param type $sep
 * @param type $limit
 * @return type
 */
function getImageAr($imgs,$limit=-1,$sep = ","){
    if(empty($imgs)){
        return [];
    }
    //返回全部
    if($limit==-1){
        return explode($sep,$imgs);
    }
    if($limit==0){
        return explode($sep,$imgs)[0];
    }
    return explode($sep,$imgs,$limit);
}
/**
 * 获取区域信息
 * @param type $id
 */
function getAreaItemAr($id){
    $cityModel = new CityModel();
    $data = $cityModel->field("id,name,level,parent_id,city_id")->where("id",$id)->find();
    if(empty($data)){
        return [];
    }
    if($data["level"]==0){
        return [$data];
    }
    $parentData = $cityModel->field("id,name,level,parent_id,city_id")->where("city_id",$data["parent_id"])->find();
    if($data["level"]==1){
        return [$parentData,$data];
    }
    $firstData = $cityModel->field("id,name,level,parent_id,city_id")->where("city_id",$parentData["parent_id"])->find();
    return [$firstData,$parentData,$data];
}

/**
 * 验证手机号是否正确
 * @param number $mobile
 * @author honfei
 */
function isMobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[3456789]{1}\d{9}$/', $mobile) ? true : false;
}

/**
 * 中间加密 用正则
 */
function encryptTel($tel)
{
    $new_tel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
    return $new_tel;
}


/**
 * 清除html
 * @param $str
 * @return mixed|string
 */
function clearHtml($str)
{
    if (!empty($str)) {
        $str = html_entity_decode($str);
        $str = strip_tags($str);
        $str = str_replace("&nbsp;", "", $str);
    }
    return $str;
}


/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    $_count = hanzi_length($str);
    if ($length > $_count && $start == 0) {
        $r = $str;
    } else {
        if (function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif (function_exists('iconv_substr')) {
            $slice = iconv_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("", array_slice($match[0], $start, $length));
        }
        $r = $suffix ? $slice . '...' : $slice;
    }
    return $r;
}


/**
 * 计算字符串长度
 * @param type $str
 * @return int
 */
function hanzi_length($str)
{
    $len = strlen($str);
    $i   = 0;
    $n   = 0;
    while ($i < $len) {
        if (preg_match("/^[" . chr(0xa1) . "-" . chr(0xff) . "]+$/", $str[$i])) {
            $i += 4;
        } else {
            $i += 1;
        }
        $n += 1;
    }
    return $n;
}


/**
 * 随机码
 * @param type $length
 * @return string
 */
function randString($length, $c = false)
{
    if ($c) {
        $_codeSet = '123456789';//不要加0
    } else {
        $_codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
    }

    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $_codeSet[mt_rand(0, strlen($_codeSet) - 1)];
    }
    return $code;
}


/**
 * 验证用户信息返回用户信息
 *
 */
function is_mobile($user)
{
    $r = false;
    //验证是否手机号码
    $is_mobel = '/^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[[0-9])[0-9]{8}/is';
    if (preg_match($is_mobel, $user)) {
        $r = true;
    }
    return $r;
}

function encodePassword($password)
{
    return empty($password) ? '' : md5('$^95@Kdf' . md5('Pincll@yiyun' . $password));
}
/**
 * 生成用户唯一ip
 * @param type $uid
 */
function makeUuip($uid){
    $codeSert = '123456789ABCDEFGHJKLMNPQRTUVWXY';
    $code = '';
    $length = 10-strlen($uid)-2;
    for ($i = 0; $i < $length; $i++) {
        $code .= $codeSert[mt_rand(0, strlen($codeSert) - 1)];
    }
    return $code."IP".$uid;
}

function makeOrderId($uid,$per="H"){
    $codeSert = '123456789ABCDEFGHJKLMNPQRTUVWXY';
    $code = '';
    $length = 4;
    for ($i = 0; $i < $length; $i++) {
        $code .= $codeSert[mt_rand(0, strlen($codeSert) - 1)];
    }
    $time = microtime(true)*10000;
    return $per . $time . $code  . "OU" .$uid;
}
/**
 * 获取唯一token
 * @param type $lower 小写
 * @return string
 */
function getPartToken($lower=false,$sep=true){
    $key = "";
    if (function_exists ( 'com_create_guid' )) {
        $key = com_create_guid();
    } else {
        //mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(),true))); //根据当前时间（微秒计）生成唯一id.
        $hyphen = chr(45); // "-"
        $uuid = '' . //chr(123)// "{"
        substr($charid,0,8 ).$hyphen.substr($charid,8,4).$hyphen.substr($charid,12,4).$hyphen.substr($charid,16,4).$hyphen.substr($charid,20,12);
        //.chr(125);// "}"
        $key = $uuid;
    }
    //小写
    if($lower){
        $key = strtolower($key);
    }
    //无分隔符
    if(!$sep){
        $key = str_replace(chr(45), "", $key);
    }
    return $key;
}
/**
 * 生成UUID
 * @param $uid
 * @return string
 */
function Uuid($uid)
{
    $uuid = randString(8,true);
    $uuid = substr($uuid,0, - (strlen($uid)+1)) ."0". $uid;
    return $uuid;
}
/**
 * 生成客服UUID
 * @param $uid
 * @return string
 */
function Kuuid($admin_id)
{
    $uuid = randString(8,true);
    $uuid = "kf".substr($uuid,0, - (strlen($admin_id)+1)) ."0". $admin_id;
    return $uuid;
}
/**
 * 生成TUUID
 * @param $tuid
 * @return string
 */
function Tuuid($tuid)
{
    $tuuid = randString(8,true);
    $tuuid = substr($tuuid,0, - (strlen($tuid)+1))."0".$tuid;
    $str   = "ABCDEFGHIJKLMNOPQRSTUVWSYZ";
    $wordStart  = substr($str,mt_rand(0,25),1);
    return $wordStart.$tuuid;
}

/**
 * 验证身份证
 * @param $num
 * @return bool
 */
function IdentityCard($num) {
    return \library\utils\IdentityCard::isValid($num);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * 获取客户端信息
 */
function getClientInfo(){
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if(empty($agent)){
        return false;
    }
    $platform="";//平台
    $browser="";//内置浏览器版本
    //ios系统
    if(strpos($agent,'iPad') !== false || strpos($agent,'iPhone') !== false){
        $platform = "ios";
    }
    //android系统
    if(strpos($agent,'Android') !== false){
        $platform = "android";
    }
    //微信内置浏览器
    if (strpos($agent,'MicroMessenger') !== false ) {
        $browser = "weixin";
    }
    //QQ内置浏览器
    if (strpos($agent,'QQ') !== false && strpos($agent,'_SQ_') !== false) {
        $browser = "qq";
    }
    return ["platform"=>$platform,"browser"=>$browser];
}
/**
 * 获取随机键值
 * @param type $count
 * @return type
 */
function getRandKeyVal(){
    $words = "abcdefghijklmnopqrstuvwxyz";
    $key = substr($words,mt_rand(0,25),1).substr($words,mt_rand(0,25),1).mt_rand(0,9);
    $val = mt_rand(100,999);
    return ["key"=>$key,"val"=>$val];
}

/**
 * 不四舍五入保留小数
 * @param type $num
 * @param type $digit
 * @return type
 */
function num_min_format($num,$digit=2){
    $num = strval(floatval($num));
    if(strpos($num,'.')===false){
       return floatval($num);
    }else{
       return floatval(explode(".",$num)[0].".".substr(explode(".",$num)[1],0,$digit));
    }
}

/*********************************经纬度计算函数*******************************/

/**
 * 获取定位信息
 * @param type $lats
 * @param type $lngs
 * @param type $gps
 * @param type $google
 * @return type
 */
function getgps($lats,$lngs, $gps=false, $google=false)
{
    $lat=$lats;
    $lng=$lngs;
    if($gps)
        $c=file_get_contents("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=$lng&y=$lat");
    else if($google)
        $c=file_get_contents("http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=$lng&y=$lat");
    else
    return array($lat,$lng);
    $arr=(array)json_decode($c);
    if(!$arr['error'])
    {
        $lat=base64_decode($arr['y']);
        $lng=base64_decode($arr['x']);
    }
    return array($lat,$lng);
}
/**
* @desc 根据两点间的经纬度计算距离
* @param float $lat 纬度值
* @param float $lng 经度值
*/
function getDistance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6367000; //approximate radius of earth in meters

    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;

    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;

    return round($calculatedDistance);
}
/**
*获取距离
**/
function getDicAres($size){
    $v = $size / 1000;
    return number_format($v, 2, '.', '');
}

/**
 * 百度转化qq
 * @param type $lng
 * @param type $lat 
 */
function bMapTransQQMap($lng, $lat){
    $x_pi=3.14159265358979324 * 3000.0/180.0;
    $x = $lng - 0.0065;
    $y = $lat - 0.006;
    $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
    $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
    $lngs = $z * cos($theta);
    $lats = $z * sin($theta);
    return array($lngs,$lats);
}

/**
 * 获取图片信息
 * @param type $url
 * @return type
 */
function getImageUrlInfo($url){
    //图片信息
    $imgInfo = @getimagesize($url);
    if(!$imgInfo){
        return false;
    }
    $urlAr = explode("/",$url);
    $fileName = $urlAr[count($urlAr)-1];
    $info=[];
    $info["size"] = remote_filesize($url);
    $info["name"] = explode(".",$fileName)[0];
//    $info["url"]  = str_replace("/{$fileName}", "", $url);
    $info["url"]  = $url;
    $info["w"]    = $imgInfo[0];
    $info["h"]    = $imgInfo[1];
    $info["ext"]  = explode("/",$imgInfo["mime"])[1]; 
    $info["md5"]  = md5_file($url);
    return $info;
}
// 获取远程文件大小函数
function remote_filesize($url, $user = "", $pw = "")
{
    ob_start();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    if(!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $ok = curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);
    return isset($matches[1]) ? intval($matches[1]) : 0;
}



