<?php
namespace Api\Model;

use Think\Model;

header("Content-Type:text/html;CharSet=UTF-8");
class StoresModel extends Model
{
    /**
     * 商家列表
     * @param int $county_id 区ID
     * @return array
     */
    public function inRadius($county_id)
    {
        $data = array();
        // 区下所有商家
        $list = $this
            ->where("`county_id`={$county_id} AND `status`=1")
            ->select();
        // 抽取位于有效范围内的商家
        foreach ($list as $key => $value) {
            $distance = getDistance($_GET['lat'], $_GET['lng'], $value['lat'], $value['lng']);
            $value['logo'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $value['logo'];
            file_put_contents("./Logs/distance.log", $distance);
            $row = M("setStore")->find();
            $radius = $row['radius'];    // 获取后台设置的有效半径
            if ($distance < $radius) {
                $value['distance'] = $distance;
                array_push(
                    $data,
                    $value
                );
            }
        }
        // 距离排序
        usort($data, array($this, "sortByDistance"));
        // 返回排序后的商家数组
        file_put_contents("./Logs/inRadius.log", "finished");
        return $data;
    }

    /**
     * 距离排序规则
     * @param  array $a 上元素
     * @param  array $b 下元素
     * @return int      -1.小于 0.等于 1.大于
     */
    public function sortByDistance($a, $b)
    {
        if ($a['distance'] > $b['distance']) {
            return 1;
        } elseif ($a['distance'] == $b['distance']) {
            return 0;
        } elseif ($a['distance'] < $b['distance']) {
            return -1;
        }
    }
}