package com.tofly.ghrq_route.base.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.common.util.ArcgisUtils.ArcgisUtils;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.module.gps.service.AmapLocationHelper;
import com.tofly.ghrq_route.module.map.controller.MapController;
import com.tofly.ghrq_route.module.map.domain.ConfigAll;
import com.tofly.ghrq_route.module.map.interfaces.MapLoadHelper;
import com.tofly.latte_core.base.BaseActivity;
import com.tofly.latte_core.base.IPresenter;

import java.util.List;

public abstract class BaseMapActivity<P extends IPresenter> extends BaseActivity<P> implements MapLoadHelper {
    protected MapView mapView;

    protected BaseMapController baseMapController;

    protected AmapLocationHelper amapLocationHelper;

    protected Point mLastLocation = null;   //格式化小数点6位后的位置坐标

    protected Point mLocation = null;

    protected Point mProjLoc = null;

    protected String mAddress = null;

    protected int mGpsFlag = 0;

    /**
     * 是否开启地图加载*/
    public abstract boolean enableLoadMap();

    /**
     * 是否开启地图拖动监听位置*/
    public abstract boolean enableMoveMapListener();

    /**
     * 是否开启Arcgis定位，用于实时显示当前的朝向，定位半径*/
    public abstract boolean enableArcgisLocating();

    /**
     * 是否开启高德定位进行实时定位*/
    public abstract boolean enableAmapLocationListener();

    /**
     * 是否高德定位后自动移动到定位位置*/
    public abstract boolean enableMapMoveToLocation();

    public boolean enableArcgisRotating() {
        return false;
    }

    /**
     * 设置定位后显示位置信息的TextView*/
    public abstract TextView getTextAddrView();

    public ArcgisUtils getArcgisUtils() {
        return baseMapController.arcgisUtils;
    }

    public MapController getMapController() {
        return baseMapController.mapController;
    }

    public void hideArcgisMapCallout() {
        getArcgisUtils().hideArcgisMapCallout();
    }

    protected LocationUtil_xu.CoordinateClass getLocation() {
        LocationUtil_xu.CoordinateClass location = new LocationUtil_xu.CoordinateClass();
        if (mProjLoc != null) {
            location.Longtitude = mProjLoc.getX();
            location.Latitude = mProjLoc.getY();
            location.addr = mAddress;
        }
        return location;
    }

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

    @Override
    public void initView() {
        Toolbar toolbar = findViewById(R.id.main_toolbar);
        if (toolbar != null) {
            initToolBar(toolbar);
        }
    }

    @Override @CallSuper
    public void initNet() {
        amapLocationHelper = new AmapLocationHelper(this);

        baseMapController = new BaseMapController(this, this);

        initListener();
    }

    /*Arcgis定位现在只用来确定当前的位置方向和移动方向*/
    protected void initArcgisLocationService() {
        LocationDisplay arcgisLdm = mapView.getLocationDisplay();
        //arcgisLdm.setAutoPanMode(LocationDisplay.AutoPanMode.COMPASS_NAVIGATION);
        arcgisLdm.startAsync();
    }

    private void initListener() {
        boolean enableLoadMap = enableLoadMap();
        if (enableLoadMap) {
            mapView = findViewById(R.id.mapview);
            baseMapController.loadMap(mapView);

            boolean enableMove = enableMoveMapListener();
            if (enableMove) {
                if (mapView != null) {
                    mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
                        @Override
                        public boolean onUp(MotionEvent e) {
                            Point pcenter = ArcgisUtils.getMapCenter(mapView);
                            if (pcenter != null) {
                                mLastLocation = pcenter;
                                mGpsFlag = 1;
                                Point location = ArcgisUtils.projectLocationDefault(pcenter.getX(), pcenter.getY());
                                if (location != null)
                                    amapLocationHelper.reserveLocation(location.getX(), location.getY());
                            }
                            return true;
                        }
                    });
                }
            }
        }

        boolean enableArcgisLoc = enableArcgisLocating();
        if (enableArcgisLoc)
            initArcgisLocationService();

        boolean enableAmapLoc = enableAmapLocationListener();
        if (enableAmapLoc) {
            amapLocationHelper.startLocating();

            amapLocationHelper.setMapLocationListener((location, addr, projLoc) -> {
                if (enableMapMoveToLocation()) {
                    mapView.setViewpointCenterAsync(projLoc).addDoneListener(() ->
                            mapView.setViewpointScaleAsync(BaseMapController.DEFAULTSCALE));
                }

                mLocation = location;
                mProjLoc = projLoc;
                mLastLocation = projLoc;
                mAddress = addr;
                mGpsFlag = 0;

                baseMapController.setLocation(location);
                baseMapController.setProjLoc(projLoc);
                baseMapController.setAddress(addr);

                if (TextUtils.isEmpty(addr)) {
                    //开启本地数据的
                    amapLocationHelper.reserveLocation(location.getX(), location.getY());
                }

                TextView textAddr = getTextAddrView();
                if (textAddr != null) {
                    textAddr.setText(addr);
                }
            });

            amapLocationHelper.setReserveLocListener((isSuccess, addr) -> {
                if (isSuccess) {
                    if (addr != null) {
                        mAddress = addr;
                    }
                }

                TextView textAddr = getTextAddrView();
                if (textAddr != null) {
                    textAddr.setText(addr);
                }
            });
        }else {
            mapView.setViewpointScaleAsync(BaseMapController.DEFAULTSCALE);
        }

        View view_layer = findViewById(R.id.layer_manager);
        if (view_layer != null) {
            view_layer.setOnClickListener(view -> baseMapController.showLayoutManager(mapView));
        }

        View view_locate = findViewById(R.id.my_location);
        if (view_locate != null) {
            view_locate.setOnClickListener(view -> moveToMyLocation());
        }
    }

    protected void moveToMyLocation() {
        amapLocationHelper.resetLocation();
    }

    protected void showNavigation(Point toPoint) {
        baseMapController.onRouteBtnPressed(mLocation, toPoint);
    }

    protected void showNavigationCallout(Point toPoint) {
        baseMapController.showRoutePointCallout(mLocation, toPoint);
    }

    /**
     * 地图加载回调处理
     */
    @Override
    public void loadOnlineMap() {

    }

    @Override
    public void loadtpkMap(List<ArcGISTiledLayer> tpkLayers) {

    }

    @Override
    public void onBaseMapLoaded() {
        //mapView.setViewpointScaleAsync(BaseMapController.DEFAULTSCALE);
    }

    @Override
    public void loadGeodataMap(FeatureLayer[] geodatabaseLayers) {

    }

    @Override
    public void loadSignPathLayer(GraphicsOverlay signPathLayer) {

    }

    @Override
    public void turnToDownload() {

    }

    @Override
    public void loadMapLayerIndexConfig(List<ConfigAll.ResultBean> result) {

    }

    @Override
    public MapView getMapView() {
        return mapView;
    }

    @Override
    public void resetMapView() {
        mapView = null;
        mapView = findViewById(R.id.mapview);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mapView != null) {
            LocationDisplay locationDisplay = mapView.getLocationDisplay();
            if (locationDisplay != null && locationDisplay.isStarted())
                locationDisplay.stop();
        }

        baseMapController.onDestroy();
        amapLocationHelper.onDestroy();
    }
}
