package com.tencent.example.location;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.tencent.map.geolocation.TencentGeofence;
import com.tencent.map.geolocation.TencentGeofenceManager;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.MapView;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CircleOptions;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.LatLngBounds;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.maps.model.Polygon;
import com.tencent.tencentmap.mapsdk.maps.model.PolygonOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地理围栏测试 Activity
 * 功能：
 * 1. 添加行政区划围栏，在地图上绘制边界
 * 2. 添加圆形围栏，在地图上绘制圆形
 * 3. 监听围栏事件（进入、离开、停留）
 */
public class DemoGeofenceActivity extends AppCompatActivity {
    private static final String TAG = "DemoGeofenceActivity";
    private static final String ACTION_TRIGGER_GEOFENCE = "com.tencent.example.location.GEOFENCE_EVENT";

    // UI 组件
    private MapView mMapView;
    private TencentMap mTencentMap;
    private TextView mTextStatus;
    private Button mBtnAddDistrict;
    private Button mBtnAddCircle;
    private Button mBtnAddPolygon;
    private Button mBtnRemoveFence;
    private Button mBtnClearFences;
    private Button mBtnStartLocation;
    private Button mBtnStopLocation;
    
    // 定位和围栏管理器
    private TencentLocationManager mLocationMgr;
    private TencentGeofenceManager mGeofenceManager;
    private GeofenceReceiver mGeofenceReceiver;
    
    // PendingIntent requestCode 计数器，避免多个围栏共用同一个 PendingIntent
    private int mPendingIntentRequestCode = 0;
    
    // 地图覆盖物
    private Map<String, Polygon> mPolygonMap = new HashMap<>();
    private Map<String, com.tencent.tencentmap.mapsdk.maps.model.Circle> mCircleMap = new HashMap<>();
    private Marker mCurrentLocationMarker;
    
    // 当前位置
    private LatLng mCurrentLocation;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_geofence);
        TencentMapInitializer.setAgreePrivacy(true);   // 同意隐私协议
        TencentLocationManager.setUserAgreePrivacy(true);
        initViews();
        initMap(savedInstanceState);
        initGeofenceManager();
    }
    
    private void initViews() {
        mMapView = findViewById(R.id.mapview_geofence);
        mTextStatus = findViewById(R.id.text_status);
        mBtnAddDistrict = findViewById(R.id.btn_add_district);
        mBtnAddCircle = findViewById(R.id.btn_add_circle);
        mBtnAddPolygon = findViewById(R.id.btn_add_polygon);
        mBtnRemoveFence = findViewById(R.id.btn_remove_fence);
        mBtnClearFences = findViewById(R.id.btn_clear_fences);
        mBtnStartLocation = findViewById(R.id.btn_start_location);
        mBtnStopLocation = findViewById(R.id.btn_stop_location);
        
        // 设置按钮监听
        mBtnAddDistrict.setOnClickListener(v -> showAddDistrictDialog());
        mBtnAddCircle.setOnClickListener(v -> showAddCircleDialog());
        mBtnAddPolygon.setOnClickListener(v -> showAddPolygonDialog());
        mBtnRemoveFence.setOnClickListener(v -> showRemoveFenceDialog());
        mBtnClearFences.setOnClickListener(v -> clearAllFences());
        mBtnStartLocation.setOnClickListener(v -> startLocation());
        mBtnStopLocation.setOnClickListener(v -> stopLocation());
    }
    
    private void initMap(Bundle savedInstanceState) {
        mTencentMap = mMapView.getMap();
        // 设置地图初始位置（北京天安门）
        LatLng beijing = new LatLng(39.9042, 116.4074);
        mTencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(beijing, 12));
        
        // 启用定位图层
        mTencentMap.setMyLocationEnabled(true);
    }
    
    private void initGeofenceManager() {
        mGeofenceManager = new TencentGeofenceManager(this);

        // 注册广播接收器
        mGeofenceReceiver = new GeofenceReceiver();
        IntentFilter filter = new IntentFilter(ACTION_TRIGGER_GEOFENCE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(mGeofenceReceiver, filter, Context.RECEIVER_EXPORTED);
        } else {
            registerReceiver(mGeofenceReceiver, filter);
        }
    }
    
    /**
     * 显示添加行政区划围栏对话框
     */
    private void showAddDistrictDialog() {
        // 创建输入框
        final EditText editText = new EditText(this);
        editText.setHint("请输入行政区划名称或Adcode，如：北京市、110101");
        editText.setText("北京市");
        editText.setPadding(50, 30, 50, 30);
        
        new AlertDialog.Builder(this)
                .setTitle("添加行政区划围栏")
                .setMessage("请输入行政区划关键词")
                .setView(editText)
                .setPositiveButton("添加", (dialog, which) -> {
                    String keyword = editText.getText().toString().trim();
                    if (keyword.isEmpty()) {
                        Toast.makeText(this, "请输入行政区划名称", Toast.LENGTH_SHORT).show();
                    } else {
                        addDistrictFence(keyword);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 添加行政区划围栏
     */
    private void addDistrictFence(String keyword) {
        updateStatus("正在添加行政区划围栏: " + keyword);
        
        // 创建行政区划围栏
        final String baseTag = "district_" + keyword + "_" + System.currentTimeMillis();
        TencentGeofence geofence = new TencentGeofence.Builder()
                .setDistrictRegion(keyword)
                .setTag(baseTag)
                .setExpirationDuration(24 * 60 * 60 * 1000)  // 24小时
                .build();

        // 创建 PendingIntent（用于进出事件和成功/失败回调）
        Intent intent = new Intent(ACTION_TRIGGER_GEOFENCE);  // 使用 CODE_ACTION 接收成功/失败回调
        intent.setPackage("com.tencent.example.location");
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_MUTABLE;
        }
        intent.putExtra("KEY_GEOFENCE_ID", geofence.getTag());
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, mPendingIntentRequestCode++, intent, flags);
        
        // 添加围栏（无返回值）
        mGeofenceManager.addFence(geofence, pendingIntent);
        updateStatus("围栏添加请求已发送: " + keyword);
        
        // 注意：行政区划围栏数据是异步获取的
        // 延迟绘制，等待异步请求完成（通常1-2秒）
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
            drawDistrictFence(baseTag);
        }, 2000);
    }
    
    /**
     * 显示添加圆形围栏对话框
     */
    private void showAddCircleDialog() {
        if (mCurrentLocation == null) {
            Toast.makeText(this, "请先开启定位获取当前位置", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建输入框
        final EditText editText = new EditText(this);
        editText.setHint("请输入半径（米）");
        editText.setText("500");
        editText.setInputType(android.text.InputType.TYPE_CLASS_NUMBER | android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editText.setPadding(50, 30, 50, 30);
        
        new AlertDialog.Builder(this)
                .setTitle("添加圆形围栏")
                .setMessage("在当前位置创建圆形围栏\n经度: " + String.format("%.6f", mCurrentLocation.latitude) 
                        + "\n纬度: " + String.format("%.6f", mCurrentLocation.longitude))
                .setView(editText)
                .setPositiveButton("添加", (dialog, which) -> {
                    String radiusStr = editText.getText().toString().trim();
                    if (radiusStr.isEmpty()) {
                        Toast.makeText(this, "请输入半径", Toast.LENGTH_SHORT).show();
                    } else {
                        try {
                            float radius = Float.parseFloat(radiusStr);
                            if (radius <= 0 || radius > 100000) {
                                Toast.makeText(this, "半径范围应在 0-100000 米之间", Toast.LENGTH_SHORT).show();
                            } else {
                                addCircleFence(radius);
                            }
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 添加圆形围栏
     */
    private void addCircleFence(float radius) {
        updateStatus("正在添加圆形围栏: 半径 " + radius + "米");
        
        // 创建圆形围栏
        TencentGeofence geofence = new TencentGeofence.Builder()
                .setTag("circle_" + System.currentTimeMillis())
                .setCircularRegion(mCurrentLocation.latitude, 
                                  mCurrentLocation.longitude, 
                                  radius)
                .setExpirationDuration(24 * 60 * 60 * 1000)  // 24小时
                .build();

        // 创建 PendingIntent（用于进出事件和成功/失败回调）
        Intent intent = new Intent(ACTION_TRIGGER_GEOFENCE);  // 使用 CODE_ACTION 接收成功/失败回调
        intent.setPackage("com.tencent.example.location");
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_MUTABLE;
        }
        intent.putExtra("KEY_GEOFENCE_ID", geofence.getTag());
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, mPendingIntentRequestCode++, intent, flags);

        // 添加围栏（无返回值）
        mGeofenceManager.addFence(geofence, pendingIntent);
        updateStatus("圆形围栏添加成功");
        
        // 立即绘制圆形围栏（圆形围栏数据是同步的）
        drawCircleFence(geofence);
    }
    
    /**
     * 显示添加多边形围栏对话框
     */
    private void showAddPolygonDialog() {
        // 创建输入框
        final EditText editText = new EditText(this);
        editText.setHint("输入经纬度坐标，格式：lat1,lng1;lat2,lng2;lat3,lng3");
        editText.setText("39.9042,116.4074;39.9142,116.4174;39.9042,116.4274");
        editText.setPadding(50, 30, 50, 30);
        editText.setLines(4);
        editText.setMaxLines(6);
        
        new AlertDialog.Builder(this)
                .setTitle("添加多边形围栏")
                .setMessage("请输入多边形顶点坐标（至少3个点）\n格式：纬度,经度;纬度,经度;...")
                .setView(editText)
                .setPositiveButton("添加", (dialog, which) -> {
                    String coordsStr = editText.getText().toString().trim();
                    if (coordsStr.isEmpty()) {
                        Toast.makeText(this, "请输入坐标", Toast.LENGTH_SHORT).show();
                    } else {
                        try {
                            List<TencentGeofence.FencePoint> points = parsePolygonCoordinates(coordsStr);
                            if (points.size() < 3) {
                                Toast.makeText(this, "多边形至少需要3个顶点", Toast.LENGTH_SHORT).show();
                            } else {
                                addPolygonFence(points);
                            }
                        } catch (Exception e) {
                            Toast.makeText(this, "坐标格式错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .setNeutralButton("使用当前位置", (dialog, which) -> {
                    if (mCurrentLocation == null) {
                        Toast.makeText(this, "请先开启定位", Toast.LENGTH_SHORT).show();
                    } else {
                        // 在当前位置周围创建一个矩形
                        addPolygonFenceAroundCurrentLocation();
                    }
                })
                .show();
    }
    
    /**
     * 解析多边形坐标字符串
     */
    private List<TencentGeofence.FencePoint> parsePolygonCoordinates(String coordsStr) throws Exception {
        List<TencentGeofence.FencePoint> points = new ArrayList<>();
        String[] coords = coordsStr.split(";");
        
        for (String coord : coords) {
            coord = coord.trim();
            if (coord.isEmpty()) continue;
            
            String[] latLng = coord.split(",");
            if (latLng.length != 2) {
                throw new Exception("坐标格式错误，应为：纬度,经度");
            }
            
            double lat = Double.parseDouble(latLng[0].trim());
            double lng = Double.parseDouble(latLng[1].trim());
            
            if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
                throw new Exception("坐标值超出范围");
            }
            
            points.add(new TencentGeofence.FencePoint(lat, lng));
        }
        
        return points;
    }
    
    /**
     * 在当前位置周围添加矩形围栏
     */
    private void addPolygonFenceAroundCurrentLocation() {
        double offset = 0.005; // 约500米
        List<TencentGeofence.FencePoint> points = new ArrayList<>();
        
        // 创建一个矩形（4个顶点）
        points.add(new TencentGeofence.FencePoint(
                mCurrentLocation.latitude + offset, 
                mCurrentLocation.longitude - offset));
        points.add(new TencentGeofence.FencePoint(
                mCurrentLocation.latitude + offset, 
                mCurrentLocation.longitude + offset));
        points.add(new TencentGeofence.FencePoint(
                mCurrentLocation.latitude - offset, 
                mCurrentLocation.longitude + offset));
        points.add(new TencentGeofence.FencePoint(
                mCurrentLocation.latitude - offset, 
                mCurrentLocation.longitude - offset));
        
        addPolygonFence(points);
    }
    
    /**
     * 添加多边形围栏
     */
    private void addPolygonFence(List<TencentGeofence.FencePoint> points) {
        updateStatus("正在添加多边形围栏，顶点数: " + points.size());
        
        // 创建多边形围栏
        TencentGeofence geofence = new TencentGeofence.Builder()
                .setTag("polygon_" + System.currentTimeMillis())
                .setPolygonRegion(points)
                .setExpirationDuration(24 * 60 * 60 * 1000)  // 24小时
                .build();

        // 创建 PendingIntent（用于进出事件和成功/失败回调）
        Intent intent = new Intent(ACTION_TRIGGER_GEOFENCE);  // 使用 CODE_ACTION 接收成功/失败回调
        intent.setPackage("com.tencent.example.location");
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_MUTABLE;
        }
        intent.putExtra("KEY_GEOFENCE_ID", geofence.getTag());
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, mPendingIntentRequestCode++, intent, flags);
        
        // 添加围栏（无返回值）
        mGeofenceManager.addFence(geofence, pendingIntent);
        updateStatus("多边形围栏添加成功");
        
        // 立即绘制多边形围栏（多边形围栏数据是同步的）
        drawPolygonFence(geofence);
    }
    
    /**
     * 绘制行政区划围栏边界
     * 注意：行政区划围栏需要从 getValidFences 中获取实际创建的围栏
     * 这主要是因为：1. 行政区划围栏数据是异步获取的；2. 行政区划围栏可能有多个（重名的多个行政区）
     * @param baseTag
     */
    private void drawDistrictFence(String baseTag) {
        // 从有效围栏列表中查找匹配的行政区划围栏
        List<TencentGeofence> validFences = mGeofenceManager.getValidFences();
        List<TencentGeofence> districtFences = new ArrayList<>();
        
        for (TencentGeofence fence : validFences) {
            // 匹配 tag 前缀（因为实际创建的 fence 的 tag 是 baseTag + "_" + adcode）
            if (fence.getTag().startsWith(baseTag) && 
                fence.getType() == TencentGeofence.GEOFENCE_TYPE_DISTRICT) {
                districtFences.add(fence);
            }
        }
        
        if (districtFences.isEmpty()) {
            Log.w(TAG, "未找到有效的行政区划围栏，可能还在请求中");
            updateStatus("等待行政区划数据...");
            return;
        }
        
        List<LatLng> allPoints = new ArrayList<>();
        int totalPolygonCount = 0;
        
        // 绘制所有匹配的行政区划围栏（可能有重名的多个行政区）
        for (TencentGeofence fence : districtFences) {
            TencentGeofence.DistrictFence districtFence = fence.getDistrictFence();
            if (districtFence == null) {
                continue;
            }
            
            List<List<TencentGeofence.FencePoint>> polygonList = districtFence.getPolygonList();
            if (polygonList == null || polygonList.isEmpty()) {
                continue;
            }
            
            // 遍历所有多边形（一个行政区划可能有多个多边形，如岛屿）
            for (List<TencentGeofence.FencePoint> polygon : polygonList) {
                List<LatLng> points = new ArrayList<>();
                for (TencentGeofence.FencePoint point : polygon) {
                    LatLng latLng = new LatLng(point.getLatitude(), point.getLongitude());
                    points.add(latLng);
                    allPoints.add(latLng);
                }
                
                // 绘制多边形
                PolygonOptions options = new PolygonOptions()
                        .add(points.toArray(new LatLng[0]))
                        .strokeColor(Color.RED)
                        .strokeWidth(3)
                        .fillColor(0x220000FF); // 半透明蓝色填充
                
                Polygon mapPolygon = mTencentMap.addPolygon(options);
                mPolygonMap.put(fence.getTag() + "_" + totalPolygonCount, mapPolygon);
                totalPolygonCount++;
            }
            
            Log.d(TAG, "绘制行政区划围栏: " + fence.getTag() + 
                    ", keyword=" + districtFence.getKeyword());
        }
        
        // 调整地图视野以显示整个围栏
        if (!allPoints.isEmpty()) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (LatLng point : allPoints) {
                builder.include(point);
            }
            LatLngBounds bounds = builder.build();
            mTencentMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
        }
        
        updateStatus("行政区划围栏已绘制: " + districtFences.size() + " 个区域，" + 
                totalPolygonCount + " 个多边形");
    }
    
    /**
     * 绘制圆形围栏
     */
    private void drawCircleFence(TencentGeofence geofence) {
        // 移除旧的圆形
        com.tencent.tencentmap.mapsdk.maps.model.Circle oldCircle = mCircleMap.remove(geofence.getTag());
        if (oldCircle != null) {
            oldCircle.remove();
        }
        
        TencentGeofence.CircleFence circleFence = geofence.getCircleFence();
        if (circleFence == null) {
            Log.w(TAG, "圆形围栏对象为空");
            return;
        }
        
        LatLng centerLatLng = new LatLng(circleFence.getLatitude(), circleFence.getLongitude());
        
        // 绘制圆形
        CircleOptions options = new CircleOptions()
                .center(centerLatLng)
                .radius(circleFence.getRadius())
                .strokeColor(Color.BLUE)
                .strokeWidth(3)
                .fillColor(0x2200FF00); // 半透明绿色填充
        
        com.tencent.tencentmap.mapsdk.maps.model.Circle circle = mTencentMap.addCircle(options);
        mCircleMap.put(geofence.getTag(), circle);
        
        // 调整地图视野
        mTencentMap.animateCamera(CameraUpdateFactory.newLatLngZoom(centerLatLng, 14));
        
        updateStatus("圆形围栏已绘制，半径: " + circleFence.getRadius() + "米");
    }
    
    /**
     * 绘制多边形围栏
     */
    private void drawPolygonFence(TencentGeofence geofence) {
        // 移除旧的多边形
        Polygon oldPolygon = mPolygonMap.remove(geofence.getTag());
        if (oldPolygon != null) {
            oldPolygon.remove();
        }
        
        TencentGeofence.PolygonFence polygonFence = geofence.getPolygonFence();
        if (polygonFence == null) {
            Log.w(TAG, "多边形围栏对象为空");
            return;
        }
        
        List<TencentGeofence.FencePoint> fencePoints = polygonFence.getPointList();
        if (fencePoints == null || fencePoints.isEmpty()) {
            Log.w(TAG, "多边形围栏点为空");
            return;
        }
        
        // 转换为地图 LatLng 对象
        List<LatLng> points = new ArrayList<>();
        for (TencentGeofence.FencePoint point : fencePoints) {
            points.add(new LatLng(point.getLatitude(), point.getLongitude()));
        }
        
        // 绘制多边形
        PolygonOptions options = new PolygonOptions()
                .add(points.toArray(new LatLng[0]))
                .strokeColor(Color.MAGENTA)
                .strokeWidth(3)
                .fillColor(0x22FF00FF); // 半透明紫色填充
        
        Polygon polygon = mTencentMap.addPolygon(options);
        mPolygonMap.put(geofence.getTag(), polygon);
        
        // 调整地图视野以显示整个多边形
        if (!points.isEmpty()) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (LatLng point : points) {
                builder.include(point);
            }
            LatLngBounds bounds = builder.build();
            mTencentMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
        }
        
        updateStatus("多边形围栏已绘制，顶点数: " + fencePoints.size());
    }
    
    /**
     * 显示移除围栏对话框
     */
    private void showRemoveFenceDialog() {
        // 获取所有有效围栏
        List<TencentGeofence> validFences = mGeofenceManager.getValidFences();
        
        if (validFences.isEmpty()) {
            Toast.makeText(this, "当前没有围栏", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建围栏列表显示
        String[] fenceItems = new String[validFences.size() + 1];
        fenceItems[0] = "手动输入 TAG";
        
        for (int i = 0; i < validFences.size(); i++) {
            TencentGeofence fence = validFences.get(i);
            String type = "";
            switch (fence.getType()) {
                case TencentGeofence.GEOFENCE_TYPE_DISTRICT:
                    type = "[行政]";
                    break;
                case TencentGeofence.GEOFENCE_TYPE_CIRCLE:
                    type = "[圆形]";
                    break;
                case TencentGeofence.GEOFENCE_TYPE_POLYGON:
                    type = "[多边形]";
                    break;
            }
            fenceItems[i + 1] = type + " " + fence.getTag();
        }
        
        // 显示选择对话框
        new AlertDialog.Builder(this)
                .setTitle("选择要移除的围栏")
                .setItems(fenceItems, (dialog, which) -> {
                    if (which == 0) {
                        // 手动输入 TAG
                        showManualRemoveFenceDialog();
                    } else {
                        // 移除选中的围栏
                        TencentGeofence fence = validFences.get(which - 1);
                        removeFenceByTag(fence.getTag());
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 显示手动输入 TAG 的对话框
     */
    private void showManualRemoveFenceDialog() {
        final EditText editText = new EditText(this);
        editText.setHint("输入围栏 TAG");
        editText.setPadding(50, 30, 50, 30);
        
        new AlertDialog.Builder(this)
                .setTitle("移除围栏")
                .setMessage("请输入要移除的围栏 TAG\\n支持前缀匹配（如: district_北京市）")
                .setView(editText)
                .setPositiveButton("移除", (dialog, which) -> {
                    String tag = editText.getText().toString().trim();
                    if (tag.isEmpty()) {
                        Toast.makeText(this, "请输入 TAG", Toast.LENGTH_SHORT).show();
                    } else {
                        removeFenceByTag(tag);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    /**
     * 根据 TAG 移除围栏（支持前缀匹配）
     */
    private void removeFenceByTag(String tag) {
        List<TencentGeofence> validFences = mGeofenceManager.getValidFences();
        List<TencentGeofence> toRemove = new ArrayList<>();
        
        // 查找匹配的围栏（支持前缀匹配）
        for (TencentGeofence fence : validFences) {
            if (fence.getTag().equals(tag) || fence.getTag().startsWith(tag)) {
                toRemove.add(fence);
            }
        }
        
        if (toRemove.isEmpty()) {
            Toast.makeText(this, "未找到匹配的围栏: " + tag, Toast.LENGTH_SHORT).show();
            updateStatus("未找到围栏: " + tag);
            return;
        }
        
        // 移除围栏
        int count = 0;
        for (TencentGeofence fence : toRemove) {
            // 从管理器中移除
            mGeofenceManager.removeFence(fence);
            
            // 移除地图上的绘制
            removeDrawnFence(fence);
            
            count++;
            Log.d(TAG, "移除围栏: " + fence.getTag());
        }
        
        String message = "已移除 " + count + " 个围栏";
        updateStatus(message);
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 移除地图上绘制的围栏
     */
    private void removeDrawnFence(TencentGeofence fence) {
        String tag = fence.getTag();
        
        // 移除多边形（行政区划和多边形围栏）
        List<String> keysToRemove = new ArrayList<>();
        for (String key : mPolygonMap.keySet()) {
            if (key.equals(tag) || key.startsWith(tag)) {
                keysToRemove.add(key);
            }
        }
        for (String key : keysToRemove) {
            Polygon polygon = mPolygonMap.remove(key);
            if (polygon != null) {
                polygon.remove();
            }
        }
        
        // 移除圆形
        com.tencent.tencentmap.mapsdk.maps.model.Circle circle = mCircleMap.remove(tag);
        if (circle != null) {
            circle.remove();
        }
    }
    
    /**
     * 清除所有围栏
     */
    private void clearAllFences() {
        // 清除地图上的绘制
        for (Polygon polygon : mPolygonMap.values()) {
            polygon.remove();
        }
        mPolygonMap.clear();
        
        for (com.tencent.tencentmap.mapsdk.maps.model.Circle circle : mCircleMap.values()) {
            circle.remove();
        }
        mCircleMap.clear();
        
        // 清除围栏管理器中的围栏
        List<TencentGeofence> fences = mGeofenceManager.getValidFences();
        for (TencentGeofence fence : fences) {
            mGeofenceManager.removeFence(fence);
        }
        
        updateStatus("已清除所有围栏");
        Toast.makeText(this, "已清除所有围栏", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 开始定位
     */
    private void startLocation() {
        // 初始化 TencentLocationManager
        if (mLocationMgr == null) {
            mLocationMgr = TencentLocationManager.getInstance(this);
        }
        
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest.create()
                .setInterval(1000)
                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_GEO);
        
        // 启动定位 (platform 参数通常为 0，表示通用平台)
        int re = mLocationMgr.requestLocationUpdates(request, mLocationObserver);
        if (re != 0) {
            updateStatus("定位启动失败： " + re);
        } else {
            updateStatus("定位已启动");
            mBtnStartLocation.setEnabled(false);
            mBtnStopLocation.setEnabled(true);
        }
    }
    
    /**
     * 停止定位
     */
    private void stopLocation() {
        if (mLocationMgr != null) {
            // 停止定位
            mLocationMgr.removeUpdates(mLocationObserver);
        }
        
        updateStatus("定位已停止");
        mBtnStartLocation.setEnabled(true);
        mBtnStopLocation.setEnabled(false);
    }
    
    /**
     * 定位监听器
     */
    private final TencentLocationListener mLocationObserver = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation location, int error, String reason) {
            if (location == null) {
                updateStatus("定位失败: 位置信息为空");
                return;
            }
            if (error == TencentLocation.ERROR_OK) {
                mCurrentLocation = new LatLng(location.getLatitude(), location.getLongitude());

                // 更新当前位置标记
                if (mCurrentLocationMarker == null) {
                    MarkerOptions options = new MarkerOptions()
                            .position(mCurrentLocation)
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                            .title("当前位置");
                    mCurrentLocationMarker = mTencentMap.addMarker(options);
                } else {
                    mCurrentLocationMarker.setPosition(mCurrentLocation);
                }

                // 显示详细定位信息
                updateStatus(location.toString());

                Log.d(TAG, "定位成功 - " + location);
            } else {
                String errorMsg = "定位失败，错误码: " + error;
                updateStatus(errorMsg);
                Log.w(TAG, errorMsg);
            }
        }

        @Override
        public void onStatusUpdate(String name, int status, String desc) {

        }
    };
    
    /**
     * 围栏事件接收器
     */
    private class GeofenceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!intent.getPackage().equals(getPackageName())) {
                // 确保收发进程一致，避免其他应用的广播
                Log.e(TAG, "进程不一致: " + intent.getPackage() + " != " + getPackageName() + "");
                return;
            }
            if (ACTION_TRIGGER_GEOFENCE.equals(action)) {
                // 检查是进出事件还是成功/失败回调
                if (intent.hasExtra(TencentGeofence.ERROR_CODE)) {
                    // 围栏添加成功/失败回调
                    int errorCode = intent.getIntExtra(TencentGeofence.ERROR_CODE, TencentGeofence.ERROR_OK);
                    String errorMsg = intent.getStringExtra(TencentGeofence.ERROR_MESSAGE);
                    String tag = intent.getStringExtra("KEY_GEOFENCE_ID");

                    if (errorCode != TencentGeofence.ERROR_OK) {
                        updateStatus("围栏错误: " + errorMsg + " (code: " + errorCode + ")");
                        Log.e(TAG, "Geofence error: " + errorMsg + ", code: " + errorCode);
                    } else {
                        updateStatus("✓ " + errorMsg);
                        Toast.makeText(context, "围栏添加成功: " + tag, Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "Geofence success: " + errorMsg);
                    }
                } else if (intent.hasExtra(LocationManager.KEY_PROXIMITY_ENTERING)) {
                    // 围栏进入/离开事件
                    boolean isEnter = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, true);
                    String tag = intent.getStringExtra("KEY_GEOFENCE_ID");
                    if (tag == null) {
                        tag = "未知围栏";
                    }

                    String statusStr = isEnter ? "进入围栏" : "离开围栏";

                    updateStatus("围栏事件: " + statusStr + " [" + tag + "]");
                    Toast.makeText(context, statusStr + ": " + tag, Toast.LENGTH_LONG).show();

                    Log.i(TAG, "Geofence event: " + statusStr + ", tag: " + tag);
                }
            } else {
                updateStatus("未知广播: " + action);
            }
        }
    }
    
    /**
     * 更新状态文本
     */
    private void updateStatus(final String status) {
        runOnUiThread(() -> {
            mTextStatus.setText(status);
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 停止定位
        if (mLocationMgr != null) {
            try {
                mLocationMgr.removeUpdates(mLocationObserver);
            } catch (Exception e) {
                Log.e(TAG, "停止定位失败", e);
            }
        }

        // 注销广播接收器
        if (mGeofenceReceiver != null) {
            try {
                unregisterReceiver(mGeofenceReceiver);
            } catch (Exception e) {
                Log.e(TAG, "注销接收器失败", e);
            }
        }

        // 清除所有围栏销毁围栏管理器
        if (mGeofenceManager != null) {
            mGeofenceManager.removeAllFences();
            mGeofenceManager.destroy();
        }
        
        // 清理地图
        if (mMapView != null) {
            mMapView.onDestroy();
        }
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        mMapView.onStart();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        mMapView.onStop();
    }
}
