package com.lnkj.ln_jq_app;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.amap.api.maps.AMapException;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapCarInfo;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviRouteNotifyData;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviPoi;

import java.util.List;

import androidx.activity.ComponentActivity;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;

/**
 * 导航
 */
public class NavigationActivity extends ComponentActivity implements AMapNaviListener {

    private static final String TAG = "NavigationActivity";

    private AMapNavi mAMapNavi;
    private AMapNaviView naviView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 创建导航视图
        naviView = new AMapNaviView(this);
        naviView.onCreate(savedInstanceState);
        naviView.setAMapNaviViewListener(new AMapNaviViewListener() {
            @Override
            public void onNaviSetting() {

            }

            @Override
            public void onNaviCancel() {
                finish();
            }

            @Override
            public boolean onNaviBackClick() {
                return false;
            }

            @Override
            public void onNaviMapMode(int i) {

            }

            @Override
            public void onNaviTurnClick() {

            }

            @Override
            public void onNextRoadClick() {

            }

            @Override
            public void onScanViewButtonClick() {

            }

            @Override
            public void onLockMap(boolean b) {

            }

            @Override
            public void onNaviViewLoaded() {

            }

            @Override
            public void onMapTypeChanged(int i) {

            }

            @Override
            public void onNaviViewShowMode(int i) {

            }
        });

        AMapNaviViewOptions aMapNaviViewOptions = new AMapNaviViewOptions();
        Bitmap carBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.car);
        aMapNaviViewOptions.setCarBitmap(carBitmap);
        aMapNaviViewOptions.setSettingMenuEnabled(false);
        naviView.setViewOptions(aMapNaviViewOptions);

        // 创建 AMapNavi 实例
        try {
            mAMapNavi = AMapNavi.getInstance(this);
            mAMapNavi.addAMapNaviListener(this);
        } catch (AMapException e) {
            Log.e(TAG, "初始化导航失败", e);
            Toast.makeText(this, "初始化导航失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 添加到容器
        FrameLayout container = new FrameLayout(this);
        container.addView(naviView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        setContentView(container);

        // 获取 Intent 中的参数
        processIntent(getIntent());

        // 处理返回键
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                finish();
            }
        });

        Log.d(TAG, "NavigationActivity created");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processIntent(intent);
    }

    /**
     * 处理 Intent 参数并启动导航
     */
    @SuppressWarnings("unchecked")
    private void processIntent(Intent intent) {
        if (intent == null) {
            Log.w(TAG, "Intent is null");
            return;
        }

        try {
            // 获取起点、终点和途经点
            NaviPoi startNaviPoi = (NaviPoi) intent.getParcelableExtra("startPoi");
            NaviPoi endNaviPoi = (NaviPoi) intent.getParcelableExtra("endPoi");
            List<NaviPoi> wayPoints = intent.getParcelableArrayListExtra("wayPoints");

            if (wayPoints != null) {
                Log.d("Navi", "获取到途径点数量: " + wayPoints.size());
            }


            if (startNaviPoi == null || endNaviPoi == null) {
                Log.e(TAG, "Missing start or end point");
                return;
            }

            // 设置车辆信息
            AMapCarInfo carInfo = (AMapCarInfo) intent.getParcelableExtra("carInfo");
            if (carInfo != null) {
                mAMapNavi.setCarInfo(carInfo);
            }

            mAMapNavi.setUseInnerVoice(true);
            // 计算并启动导航
            mAMapNavi.calculateDriveRoute(startNaviPoi, endNaviPoi, wayPoints, PathPlanningStrategy.DRIVING_MULTIPLE_ROUTES_DEFAULT);

            Log.d(TAG, "Navigation started from: " + startNaviPoi.getName() + " - " + endNaviPoi.getName());

        } catch (Exception e) {
            Log.e(TAG, "Process intent error", e);
            Toast.makeText(this, "导航启动失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (naviView != null) {
            naviView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (naviView != null) {
            naviView.onPause();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (naviView != null) {
            naviView.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止导航
        if (mAMapNavi != null) {
            mAMapNavi.stopNavi();
            mAMapNavi.removeAMapNaviListener(this);
        }
        if (naviView != null) {
            naviView.onDestroy();
        }
        Log.d(TAG, "NavigationActivity destroyed");
    }

    private int dp2px(float dp) {
        float density = getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    // ============ AMapNaviListener 回调实现 ============


    @Override
    public void onInitNaviFailure() {
        Log.e(TAG, "onInitNaviFailure");
    }

    @Override
    public void onInitNaviSuccess() {
        Log.d(TAG, "onInitNaviSuccess");
    }

    @Override
    public void onStartNavi(int i) {
        Log.d(TAG, "onStartNavi: " + i);
    }

    @Override
    public void onTrafficStatusUpdate() {
    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {
    }

    @Override
    public void onGetNavigationText(int i, String s) {
    }

    @Override
    public void onGetNavigationText(String s) {
    }

    @Override
    public void onEndEmulatorNavi() {
    }

    @Override
    public void onArriveDestination() {
        Log.d(TAG, "onArriveDestination");
    }

    @Override
    public void onCalculateRouteFailure(int i) {
        Log.e(TAG, "onCalculateRouteFailure: " + i);
        Toast.makeText(this, "路径计算失败: " + i, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {
    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {
    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {
    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {
    }

    @Override
    public void hideCross() {
    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {
    }

    @Override
    public void hideModeCross() {
    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {
    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {
    }

    @Override
    public void hideLaneInfo() {
    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        Log.d(TAG, "onCalculateRouteSuccess");
        if (mAMapNavi != null) {
            mAMapNavi.startNavi(NaviType.GPS);
        }
    }

    @Override
    public void notifyParallelRoad(int i) {
    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {
    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {
    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {
    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {
    }

    @Override
    public void onPlayRing(int i) {
    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {
        Log.d(TAG, "onCalculateRouteSuccess (result)");
        if (mAMapNavi != null) {
            mAMapNavi.startNavi(NaviType.GPS);
        }
    }

    @Override
    public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {
        Log.e(TAG, "onCalculateRouteFailure: " + aMapCalcRouteResult.getErrorCode());
        Toast.makeText(this, "路径计算失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNaviRouteNotify(AMapNaviRouteNotifyData aMapNaviRouteNotifyData) {
    }

    @Override
    public void onGpsSignalWeak(boolean b) {
    }

    @Override
    public void onReCalculateRouteForYaw() {
        Log.d(TAG, "onReCalculateRouteForYaw");
    }

    @Override
    public void onReCalculateRouteForTrafficJam() {
    }

    @Override
    public void onArrivedWayPoint(int i) {
    }

    @Override
    public void onGpsOpenStatus(boolean b) {
    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {
    }
}
