<?php
// 应用公共文件
use app\model\Website;
use Curl\Curl;
/**
 * 随机数
 */
if (!function_exists('generateRandom')) {

    function generateRandom($length = 8) {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";//大小写字母以及数字
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }
}

/**
 * 读取网站配置
 */
if (!function_exists('getWebsite')) {

    function getWebsite() {
        $website = cache('website');
        if (is_null($website)) {
            $website = Website::select()->pop();
            $website = $website ?? [];
        }
        return $website;
    }
}

if (!function_exists('setConfig')) {
    /**
     * 修改config的函数
     * @param $arr1 配置前缀
     * @param $arr2 数据变量
     * @return bool 返回状态
     */
    function setConfig($values, $name) {
        /**
         * 原理就是 打开config配置文件 然后使用正则查找替换 然后在保存文件.
         * 传递的参数为2个数组 前面的为配置 后面的为数值.  正则的匹配为单引号  如果你的是分号 请自行修改为分号
         * $pat[0] = 参数前缀;  例:   default_return_type
         * $rep[0] = 要替换的内容;    例:  json
         */
        if (is_array($values)) {

            $pats = [] ;
            $reps = [] ;
            $i = 0 ;
            foreach($values as $key=>$value){

                if(is_array($value) ){
                    $pats[$i] = '/\'' . $key . '\'(.|\n)*?],/';
                    $v = var_export($value,true);
                    $v = preg_replace(['/array(.*?)\(/','/\)/'],['[',']'],$v);
                    $reps[$i] = "'" . $key . "'" . "=>" .  $v . ",";
                }else{
                    $pats[$i] = '/\'' . $key . '\'(.*?),/';
                    $reps[$i] = "'" . $key . "'" . "=>" . "'" . $value . "',";
                }
                $i++;
            }
            $fileurl = config_path() . $name . ".php";
            $string = file_get_contents($fileurl);//加载配置文件
            $string = preg_replace($pats, $reps, $string);// 正则查找然后替换
            file_put_contents($fileurl, $string);// 写入配置文件
            return true;
        } else {
            return false;
        }
    }
}

// 获取当前时间戳
if( !function_exists('getCurrentTime') ){

    function getCurrentTime( $time = '' ){
        return $time ? strtotime($time) : time();
    }
}

if( !function_exists('getCurrentMicrotime') ){
    function getCurrentMicrotime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (int)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
}

if( !function_exists('getCurrentDate') ){

    function getCurrentDate($time = '') {
        if( $time ){
            $time = getCurrentTime() ;
        }
        return date('Y-m-d h:i:s',$time);
    }
}

if( !function_exists('removeFile')){

    function removeFile($path){
        if( !file_exists($path) ){
            return false ;
        }
        if( !is_file($path) ){
            return false ;
        }
        unlink($path) ;
        return true ;
    }
}

if( !function_exists('getFileAccessPath') ){
    function getFileAccessPath($path){
        return "".$path ;
    }
}

if( !function_exists('getFilePath') ){
    function getFilePath($path,$full=false){
        $root = config('filesystem.disks.public')['root'] ;
        if( !$full ){
            $root = str_replace(app()->getRootPath(),'',$root) ;
        }
        return $root.'/'.$path ;
    }
}

if( !function_exists('moveFile') ){

    function moveFile($path,$movePath){

        $filename = '';

        if( strstr($movePath,'.') === false ){
            return false ;
        }

        $temp = explode('/',$movePath);
        $filename = array_pop($temp) ;
        $movePath = implode('/',$temp) ;

        if(!file_exists($movePath)){
            mkdir($movePath,0777,true);
        }
        if( !file_exists($path) ){
            //mkdir($path,0777,true);
            return '路径不存在';
        }
        return rename($path,$movePath.'/'.$filename);
    }
}

if( !function_exists('api') ){
    function api($url,$method='get',$data=[],$params=[]){

        $curl = new Curl();
        $url = str_replace(" ",'+',$url) ;
        $curl->setOpt(CURLOPT_ENCODING, "gzip");
        $curl->setOpt(CURLOPT_RETURNTRANSFER, 1);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $curl->setOpt(CURLOPT_SSL_VERIFYHOST, false);

        if( isset( $params['referer'] ) ){
            $curl->setReferer($params['referer']);
        }
        if( isset( $params['cookie'] ) ){
            $curl->setOpt(CURLOPT_COOKIE,$params['cookie']);
        }
//        $curl->setOpt(  CURLOPT_USERAGENT,'');

        $curl->setUserAgent('Mozilla/5.0 (Linux; Android 4.4.2; NoxW Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36');

        $curl->{$method}($url,$data);

        if( $curl->error ){
            return false ;
        }

        $response = $curl->getResponse();
        $curl->close();

        return $response ;
    }
}

if( !function_exists('createOutFileUrl') ){
    function createOutFileUrl($url = ''){
        return empty( $url )  ?  $url : ( request()->domain() .'/storage/' . $url ) ;
    }
}



