<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

// 应用公共函数库文件

/**
 * 获取当前访问的渠道(微信小程序、H5、APP等)
 * @return string|null
 */
function getPlatform(): ?string
{
    static $value = null;
    // 从header中获取 channel
    empty($value) && $value = request()->header('platform');
    // 调试模式下可通过param中获取
    if (is_debug() && empty($value)) {
        $value = request()->param('platform');
    }
    return $value;
}


/**
 * 计算用户和门店距离
 * @param float $lat1 用户纬度
 * @param float $lon1 用户经度
 * @param float $lat2
 * @param float $lon2
 * @return float
 */
function calculateDistance($lat1, $lon1, $lat2, $lon2): float
{
    // 将角度转换为弧度
    $degToRad = M_PI / 180;

    // 经纬度转换成弧度
    $lat1 *= $degToRad;
    $lon1 *= $degToRad;
    $lat2 *= $degToRad;
    $lon2 *= $degToRad;

    // 应用Haversine Formula计算球体上两点之间的距离
    $dLat = ($lat2 - $lat1);
    $dLon = ($lon2 - $lon1);
    $a = pow(sin($dLat/2), 2) + cos($lat1) * cos($lat2) * pow(sin($dLon/2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $distance = 6371 * $c; // 地球平均半径为6371km

    return round($distance, 2); // 返回结果保留小数点后两位
}

/**
 * 格式化起止时间(为了兼容前端RangePicker组件)
 * 2020-04-01T08:15:08.891Z => 1585670400
 * @param array $times
 * @param bool $isWithTime 是否包含时间
 * @return array
 */
function between_time(array $times, bool $isWithTime = false): array
{
    foreach ($times as &$time) {
        $time = trim($time, '&quot;');
        $time = str2date($time, $isWithTime);
    }
    return ['start_time' => current($times), 'end_time' => next($times)];
}

/**
 * 日期转换时间戳
 * 例如: 2020-04-01 08:15:08 => 1585670400
 * @param string $date
 * @param bool $isWithTime 是否包含时间
 * @return false|int
 */
function str2date(string $date, bool $isWithTime = false)
{
    if (!$isWithTime) {
        $date = date('Y-m-d', strtotime($date));
    }
    return strtotime($date);
}