package com.example.travelfootprints;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.travelfootprints.databinding.ActivityMainBinding;


public class MainActivity extends AppCompatActivity implements AMapLocationListener {
    private static final String TAG = "MainActivity";
    private ActivityMainBinding binding;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    // 请求权限意图
    private ActivityResultLauncher<String> requestPermission;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestPermission = registerForActivityResult(new ActivityResultContracts.RequestPermission(), result -> {
            // 权限申请结果
            Log.d(TAG, "权限申请结果: " + result);
            showMsg(result ? "已获取到权限" : "权限申请失败");
        });
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // 初始化定位
        initLocation();
        Button button = (Button) findViewById(R.id.reloc);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "onClick: start loc");
                startLocation();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查是否已经获取到定位权限
        if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // 获取到权限
            Log.d(TAG, "onResume: 已获取到权限");
            showMsg("已获取到权限");
        } else {
            // 请求定位权限
            requestPermission.launch(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    private void showMsg(CharSequence str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    private void initLocation() {
        try {
            //初始化定位
            mLocationClient = new AMapLocationClient(getApplicationContext());
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            //初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Device_Sensors，使用GPS
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
            //获取最近3s内精度最高的一次定位结果
            mLocationOption.setOnceLocationLatest(true);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位超时时间，单位是毫秒
            mLocationOption.setHttpTimeOut(6000);
            //允许模拟位置
            mLocationOption.setMockEnable(true);
            //关闭缓存机制
            mLocationOption.setLocationCacheEnable(false);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void startLocation() {
        if (mLocationClient != null) mLocationClient.startLocation();
    }

    private void stopLocation() {
        if (mLocationClient != null) mLocationClient.stopLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        if (aMapLocation == null) {
            showMsg("定位失败，aMapLocation 为空");
            return;
        }
        // 获取定位结果
        if (aMapLocation.getErrorCode() == 0) {
            String result = "定位结果：\n" +
                    "定位类型：" + aMapLocation.getLocationType() + "\n" +
                    "纬度：" + aMapLocation.getLatitude() + "\n" +
                    "经度：" + aMapLocation.getLongitude() + "\n" +
                    "精度信息：" + aMapLocation.getAccuracy() + "\n" +
                    "详细地址：" + aMapLocation.getAddress() + "\n" +
                    "国家信息：" + aMapLocation.getCountry() + "\n" +
                    "省信息：" + aMapLocation.getProvince() + "\n" +
                    "城市信息：" + aMapLocation.getCity() + "\n" +
                    "城区信息：" + aMapLocation.getDistrict() + "\n" +
                    "街道信息：" + aMapLocation.getStreet() + "\n" +
                    "街道门牌号信息：" + aMapLocation.getStreetNum() + "\n" +
                    "城市编码：" + aMapLocation.getCityCode() + "\n" +
                    "地区编码：" + aMapLocation.getAdCode() + "\n" +
                    "AOI信息：" + aMapLocation.getAoiName() + "\n" +
                    "建筑物Id：" + aMapLocation.getBuildingId() + "\n" +
                    "楼层：" + aMapLocation.getFloor() + "\n" +
                    "GPS状态：" + aMapLocation.getGpsAccuracyStatus();

            // 设置结果到 TextView
            binding.tvAddress.setText(result);
            // 停止定位
            Log.d(TAG, "onLocationChanged: "+result);
            stopLocation();
        } else {
            // 定位失败
            showMsg("定位失败，错误：" + aMapLocation.getErrorInfo());
            Log.e(TAG,"location Error, ErrCode:"
                    + aMapLocation.getErrorCode() + ", errInfo:"
                    + aMapLocation.getErrorInfo());
        }
    }
}