<?php

use think\facade\Request;
use think\facade\Db;
use app\common\model\Users as UsersModel;

/**
 * @param $value
 * @param $decimal
 * @return string
 */
function formatMoney($value,$decimal=2){
    return sprintf("%.{$decimal}f",$value);
}

/**
 * 写入日志
 * @param $content
 * @param bool $export
 */
function pre($content,$file,$flags=FILE_APPEND){
    file_put_contents($file,var_export($content,true),$flags);
}

/**
 * 订单号
 * @return string
 */
function orderNo(){
    return date("YmdHis") . mt_rand(1, 99999999999);
}

/**
 * 返回用户名称
 * @param $id
 * @return mixed|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getUserName($id){
    $user = UsersModel::where("id",$id)->find();
    if(!empty($user["mobile"])){
        return $user["mobile"];
    }

    if(!empty($user["nickname"])){
        return $user["nickname"];
    }

    return $user["username"]??"未知用户";
}

/**
 * 查找当前分类所有下级分类
 * @param $condition ["pid"=>$id,"status"=>1]
 * @param $res []
 * @return array
 */
function getCategoryChildren($condition,$res=[]){
    $row = Db::name("category")->where($condition)->select()->toArray();
    foreach($row as $val){
        $res[] = $val["id"];
        $res   = array_merge($res,getCategoryChildren(array_merge($condition,["pid"=>$val["id"]])));
    }

    return $res;
}

/**
 * 返回json数据
 * @param string  $msg
 * @param integer $code
 * @param array   $data
 * @return \think\response\Json
 */
function returnAjax($msg="",$code=0,$data=[]) {
    return json(["code"=>$code, "msg"=>$msg, "data"=>$data]);
}

/**
 * 获取服务器IP
 * @param string|null $value
 * @return string the IPv4 address or a string containing the unmodified
 */
function getServerIP($value=null){
    $hostname = empty($value) ? Request::host() : $value;
    return gethostbyname($hostname);
}

/**
 * 对比php版本
 * @param string $version
 * @return bool
 */
function comparePhp($version) {
    return version_compare(PHP_VERSION, $version) >= 0 ? true : false;
}
