<?php
namespace app\controller\api;

use app\model\CouponMain;
use app\model\Slide;
use app\repository\AccountRepository;
use app\repository\BusinessRepository;
use app\repository\CouponRepository;
use app\repository\OperationRepository;
use think\Collection;
use think\Exception;
use think\exception\ValidateException;
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), // 优惠卷类型
            'businessCode'          => $this->request->param('businessCode/s'), // 商家code
            'businessCircleId'      => $this->request->param('businessCircle/d',0), // 商圈id
            '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');


            $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];

            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 (!empty($params['businessCode'])) {
                $whereMap[] =  ['business_code', '=', $params['businessCode']];
            }
            if (($params['businessCircleId']) > 0 ) {
                $whereMap[] =  ['business_circle_id', '=', $params['businessCircleId']];
            }

            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->with(["business"=>function($q){
                        return $q->field("business_subtitle,code");
                    }])->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);

            $accountRepo= AccountRepository::getInstance();

            $accountId = $this->request->user['user_id'] ?? 0;
            $flowArray = [];
            if ($accountId) {
                $account = $accountRepo->findById($accountId, [], function ($q) {
                    return $q->with(['business', 'parent']);
                });
                if (!empty($account)) {
                    $flowArray = $accountRepo->getBusinessFlowCodeArray($account->user_code);
                }
            }
            $time = time();
            $res['list']->each(function ($item) use ($params, $flowArray, $time) {
                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";
                }

                //是否收藏了该优惠券的商家
                $item->isFlow = in_array($item->business_code,$flowArray);

                 $item->couponId            = $item->id;
                 $item->businessCode        = $item->business_code;
                 $item->businessName        =  $item->business_name;
                 $item->cover               =  $this->request->domain().$item->image_url;
                 $item->couponName          =  $item->name;

                //到期状态  到期前7天!!!!!!!!没做完
                $weekTime = 7 * 86400;
                $endTime = strtotime($item->end_time);
                if (($endTime - $time) < $weekTime) {
                    $ExpirationTime = ($endTime - $time) / 86400;
                    $item->expirationTimeStr = "还有" . ceil($ExpirationTime) . "到期";
                } else {
                    $item->expirationTimeStr = '';
                }
            });

            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"]);
    }


    /**
     * 关注/取消关注一个商家
     * */
    public function flowBusiness()
    {
        $accountId = $this->request->user['user_id'] ?? 0;
        $accountRepo = AccountRepository::getInstance();
        try {
            $account = $accountRepo->findById($accountId, [], function ($q) {
                return $q->with(['business', 'parent']);
            });
            if (empty($account)) {
                throw new ValidateException('用户无效！');
            }

            $businessCode = input("businessCode/s");
            $business = BusinessRepository::getInstance()->findOneByWhere(["code"=>$businessCode]);
            if(empty($business)){
                throw new ValidateException('商家无效！');
            }
            $businessFlow = $accountRepo->hasBusinessFlow($account->user_code,$businessCode);

            //如果关注了 就删除
            if($businessFlow){
                $businessFlow->delete();
            }else{
                //没有关注就添加
                $accountRepo->createBusinessFlow($account->user_code,$businessCode,$business->business_name);
            }
            return $this->json();

        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            return $this->json(5001, '服务器繁忙！');
        }
    }


    /**
     * 关注商家的列表
     * */
    public function getFlowBusiness()
    {
        $accountId      = $this->request->user['user_id'] ?? 0;
        $page           = $this->request->param('page/d', 1);
        $size           = $this->request->param('size/d', 10);
        $keyword        = input("keyWord/s");
        $accountRepo = AccountRepository::getInstance();
        try {
            $account = $accountRepo->findById($accountId, [], function ($q) {
                return $q->with(['business', 'parent']);
            });
            if (empty($account)) {
                throw new ValidateException('用户无效！');
            }
            $data = AccountRepository::getInstance()->getBusinessFlowList($account->user_code,$page,$size,$keyword);
            $data["list"]->each(function ($item){
                $item->businessCover = $this->request->domain() . $item->background;
            });
            return $this->json(0,"success",$data);
        }catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            echo $e->getMessage();
            return $this->json(5001, '服务器繁忙！获取用户个人信息失败');
        }

    }
}