<?php
namespace app\common\utils;

/**
* 网络请求帮助类
*/
class Util
{
    /**
     * 生成随机字符串
     * @param  integer $length [description]
     * @return [type]          [description]
     */
    public static function getRandChar($length=0)
    {
        $str = '';
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;
        for($i = 0; $i < $length; $i++){
            //rand($min,$max)生成介于min和max两个数之间的一个随机整数
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }

    /**
     * 生成随机名
     * @return [type] [description]
     */
    public static function getRandName()
    {
        $t = getdate();
        $year = $t['year'];
        $mon = $t['mon'] > 10 ? $t['mon'] : "0".$t['mon'];
        $day = $t['mday'] > 10 ? $t['mday'] : "0".$t['mday'];
        $hours = $t['hours'] > 10 ? $t['hours'] : "0".$t['hours'];
        $minutes = $t['minutes'] > 10 ? $t['minutes'] : "0".$t['minutes'];
        $seconds = $t['seconds'] > 10 ? $t['seconds'] : "0".$t['seconds'];

        $str = $year.$mon.$day.$hours.$minutes.$seconds.rand(1000, 9999);
        return $str;
    }

    /**
     * 获取当前时间毫秒数
     * @return [type] [description]
     */
    public static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    /**
     * unicode to utf8
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public static function unicode2utf8($str)
    {
        if(!$str){
            return $str;
        }
        $decode = json_decode($str);
        if($decode){
            return $decode;
        }
        $str = '["' . $str . '"]';
        $decode = json_decode($str);
        if(count($decode) == 1){
            return $decode[0];
        }
        return $str;
    }

    /**
     * 获取扩展名
     * @param filename
     */
    public static function getFileExt( $fileName )
    {
        $pos = strrpos($fileName, '.');
        $fileExt = strtolower(substr($fileName, ($pos+1) ));

        return $fileExt;
    }

    /**
     * 获取去除扩展名的文件名
     * @param filename
     */
    public static function getPureName( $fileName )
    {
        $pos = strrpos($fileName, '.');
        $fileName = strtolower(substr($fileName, 0, $pos));

        return $fileName;
    }

    /**
     * 生成随机的文件名
     * @param filename
     */
    public static function getRandomName( $fileName ){
        $pos = strrpos($fileName, '.');
        $fileExt = strtolower(substr($fileName, $pos));
        $t = getdate();
        $year = $t['year'];
        $mon = $t['mon'] > 10 ? $t['mon'] : "0".$t['mon'];
        $day = $t['mday'] > 10 ? $t['mday'] : "0".$t['mday'];
        $hours = $t['hours'] > 10 ? $t['hours'] : "0".$t['hours'];
        $minutes = $t['minutes'] > 10 ? $t['minutes'] : "0".$t['minutes'];
        $seconds = $t['seconds'] > 10 ? $t['seconds'] : "0".$t['seconds'];

        $str = $year.$mon.$day.$hours.$minutes.$seconds.rand(1000, 9999).$fileExt;
        return $str;
    }

    /**
     * 容量单位计算，支持定义小数保留长度；定义起始和目标单位，或按1024自动进位
     *
     * @param int $size,容量计数
     * @param type $unit,容量计数单位，默认为字节
     * @param type $decimals,小数点后保留的位数，默认保留一位
     * @param type $targetUnit,转换的目标单位，默认自动进位
     * @return type 返回符合要求的带单位结果
     */
    public static function fileSizeConv($size, $unit = 'B', $decimals = 1, $targetUnit = 'auto') {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
        // 初始单位是哪个
        $theUnit = array_search(strtoupper($unit), $units);
        // 判断是否自动计算
        if ($targetUnit != 'auto'){
            $targetUnit = array_search(strtoupper($targetUnit), $units);
        }
        // 循环计算
        while ($size >= 1024) {
            $size/=1024;
            $theUnit++;
            // 已符合给定则退出循环吧！
            if ($theUnit == $targetUnit){
                break;
            }
        }
        return sprintf("%1\$.{$decimals}f", $size) ." ". $units[$theUnit];
    }

    /**
     * 图像缩放
     * @param $source_path string 原图路径
     * @param $save_path string 保存路径
     * @param $ratio int 大图与小图比例 3:1=3
     * @param $file_name string 文件名
     */
    public static function imageratio($source_path, $save_path, $ratio, $file_name)
    {
        $source_info = getimagesize($source_path);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];

        $target_width = $source_width / $ratio;
        $target_height = $source_height / $ratio;

        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }

        $target_image = imagecreatetruecolor($target_width, $target_height);
        // 缩放
        imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $target_width, $target_height, $source_width, $source_height);

        //保存图片到本地
        switch ($source_mime) {
            case 'image/gif':
                imagegif($target_image, $save_path.$file_name);
                break;
            case 'image/jpeg':
                imagejpeg($target_image, $save_path.$file_name);
                break;
            case 'image/png':
                imagepng($target_image, $save_path.$file_name);
                break;
            default:
                return false;
                break;
        }

        imagedestroy($source_image);
        imagedestroy($target_image);

        return $file_name;
    }

    /**
     * 图像裁剪
     * @param $source_path string 原图路径
     * @param $save_path string 保存路径
     * @param $target_width string 需要裁剪的宽
     * @param $target_height string 需要裁剪的高
     * @param $file_name string 文件名
     */
    public static function imagecropper($source_path, $save_path, $target_width, $target_height, $file_name)
    {
        $source_info = getimagesize($source_path);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];
        $source_ratio = $source_height / $source_width;
        $target_ratio = $target_height / $target_width;

        // 源图过高
        if ($source_ratio > $target_ratio) {
            $cropped_width = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        }
        // 源图过宽
        elseif ($source_ratio < $target_ratio) {
            $cropped_width = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        }
        // 源图适中
        else{
            $cropped_width = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }

        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }

        $target_image = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

        //保存图片到本地
        switch ($source_mime) {
            case 'image/gif':
                imagegif($target_image, $save_path.$file_name);
                break;
            case 'image/jpeg':
                imagejpeg($target_image, $save_path.$file_name);
                break;
            case 'image/png':
                imagepng($target_image, $save_path.$file_name);
                break;
            default:
                return false;
                break;
        }

        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);

        return $file_name;
    }

    /**
     * @desc 异步将远程链接上的内容(图片或内容)写到本地
     * @param str $url 远程图片/文件地址
     * @param str $localfile 本地服务器保存文件的路径（包括文件名）
     * @return boolean
    */
    public static function download_url_file($url, $localfile) {
        // 设置运行时间为无限制
        set_time_limit ( 0 );
        
        $url = trim ( $url );
        $curl = curl_init ();
        // 设置你需要抓取的URL
        curl_setopt ( $curl, CURLOPT_URL, $url );
        // 设置header
        curl_setopt ( $curl, CURLOPT_HEADER, 0 );
        // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
        // 运行cURL，请求网页
        $file = curl_exec ( $curl );
        // 关闭URL请求
        curl_close ( $curl );
        // 将文件写入获得的数据
        $write = @fopen ( $localfile, "w" );
        if ($write == false) {
            return false;
        }
        if (fwrite ( $write, $file ) == false) {
            return false;
        }
        if (fclose ( $write ) == false) {
            return false;
        }
    }

    /**
     * @desc 拼接合成多长张图片
     * @param unknown $src_image  合成图片的底图 
     * @param unknown $images  要合成的图片数组
     * @param unknown $dstpng  合成后最后的图片路径
     * @return boolean
    */
    public static function mergerImg($src_image, $images, $dstpng) {
        // $src_image = "../src.png";
        // $images = array(
        //     0 => array(
        //         "path" => "../1.png",
        //         "x" => 60,
        //         "y" => 60,
        //     ),
        //     1 => array(
        //         "path" => "../2.png",
        //         "x" => 30,
        //         "y" => 30,
        //     ),
        //     2 => array(
        //         "path" => "../3.png",
        //         "x" => 110,
        //         "y" => 110,
        //     )
        // );

        list($max_width, $max_height) = getimagesize($src_image);
        $dests = imagecreatetruecolor($max_width, $max_height);
        
        $dst_im = imagecreatefrompng($src_image);

        imagecopy($dests,$dst_im, 0, 0, 0, 0, $max_width, $max_height);
        imagedestroy($dst_im);

        // 循环合成图片
        foreach ($images as $key => $img) {
            // 二维码
            $src_im = imagecreatefrompng($img["path"]);
            $src_info = getimagesize($img["path"]);
            imagecopy($dests, $src_im, $img["x"], $img["y"], 0, 0, $src_info[0], $src_info[1]);
            imagedestroy($src_im);
        }
        
        // header("Content-type: image/jpeg");
        return imagejpeg($dests, $dstpng);
    }

    /**
     * @desc 按指定尺寸改变图片大小
     * @param  $imgsrc  原图路径
     * @param  $imgdst  处理后的图片路径（可以和原图一样）
     * @param  $imgwidth   要改变的宽度 
     * @param  $imgheight  要改变的高度
     * @return boolean
    */
    public static function resizejpg($imgsrc, $imgdst, $imgwidth, $imgheight)
    {
        // 取得图片的宽度,高度值
        $arr = getimagesize($imgsrc);                     
        // header("Content-type: image/jpg");
        
        $imgWidth = $imgwidth;
        $imgHeight = $imgheight;
        // Create image and define colors
        $imgsrc = imagecreatefromjpeg($imgsrc);
        $image = imagecreatetruecolor($imgWidth, $imgHeight);  //创建一个彩色的底图
        imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth, $imgHeight, $arr[0], $arr[1]);
        imagepng($image, $imgdst);
        return imagedestroy($image);
    }

    /**
     * @desc 文字生成图片，字体为『微软雅黑』
     * @param  $font  字体
     * @param  $font_size  字体大小  14px
     * @param  $text  文字内容：汪小熊
     * @param  $text_png  目标图片 
     * @return boolean
    */
    public static function text2image($font, $font_size, $text, $colors, $text_png){
        $font =  iconv("UTF-8", "gb2312", $font);
        $fontarea = imagettfbbox($font_size,0,$font,$text); //确定会变化的字符串的位置
        $text_width = $fontarea[2]-$fontarea[0]+($font_size/3); //字符串文本框长度
        $text_height = $fontarea[1]-$fontarea[7]+($font_size/3); ////字符串文本框高度
        $im = imagecreate($text_width , $text_height); 
        $white = imagecolorallocate($im, 255, 255, 255); //定义透明色
        $red = imagecolorallocate ($im , $colors["r"], $colors["g"], $colors["b"]);  //文本色彩
        imagettftext ($im , $font_size , 0 , 0, $text_height-($font_size/2.5) , $red, $font, $text); 
        imagecolortransparent($im, $white);
        imagepng ( $im, $text_png); 
        imagedestroy ($im); 
    }

    /**
     * @desc 检查手机号格式
     * @param  $phone  手机号
     * @return boolean / $phone
    */
    public static function checkPhone($phone)
    {
        $phone = trim($phone);
        $flag = preg_match("/^1[0-9]{10}$|^0[0-9]{9,10}$/", $phone);

        if ( $flag ) {
            return  $phone;
        } else {
            return false;
        }
    }

    /**
     * @desc 生成折线图
     * @param  $array  统计数据
    */
    public static function getJPGraph($array, $title, $standard_color="blue", $standard_index=-1)
    {
        require_once (VENDOR_PATH."jpgraph/jpgraph/jpgraph.php");  
        require_once (VENDOR_PATH."jpgraph/jpgraph/jpgraph_line.php"); 

        $colors = array("red", "green", "orange", "drakred","drakgreen","drakblue","drakyellow","drakorange", "yellow");

        $data = $array;
        $data_keys = array_keys($data);

        $graph = new \Graph(500,300);   
        $graph->SetScale("textlin");
        $graph->SetShadow();
        $graph->img->SetMargin(60,30,30,70); //设置图像边距  
        
        $graph->graph_theme = null; //设置主题为null，否则value->Show(); 无效  

        // 画折线图
        for ($i=0; $i < count($data_keys); $i++) { 
            $lineplot=new \LinePlot($data[$data_keys[$i]]); //创建设置两条曲线对象  

            if ($standard_index != -1) {
                // 标准线索引和颜色
                if ($i == $standard_index) {
                    $lineplot->SetColor($standard_color);
                }else{
                    $lineplot->SetColor($colors[$i]);
                }
            }else{
                $lineplot->SetColor($colors[$i]);
            }

            $lineplot->value->SetColor($colors[$i]);  
            $lineplot->value->Show();  
            $graph->Add($lineplot);  //将曲线放置到图像上
            $lineplot->SetLegend($data_keys[$i]);  
        }

        $graph->title->Set($title);   //设置图像标题  

        // $graph->xaxis->title->Set(iconv("UTF-8", "GB2312//IGNORE", "月份")); //设置坐标轴名称  
        // $graph->yaxis->title->Set(iconv("UTF-8", "GB2312//IGNORE", "流 量(Gbits)"));  
        $graph->title->SetMargin(10);
        $graph->xaxis->title->SetMargin(10);  
        $graph->yaxis->title->SetMargin(10);  
 
        // $graph->xaxis->SetTickLabels($gDateLocale->GetShortMonth());  //设置x轴的值
        
        $graph_png = "./qrcode/jpgraph_".self::getRandChar(5).".png";  //输出图像路径
        $graph->Stroke( $graph_png );  //输出图像  
        return $graph_png;
    }


    /**
     * @descs 随机生成授权码
     * @param  $length  随机数长度
    */
    public static function generate_password( $length ) { 
        // 密码字符集，可任意添加你需要的字符 
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
        $password = ""; 
        for ( $i = 0; $i < $length; $i++ ) 
        { 
            // 这里提供两种字符获取方式 
            // 第一种是使用 substr 截取$chars中的任意一位字符； 
            // 第二种是取字符数组 $chars 的任意元素 
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); 
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
        } 
        return $password; 
    } 


}