<?php
namespace app\controller\api;

use app\exception\RepositoryException;
use app\repository\BusinessRepository;
use app\repository\CouponRepository;
use app\repository\DictionaryRepository;
use think\facade\Config as CConfig;
use think\response\Json;
use app\model\{Business as BusinessModel, BusinessCircle, Member};

/**
 * APP 数据字典
 *
 * Class Dictionary
 * @package app\controller\api
 */
class Dictionary extends Base
{
    protected $noNeedLogin = [
        'getDistanceList',
        'getBusinessCircle',
        'getAgencyList',
        'getBusinessTypeList',
        'getCouponTypeList',
        'screen',
    ];

    /**
     * 获取距离(distance)列表
     * @return Json
     */
    public function getDisList(): Json
    {
        $list = [
            ['id' => 1, 'name'=> "1km", 'value' => 1],
            ['id' => 3, 'name'=> "3km", 'value' => 3],
            ['id' => 5, 'name'=> "5km", 'value' => 5],
            ['id' => 10, 'name'=> "10km", 'value' => 10],
        ];

        return $this->json(0, 'success', $list);
    }

    /**
     * 获取商圈列表
     * @return Json
     */
    public function getBusinessCircle(): Json
    {
        $lng                   = $this->request->param('lng/f', 0); // 经度 104.752890
        $lat                   = $this->request->param('lat/f', 0); // 纬度 31.465040
        $field = ["*"];
        $order = [];

        if ($lng && $lat) {
            $field[] = "abs( (IFNULL(lat,0) - {$lat})  *  (IFNULL(lng,0) - {$lng})  ) as square";
            $order["square"] = "asc";
        }

        $order["sort"] = "desc";
        $order["id"]    = "desc";

        $items = DictionaryRepository::getInstance()->getAllBusinessCircleList($field,$order);
        $items->each(function ($item)use($lat,$lng) {
            $areaText = '';
            if (!empty($item['province_text'])) {
                $areaText = $item['province_text'].'·';
            }
            if (!empty($item['city_text']) && $item['city_text'] != '市辖区') {
                $areaText .=  $item['city_text'].'·';
            }
            if (!empty($item['county_text'])) {
                $areaText .=  $item['county_text'];
            }

            $item['name_text'] = $item['name'];
            if (!empty($areaText)) {
                $item['name_text'] = $item['name'] . '「'.$areaText.'」';
            }

            if($lng && $lat){
                $distance =  get_distance($lat,$lng,$item['lat'],$item['lng']);
                if ($distance >= 1000) {
                    $distance = round($distance/1000,2)."km";
                }else{
                    $distance .= "m";
                }
                $item['distance_text'] = $distance;
            }else{
                $item['distance_text'] = '';
            }

            return $item;
        });
        return $this->json(0, 'success', $items);
    }

    /**
     * 获取代理机构(代理商)关联的商家列表
     * (来源商家表中的代理商)
     *
     * $size 0 表示不分页,获取所有数据
     *
     */
    public function getAgencyList(): Json
    {
        try {
            $data =  Member::getAgentAll();
            return $this->json(0 , 'success', $data);
        } catch (RepositoryException | \Exception $e) {
            return $this->json(0 , 'success', []);
        }
    }

    /**
     * 获取商家分类
     */
    public function getBusinessTypeList(): Json
    {
        $pid    = $this->request->param('pid/d', 0);

        $whereMap   = [];
        if ($pid > 0) {
            $whereMap[] = ['pid', '=', $pid];
        }

        $repo       = DictionaryRepository::getInstance();
        $items      = $repo->getBusinessTypeList($whereMap, [], null, ['pid'=>'asc']);

        $list       = $items->toArray();
        $list       = $repo->recursionChildrenList($list, $pid, 'pid', 'id');

        return $this->json(0, 'success', $list);
    }

    /**
     * 获取优惠卷类型列表
     * @return Json
     */
    public function getCouponTypeList(): Json
    {
        $items = CouponRepository::getInstance()->getCouponTypeAll(['id', 'name'],['id'=>'asc']);
        return $this->json(0, 'success', $items);
    }


    /**
     * 商圈大屏
     * */
    public function screen()
    {
        $id = input("id/d",0);
        $business_circle =  BusinessCircle::findOne([["id","=",$id]]);
        if(empty($business_circle)){
            return $this->json(4001,"商圈不存在");
        }

        $couponMain = CouponRepository::getInstance()->screen($id);



        CConfig::load('extra/wechat', 'wechat');
        $screenTopBanner = config('wechat')['screenTopBanner']??"/static/images/screenTopBanner.jpg";

        return view('/page/screen')->assign(["couponMain"=>json_encode($couponMain),"screenTopBanner"=>($screenTopBanner)]);

    }

}