<?php

namespace app\model;

use think\facade\Db;

/**
 * 工地表
 *
 * Class Worksite
 * @package app\model
 */
class Worksite extends Base
{
    public const STATUS_NO  = 0;//禁用
    public const STATUS_YES = 1;//正常

    public static function statusText(): array
    {
        return [
            self::STATUS_NO => '禁用',
            self::STATUS_YES  => '正常',
        ];
    }
    // 获取指定距离内由近及远的N条记录

    /**
     * @param  string  $lng  经度
     * @param  string  $lat  维度
     * @param  float|int  $area  距离 单位米 默认500
     * @param  int  $limit  条数
     * @return mixed
     */
    public static function getListByDistance(string $lng, string $lat, float $area = 500, int $limit = 10)
    {
        $sql = 'SELECT
                    `id`,
                    `name`,
                    `lat`,
                    `lng`,
                    st_distance ( point ( lng, lat ), point ( :lng, :lat ) )* 111195 AS distance 
                FROM
                    bee_worksite 
                HAVING
                    distance <= :area 
                ORDER BY
                    distance
                LIMIT :limit
                ';

        return Db::query($sql, ['lng' => $lng, 'lat' => $lat, 'area' => $area, 'limit' => $limit]);
    }

    // 获取指定范围内最近工地

    /**
     * 获取所在工地 默认按指定范围搜索最近
     *
     * @param  string  $lng  经度
     * @param  string  $lat  维度
     * @param  float|int  $area  范围 米 默认500
     * @return array|mixed
     */
    public static function getNearest(string $lng, string $lat, float $area = 500)
    {
        $sql = 'SELECT
                    `id`,
                    `name`,
                    `lat`,
                    `lng`,
                    st_distance ( point ( lng, lat ), point ( :lng, :lat ) )* 111195 AS distance 
                FROM
                    bee_worksite 
                HAVING
                    distance <= :area 
                ORDER BY
                    distance
                LIMIT 1
                ';

        $res = Db::query($sql, ['lng' => $lng, 'lat' => $lat, 'area' => $area]);
        return $res[0] ?? [];
    }

    public static function list()
    {
        return self::order('sort', 'desc')->order('id', 'desc')->column('name', 'id');
    }
}
