<?php
function appExec($module, $class, $action)
{
    S('MODULE', $module);
    S("CONTROLLER", $class);
    S("ACTION", $action);
    S('URL_PATH', "/{$module}/{$class}/{$action}");
    $ctrl = \App::make("\\App\\Http\\Controllers\\" . ucfirst($module) . "\\" . ucfirst($class) . "Controller");
    return \App::call([$ctrl, $action]);
}

/**
 * 计算当前用时
 *
 * @param string $runName
 * @param integer $return
 * @return void
 */
function computeTime($runName='',$return=0,$start=1){
    $curTime= get_millisecond();
    $oldTime=LARAVEL_START;
	$numTime=$curTime-(intval($oldTime)*1000);
	if($return){
		return array('curTime'=>$curTime,'numTime'=>$numTime,'runName'=>$runName);
	}else{
		echo "<pre>执行{$runName} 功能,当前时间为:{$curTime},累积用时: {$numTime}</pre>";
		return;
	}

}
function get_millisecond()
{
    list($usec, $sec) = explode(" ", microtime());
    $msec = round($usec * 1000);
    return $sec . $msec;

} 

//获取当日或指定日期年、月、日、周、季
function GetpartTime($date=''){
    $date = empty($date)?date('Y-m-d',time()):$date;
    $tstr = strtotime($date);
    $t = array();
    $t['year'] = date('Y',$tstr);
    $t['month'] = date('m',$tstr);
    $t['day'] = date('d',$tstr);
    $t['season'] = ceil($t['month']/3);
    /*$time = $t['year'] . '-' . $t['month'];
    $weekday = date('w', strtotime($time));      //获取1号是周几
    if ($weekday == 1) {      //1号是周一
        $firstWeekDay = 7;
    } elseif ($weekday == 0) {      //1号是周日
        $firstWeekDay = 1;
    } else {
        $firstWeekDay = 8 - $weekday;
    }
    $t['week'] = 1 + ceil(($t['day'] - $firstWeekDay) / 7);*/   
    $t['week'] = date('W', $tstr);
    $t['wyear'] = ($t['month']==12 && $t['week']==1)?($t['year']+1):$t['year'];
    return $t;
}

//检测是否有权限，有权限返回True,没有权限false
function checkRriv($code)
{
    if (($re=\App\Models\Role::hasRoot($code)) == 1) {

        return true;
    }
    return false;
}
function arrayToOptions($data, $key, $val)
{
    $options = array();
    if (is_array($data) && count($data)) {
        foreach ($data as $k => $value) {
            $options[$value[$key]] = $value[$val];
        }
    }
    return $options;
}
function arrayToNumber($data, $field = array())
{

    if (is_array($data) && count($data)) {
        foreach ($data as $k => $value) {

            foreach ($value as $key => $v) {
                if (in_array($key, $field)) {
                    $data[$k][$key] = intval(round(floatval($v) * 100)) / 100;
                }
            }
        }
    }
    return $data;
}
function responseToJson($status, $msg = '', $data = '')
{
    $return = array(); //返回数组
    //组装状态码和返回数据
    if ($status < 0) {
        $return['status'] = $status;
        $return['data'] = $data;
    } else {
        if (!is_numeric($status)) {
            $return['data'] = $status;
            $return['status'] = 1;
        } else {
            $return['status'] = $status;
            $return['data'] = $data;
        }
    }
    //组装返回信息
    if (empty($msg)) {
        $return['msg'] = trans('error.' . $return['status']);
    } else {
        $return['msg'] = $msg;
    }
    //返回json数据
    return response()->json($return);
}

/**
 *密码加密码
 */
function GenEncryption()
{
    srand((double) microtime() * 1000000); //create a random number feed.
    $ychar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
    $list = explode(",", $ychar);
    $authnum = "";
    for ($i = 0; $i < 6; $i++) {
        $randnum = rand(0, 61); // 10+26;
        $authnum .= $list[$randnum];
    }
    return $authnum;
}

//密码加密
function GenPassword($password)
{
    $Enc = GenEncryption();
    $Pwd = md5(md5($Enc . $password));
    return array("encryption" => $Enc, "password" => $Pwd);
}

//密码验证
function VerPassword($checkpwd, $enc, $ypwd)
{
    $VerPwd = md5(md5($enc . $checkpwd));
    if ($VerPwd == $ypwd) {
        unset($VerPwd);
        return true;
    } else {
        unset($VerPwd);
        return false;
    }

}
//订单号
function OrderID($prefix = '')
{
    $num = mt_rand(100, 999);
    list($s, $m) = explode(' ', microtime());
    $order = date("YmdHis") . ($s * 1000000) . $num;
    return $prefix . $order;
}
//identity生产
function UUID()
{
    $prefix = '';
    $uuid = '';
    $str = md5(uniqid(mt_rand(), true));
    $uuid = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $prefix . $uuid;
}

function S($key, $value = '')
{
    if (!isset($GLOBALS[$key]) && empty($value)) {
        return -1;
    }
    if (isset($GLOBALS[$key]) && empty($value)) {
        return $GLOBALS[$key];
    }
    return $GLOBALS[$key] = $value;
}
/**
 * 获取客户端真实IP
 */
function GETIP()
{
    global $ip;

    if (getenv("HTTP_CLIENT_IP")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR")) {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (getenv("REMOTE_ADDR")) {
        $ip = getenv("REMOTE_ADDR");
    } else {
        $ip = "Unknow";
    }

    return $ip;

}
function OperationLog($id, $opt, $data)
{
    $data = array(
        'identity' => UUID(),
        'status' => 1,
        'ip' => GETIP(),
        'operation_time' => date('Y-m-d H:i:s', time()),
        'system_identity' => $id,
        'operation' => vsprintf(trans('operation.' . $opt), $data),
    );
    $db = new \App\Models\System_log;
    return $db->insertData($data);
}

function arrayToNum($data, $field = array())
{

    if (is_array($data) && count($data)) {
        foreach ($data as $k => $value) {
            if (in_array($k, $field)) {
                $data[$k] = intval(floatval($value) * 100) / 100;
            }
        }
    }
    return $data;
}

//邮箱中间星号
function emailHide($email)
{
    if (!empty($email)) {
        $arr = explode('@', $email);
        if (is_array($arr)) {
            $rest = substr($arr[0], 2, -2);
            $arr[0] = str_replace($rest, str_repeat('*', strlen($rest)), $arr[0]);
            $email = implode('@', $arr);
        }
    }
    return $email;
}
//手机中间星号
function phoneHide($phone)
{
    if (!empty($phone)) {
        $phone = substr_replace($phone, '****', 3, 4);
    }
    return $phone;
}
//用户名中间星号
function userHide($user_name)
{
    $len = strlen($user_name) / 2;
    return substr_replace($user_name, str_repeat('*', $len), ceil(($len) / 2), $len);
}
//银行卡号中间星号
function bankHide($bank)
{
    //截取银行卡号前4位
    $prefix = substr($bank, 0, 4);
    //截取银行卡号后4位
    $suffix = substr($bank, -4, 4);
    $maskBankCardNo = $prefix . " ************ " . $suffix;
    return $maskBankCardNo;
}
function toLog($data){
    file_put_contents();
}
//生成token
function createToken(){
    $enc = GenEncryption();
    $time = time();
    $token = substr(uniqid($enc . $time), 0, 35);
    return $token;
}
//更新token
function refreshToken($admin_id){
    $db=new \App\Models\System_user;
    $token=createToken();
    $res=$db->refreshToken($admin_id,$token);
    if($res>0){
        return $token;
    }
    return $res;
}
//检测token
function checkToken($admin_id,$token){
    $db=new \App\Models\System_user;
    return $db->checkToken($admin_id,$token);
}

//保留小数位数
function  floatPointDigit($data,$long=2){
    $long = intval($long) ;
    $for1 = "%.".$long."f" ;
    $for2 = "%.".($long+1)."f" ;
    return  sprintf($for1,substr(sprintf($for2, $data), 0, -1));
}


