<?php
namespace app\controller\api;

use app\model\CouponMain;
use app\model\Slide;
use app\repository\CouponRepository;
use app\repository\OperationRepository;
use think\Collection;
use think\response\Json;

/**
 * 消费者端:游客、普通用户
 *
 * Class Consumer
 * @package app\controller\api
 */
class Consumer extends Base
{
    protected $noNeedLogin = [
        'home',
        'bannerList',
    ];

    /**
     * 获取附近商家发布的优惠卷
     * @return Json
     */
    public function home()
    {
        $params = [
            'businessType'  => $this->request->param('businessType/d', 0), // 商家类型
            'couponType'    => $this->request->param('couponType/d', 0), // 优惠卷类型
            'dis'           => $this->request->param('dis/d', -1), // 距离,单位为km
            'lng'           => $this->request->param('lng/f', 0), // 经度 104.752890
            'lat'           => $this->request->param('lat/f', 0), // 纬度 31.465040
            'keyword'       => $this->request->param('key/s', ''), // 关键词查询
            'page'          => $this->request->param('page/d', 1),
            'size'          => $this->request->param('size/d', 10),
        ];


        try {
            $repo   = CouponRepository::getInstance();
            $nowDate    = date('Y-m-d H:i:s');
            $sumPoint   = $params['lng'] + $params['lat'];

            $lngRange   = [];
            $latRange   = [];
            $whereMap   = [];
            $sortOrder  = ['square'=> 'asc', 'start_time'=>'asc'];

//            $whereMap[] = ['status', '=', CouponMain::status_on];
//            $whereMap[] = ['on_shelf', '=', CouponMain::on_shelf_on];
//            $whereMap[] = ['start_time', '> TIME', $nowDate];
//            $whereMap[] = ['end_time', '< TIME', $nowDate];
//            $whereMap[] = ['using_count', '>', 0];
            $whereMap[] = ['id', '>', 300];

            if (!empty($params['keyword'])) {
                $whereMap[] = ['name', 'like', "%{$params['keyword']}%"];
            }
            if ($params['businessType'] > 0) {
                $whereMap[] = ['business_type', '=', $params['businessType']];
            }
            if ($params['couponType'] > 0) {
                $whereMap[] = ['type', '=', $params['couponType']];
            }

            if ($params['dis'] > 0) {
                $pointList = getEarthSquareRangePoint($params['lat'],$params['lng'], $params['dis']);
                $latRange[]   = ['lat', 'BETWEEN', [$pointList['lat_min'], $pointList['lat_max']]];
                if (abs($pointList['cur_lng'] - $pointList['lng_min']) != $pointList['dis_lng'] && $pointList['lng_min'] < 0) {
                    $lngRange[] = ['lng', 'BETWEEN' , [-180, $pointList['lng_min']]];
                    $lngRange[] = ['lng', 'BETWEEN' , [($pointList['cur_lng'] - $pointList['dis_lng']), 180]];
                } else {
                    $lngRange[] = ['lng', 'BETWEEN' , [$pointList['lng_min'], $pointList['lng_max']]];
                }
            }

            $res    = $repo->findCouponMainList($whereMap, [], $params['page'], $params['size'], function ($q) use($lngRange, $latRange, $params) {
                    return $q->when(!empty($lngRange) && !empty($latRange), function($query) use($lngRange, $latRange){
                        $query->where(function ($queryB) use($lngRange) {
                            $queryB->whereOr($lngRange);
                        })->where($latRange);
                    })
                    ->field("*, abs( (IFNULL(lat,0) - {$params['lat']})  *  (IFNULL(lng,0) - {$params['lng']})  ) as square");
            }, $sortOrder);


            $res['list']->each(function ($item)use($params){
                unset($item->square);
                $distance = (get_distance($params["lat"], $params["lng"], $item["lat"],$item["lng"]));
                if ($distance >= 1000) {
                    $item->distance_text = round($distance / 1000, 2) . "km";
                } else {
                    $item->distance_text = $distance . "m";
                }

            });

            return $this->json(0, 'success', $res);
        } catch (\Exception $e) {
            return $this->json(0, 'success', [
                "total" => 0,
                "current" => $params['page'],
                "size" => $params['size'],
                "list" => new Collection()
            ]);
        }

    }

    /**
     * banner列表
     * */
    public function bannerList()
    {
        $repo       = OperationRepository::getInstance();
        $whereMap   = [];
        $orders     = ['sort'=>'asc'];
        $page       = input("page/d",1);
        $size       = input("size/d",1000);
        $whereMap[] = ['position', '=', Slide::homePosition];
        $list = $repo->slideList($whereMap, ["id","title","src as image","url","url_type as type"], $page, $size, function ($q){
            return $q->withAttr("image",function ($value){
                return $this->request->domain() . $value;
            });
        }, $orders);
        return $this->json(1,"ok",$list["list"]);
    }
}