<?php
/**
 * @Created by PhpStorm
 * @author: Kirin
 * @day: 2024/11/20
 * @time: 11:24
 */

namespace app\common;


use app\Request;
use Joypack\Tencent\Map\Bundle\Location;
use Joypack\Tencent\Map\Bundle\LocationOption;
use qiniu\basic\BaseController;

abstract class ApiBaseController extends BaseController
{


    /**
     * 当前登陆用户信息
     * @var
     */
    protected $userInfo;

    /**
     * 当前登陆用户ID
     * @var
     */
    protected $uid;

    protected $service = null;

    /**
     * 初始化
     */

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->initialize();
    }

    protected function initialize()
    {
        $this->uid = $this->request->uid();
        $this->userInfo = $this->request->user();
    }

    /**
     * @return array
     */
    public function getAddress(): array
    {
        list($latitude, $longitude) = $this->request->location();
        $address = $this->geoLbscoder($latitude, $longitude);
        if ($address) {
            return [
                'address' => $address['address_component'],
                'formatted_addresses' => $address['formatted_addresses'],
                'info' => $address['ad_info'],
            ];
        }
        return [];
    }

    /**
     * 经纬度反向解析地址
     * @param string $latitude
     * @param string $longitude
     * @return mixed|null
     */
    private function geoLbscoder(string $latitude, string $longitude)
    {
        if (!$latitude || !$longitude) {
            return null;
        }
        $mapKey = sys_config('tengxun_map_key');
        $mapKSecret = sys_config('tengxun_map_secret', '');
        if (!$mapKSecret) $mapKSecret = null;
        if (!$mapKey) {
            return null;
        }
        try {
            $locationOption = new LocationOption($mapKey, $mapKSecret);
            $locationOption->setLocation($latitude, $longitude);
            $location = new Location($locationOption);
            $res = $location->request();
            if ($res->error) {
                return null;
            }
            if ($res->status) {
                return null;
            }
            if (!$res->result) {
                return null;
            }
            return $res->result;
        } catch (\Throwable $e) {
            return null;
        }
    }
}