package com.lnkj.ln_jq_app;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;

public class MainActivity extends FlutterActivity {

    private static final String CHANNEL = "com.lnkj.ln_jq_app/map";
    private static final String TAG = "MainActivity";

    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 1001;

    private NativeMapView mapView;

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

        // 注册高德地图导航Platform View
        flutterEngine
                .getPlatformViewsController()
                .getRegistry()
                .registerViewFactory(
                        "NativeFirstPage",
                        new NativeMapFactory(this)
                );

        // 设置 Activity 实例到地图
        NativeMapFactory.setActivity(this);
    }

    /**
     * 获取当前系统版本需要申请的权限列表
     */
    private String[] getRequiredPermissions() {
        List<String> permissions = new ArrayList<>();
        // 定位权限是必须的
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);

        // 存储权限处理：Android 13 (API 33) 以下才需要申请 legacy 存储权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        return permissions.toArray(new String[0]);
    }

    /**
     * 检查并申请权限
     */
    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] requiredPermissions = getRequiredPermissions();
            List<String> deniedPermissions = new ArrayList<>();

            for (String permission : requiredPermissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permission);
                }
            }

            if (!deniedPermissions.isEmpty()) {
                ActivityCompat.requestPermissions(
                        this,
                        deniedPermissions.toArray(new String[0]),
                        PERMISSION_REQUEST_CODE
                );
            } else {
                Log.d(TAG, "所有必要权限已授予");
                if (mapView != null) {
                    mapView.startLocation();
                }
            }
        } else {
            if (mapView != null) {
                mapView.startLocation();
            }
        }
    }

    private void requestPermissions() {
        checkAndRequestPermissions();
    }

    public void setMapView(NativeMapView mapView) {
        this.mapView = mapView;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.dispose();
            mapView = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 处理从搜索目的地页面返回的结果
        if (requestCode == 1000 && resultCode == RESULT_OK && data != null) {
            String name = data.getStringExtra(SearchDestinationActivity.EXTRA_RESULT_NAME);
            String address = data.getStringExtra(SearchDestinationActivity.EXTRA_RESULT_ADDRESS);
            double lat = data.getDoubleExtra(SearchDestinationActivity.EXTRA_RESULT_LAT, 0);
            double lon = data.getDoubleExtra(SearchDestinationActivity.EXTRA_RESULT_LON, 0);
            String district = data.getStringExtra(SearchDestinationActivity.EXTRA_RESULT_DISTRICT);

            if (name != null && lat != 0 && lon != 0) {
                // 获取地图实例并设置目的地
                NativeMapView mapView = NativeMapFactory.getMapView();
                if (mapView != null) {
                    mapView.setDestination(name, address, lat, lon, district);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean locationGranted = false;
            for (int i = 0; i < permissions.length; i++) {
                if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permissions[i])
                        && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    locationGranted = true;
                    break;
                }
            }

            if (locationGranted) {
                if (mapView != null) {
                    mapView.startLocation();
                }
            } else {
                // 只有在定位权限确实被拒绝时才弹出提示
                Toast.makeText(this, "请授予应用定位权限以正常使用地图功能", Toast.LENGTH_LONG).show();
            }
        }
    }
}
