package com.tofly.ghrq_route.common.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.ProximityResult;
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.JsonObject;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.Intents;
import com.mgq.base.utils.net.NetworkStatus;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseMapActivity;
import com.tofly.ghrq_route.base.ui.BaseMapController;
import com.tofly.ghrq_route.base.ui.BaseMapController.MapMode;
import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.common.ui.dialog.UiMainLayerManagerDailog;
import com.tofly.ghrq_route.common.ui.fragment.PipeSearchFragment;
import com.tofly.ghrq_route.common.ui.view.FloatAddressSearchBar;
import com.tofly.ghrq_route.common.ui.view.FloatDeviceSearchBar;
import com.tofly.ghrq_route.common.ui.view.PipeAnalyzeResultBottomSheet;
import com.tofly.ghrq_route.common.util.ArcgisUtils.ArcgisUtils;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.common.util.app.AppUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import com.tofly.ghrq_route.common.util.measure.MeasuringTool;
import com.tofly.ghrq_route.module.map.MapServiceTool;
import com.tofly.ghrq_route.module.map.controller.MapController;
import com.tofly.ghrq_route.module.map.controller.MapServiceCallback;
import com.tofly.ghrq_route.module.map.domain.ConfigAll;
import com.tofly.ghrq_route.module.map.domain.PipeQueryBean;
import com.tofly.ghrq_route.module.map.service.Container;
import com.tofly.ghrq_route.module.map.view.PipeSearchManager;
import com.tofly.ghrq_route.module.pipeAnalyze.domain.PipeAnalysisResultBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by zombiexq on 2016/6/17.
 */
public class UiMapTool extends BaseMapActivity {
    @BindView(R.id.layout_collapse_toolbar)
    CollapsingToolbarLayout collapsingToolbarLayout;
    @BindView(R.id.layout_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.main_toolbar)
    Toolbar toolbar;
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.maptool_pipenet_ll)
    CardView maptooPipeNetLl;
    @BindView(R.id.img_pipenet)
    ImageView imgPipenet;
    @BindView(R.id.maptool_pipeSearchManager)
    PipeSearchManager pipeSearchManager;
    @BindView(R.id.layout_float_search)
    FloatDeviceSearchBar deviceSearchBar;
    @BindView(R.id.layout_float_search_addr)
    FloatAddressSearchBar addrSearchBar;
    @BindView(R.id.layout_pipe_analyze)
    LinearLayout layoutPipeAnalyze;
    @BindView(R.id.img_pipe)
    ImageView imagePipeAnalyze;
    @BindView(R.id.text_pipe_analyze)
    TextView textPipeAnalyze;
    @BindView(R.id.pipe_analyze_bottom_sheet)
    PipeAnalyzeResultBottomSheet pipeAnalyzeResultBottomSheet;

    private TroubleBean troubleSelected = null;
    private GraphicsOverlay troubleLayer = null;
    private ActionBar actionBar;

    private final double DEFAULTSCALE = BaseMapController.DEFAULTSCALE;

    private double mCurrentScale = DEFAULTSCALE;

    private PipeSearchFragment pipeSearchFragment;

    private List<ConfigAll.ResultBean> layerIndexConfigs;

    private BaseMapController.MapMode mapFlag = BaseMapController.MapMode.offlineMode; // 离线地图模式 / 在线地图模式 /爆管分析模式

    private GraphicsOverlay localLocLayer = null;

    //爆管分析图层
    private List<ArcGISMapImageLayer> analysisIndexList = new ArrayList<>();

    private BitmapDrawable imageLoc;

    private MarkerSymbol symbolLoc;

    private MapServiceTool mapServiceTool;

    private MeasuringTool measuringTool;

    private MapController mapController;

    private PhotoHelper photoHelper;

    private PermissionHelper permissionHelper;

    @Subscribe
    public void onMessageEvent(UiPlan.PlanEvent event){
        if (event.message.equals(UiPlan.PLAN_SERVICE_LOCATION)) {
            Point point = (Point) event.arg0;
            showLocationPerson(point);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE
                    );
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {

                }
            }
        }
        return super.onPrepareOptionsPanel(view, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        clearEditFocus();
        int itemId = item.getItemId();
        switch (itemId) {
            case R.id.action_measure:
                if (mapFlag == MapMode.analyzeMode) {
                    showToast("请退出爆管分析模式后再试！");
                    return true;
                }
                initMeasuringTool();//点击绘图工具
                return true;
            case R.id.action_sketch:
                baseMapController.showSketch();
                return true;
            case R.id.action_qrcode:
                if (mapFlag == MapMode.analyzeMode) {
                    showToast("请退出爆管分析模式后再试！");
                    return true;
                }
                checkCameraPermission();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void clearEditFocus() {
        if (deviceSearchBar != null)
            deviceSearchBar.clearInputFocus();
        deviceSearchBar.requestFocus();

        if (addrSearchBar != null)
            addrSearchBar.clearInputFocus();
        addrSearchBar.requestFocus();
    }

    //设置ActionBar下拉菜单显示图标，TODO 还不起作用
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public void onBackPressed() {
        if (pipeSearchManager != null && pipeSearchManager.behavior != null) {
            int state = pipeSearchManager.behavior.getState();
            if (state == BottomSheetBehavior.STATE_EXPANDED) {
                pipeSearchManager.behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            } else if (state == BottomSheetBehavior.STATE_COLLAPSED) {
                pipeSearchManager.behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
            } else if (state == BottomSheetBehavior.STATE_HIDDEN) {
                AppUtil.gotoSystemHome(this);
            }
        } else {
            AppUtil.gotoSystemHome(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void initView() {
        super.initView();

        initAppBar();

        imageLoc = (BitmapDrawable) getBaseContext().getResources().getDrawable(R.mipmap.trouble_location);
        symbolLoc = SizeMarkerSymbol.sizeSymbol(imageLoc, 18, 18);
    }

    private void initAppBar() {
        // 4.4及以上版本开启
        setLightStatusBar();
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            collapsingToolbarLayout.setTitle(getString(R.string.maptool_title));
        });
    }

    @Override
    public void initNet() {
        super.initNet();

        mapController = getMapController();
        mapServiceTool = MapServiceTool.getInstance();

        permissionHelper = baseMapController.permissionHelper;
        photoHelper = baseMapController.photoHelper;

        initListener();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == QR_SCAN_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getStringExtra(Intents.Scan.RESULT);
                if (result != null) {
                    getLayerIdFromQrCodeSid(result);
                } else {
                    showToast("扫描数据为空。");
                }
            }else {
                if (resultCode != Activity.RESULT_CANCELED)
                    showToast("扫描二维码出错，请重试。");
            }
        }else {
            if (photoHelper != null) {
                photoHelper.handleActivityResult(requestCode, resultCode, data);
            }
        }
    }

    private void getLayerIdFromQrCodeSid(String sid) {
        String strUploading = getResources().getString(R.string.querying_map);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);

        mapServiceTool.query_device_by_sid(this, sid, new MapServiceCallback(){
            @Override
            public void onQueryMapBySid(boolean isSuccess, int errorCode, String errMsg,
                                        JsonObject jsonAttributes, JsonObject jsonGeometry, String tableName) {
                super.onQueryMapBySid(isSuccess, errorCode, errMsg, jsonAttributes, jsonGeometry, tableName);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    if (jsonAttributes != null) {
                        mapController.showCalloutFromJsonObject(mapView, jsonAttributes, jsonGeometry, tableName);
                    }else {
                        showToast("查询失败");
                    }
                }else {
                    showToast(errMsg);
                }
            }
        });
    }

    @OnCheckedChanged({R.id.radio_btn_device, R.id.radio_btn_addr})
    public void onRadioCheck(CompoundButton view, boolean ischanged) {
        if (ischanged) {
            switch (view.getId()) {
                case R.id.radio_btn_device:
                    deviceSearchBar.setVisibility(View.VISIBLE);
                    addrSearchBar.setVisibility(View.GONE);
                    addrSearchBar.onSearchClosed();
                    break;
                case R.id.radio_btn_addr:
                    addrSearchBar.setVisibility(View.VISIBLE);
                    deviceSearchBar.setVisibility(View.GONE);
                    deviceSearchBar.onSearchClosed();
                    break;
            }
        }
    }

    //管网查询开关
    private boolean isPipeNetOn = false;
    private boolean isPipeAnalyzeOn = false;
    @OnClick({R.id.maptool_pipenet_ll, R.id.layout_pipe_analyze, R.id.pipe_analyze_bottom_sheet, R.id.btn_close_bottom_sheet})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.maptool_pipenet_ll:
                if (isPipeNetOn) {
//                    clossPipeFragmentDialog();
                    closePipeBottomSheet();
                } else {
//                    showPipeFragmentDialog();
                    showPipeBottomSheet();
                }
                break;
            case R.id.layout_pipe_analyze:{
                boolean canOpen = canOpenPipeAnalyzeMode();
                if (!canOpen)
                    return;

                if (mapFlag != MapMode.analyzeMode){
                    mapFlag = MapMode.analyzeMode;
                    enterPipeAnalyzeMode();
                }else {
                    mapFlag = MapMode.offlineMode;
                    exitPipeAnalyzeMode();
                }
            }
            break;
            case R.id.pipe_analyze_bottom_sheet:{

            }
            break;
            case R.id.btn_close_bottom_sheet: {
                mapFlag = MapMode.offlineMode;
            }
            break;
        }
        clearEditFocus();
    }

    protected void initListener() {
        if (mapView != null) {
            mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent event) {
                    clearEditFocus();
                    onSingleTap(event.getX(), event.getY());
                    return true;
                }

                @Override
                public boolean onRotate(MotionEvent event, double rotationAngle) {
                    return false;
                }
            });
        }

        if (pipeSearchManager.getOnMapShowListenerIsNull()) {
            pipeSearchManager.setOnMapShowListener(feature -> mapController.showCallOutAtMap(mapView, feature));
        }

        deviceSearchBar.setOnSearchListener(new FloatDeviceSearchBar.onSearchListener() {
            @Override
            public void onSearchClosed() {
                mapController.closeMapQueryView(mapView);
            }

            @Override
            public void onSearchSelected(Feature feature, String deviceName) {
                Geometry geometry = feature.getGeometry();
                if (geometry instanceof Point) {
                    Point point = (Point) geometry;
                    baseMapController.gotoSearchCoordinate(mapView, point.getX(), point.getY(), deviceName);
                }
                String tableName = "";
                if (feature.getFeatureTable() != null) {
                    tableName = feature.getFeatureTable().getTableName();
                }
                mapController.showOnlineResult(mapView, feature, tableName);
            }

            @Override
            public void onSearchDevice(int layerId, String device_code) {
                hideSoftKeyboard();
                searchDevice(layerId, device_code);
            }
        });

        addrSearchBar.setOnSearchListener(new FloatAddressSearchBar.onSearchListener() {
            @Override
            public void onSearchClosed() {
                baseMapController.clearMarkGraphic(mapView);
            }

            @Override
            public void onSearchSelected(double lng, double lat, String addr) {
                baseMapController.gotoSeaarchAddr(mapView, lng, lat, addr);
            }

            @Override
            public void onSearchNavi(double lng, double lat) {
                baseMapController.naviSearchAddr(mLocation, lng, lat);
            }

            @Override
            public void onCoordinateSearch(double lng, double lat) {
                baseMapController.gotoSearchCoordinate(mapView, lng, lat, null);
            }
        });
    }

    private void showLocationPerson(Point point) {
        if (point != null) {
            if (localLocLayer != null)
                mapView.getGraphicsOverlays().remove(localLocLayer);

            if (C.bLogMapToolLocForBaiduArcgis_debug){
                BitmapDrawable serviceLoc = (BitmapDrawable) getResources().getDrawable(R.drawable.ic_people_purple_400_24dp);
                MarkerSymbol symbol = SizeMarkerSymbol.sizeSymbol(serviceLoc, 36, 36);
                Graphic graphic = new Graphic(point, symbol);
                GraphicsOverlay pointLayer = new GraphicsOverlay();
                pointLayer.getGraphics().add(graphic);

                int lineColor = getResources().getColor(R.color.colorPrimary);
                SimpleLineSymbol circleSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, 2.0f);
                Polygon polygon = ArcgisUtils.getLocationCircleGeometry(point, 5, mapView.getSpatialReference());
                if (polygon != null) {
                    Graphic locCircleGraphic = new Graphic(polygon, circleSymbol);
                    pointLayer.getGraphics().add(locCircleGraphic);
                }

                mapView.getGraphicsOverlays().add(pointLayer);
                localLocLayer = pointLayer;
            }
        }
    }

    private void searchDevice(int layerId, String device_code) {
        String strHint = getResources().getString(R.string.querying_map);
        ProgressManager.getInstance().showProgress(this, null, strHint, false);
        mapController.queryDevice(null, layerId, device_code, new MapServiceCallback() {
            @Override
            public void onGetDevices(List<Feature> devices) {
                ProgressManager.getInstance().cancelProgress();
                deviceSearchBar.showSearchResult(devices);
            }

            @Override
            public void onError(String error) {
                ProgressManager.getInstance().cancelProgress();
                showToast(error);
            }
        });
    }

    private void onSingleTap(float x, float y) {
        android.graphics.Point screenPoint =
                new android.graphics.Point(Math.round(x), Math.round(y));
        Point mapPoint = mapView.screenToLocation(screenPoint);
        if (mapFlag == MapMode.offlineMode) {//当现实的是离线地图，才显示管线详情
            boolean isNetConnected = NetworkStatus.isNetworkConnected(this);
            if (!isNetConnected){
                showToast(getResources().getString(R.string.connect_server_error));
                return;
            }
            mapController.setQueryRsultCallback(new Container.ShowQueryRsultCallback() {
                @Override
                public void showResult(Feature ff, List<Field> fields, List<Feature> whichLayerList,
                                       String tableName, List<PipeQueryBean> allResults) {
                    mapController.showResult(mapView, ff, fields, screenPoint, tableName);
                    if (pipeSearchManager != null) {
                        pipeSearchManager.shotSearchPipeResultToShow(whichLayerList, tableName);
                    }
                }

                @Override
                public void showOnlineResult(Feature result0, List<Feature> results, String tabbleName, Map<String, List<Feature>> layersMap) {
                    mapController.showOnlineResult(mapView, result0, tabbleName);
                }
            });
            mapController.query_pipe(screenPoint, mapView);
        } else if (mapFlag == MapMode.troubleMode) {

        } else if (mapFlag == MapMode.analyzeMode) {
            boolean isNetConnected = NetworkStatus.isNetworkConnected(BaseApp.getInstance());
            if (!isNetConnected){
                showToast(getResources().getString(R.string.connect_server_error));
                return;
            }

            boolean canOpen = canOpenPipeAnalyzeMode();
            if (!canOpen)
                return;

            /*在线数据查询*/
            mapController.setOnlineQueryRsultCallback((isSucess, result0, results, tabbleName) -> {
                if (isSucess){
                    ProximityResult proximity2DResult = GeometryEngine.nearestCoordinate(result0.getGeometry(), mapPoint);
                    if (proximity2DResult != null && proximity2DResult.getCoordinate() != null){
                        final Point nearPoint = proximity2DResult.getCoordinate();

                        /*添加地图上的点的图层*/
                        addPointLayer(nearPoint);

                        /*设置管线类型和管线编号*/
                        String lineNo = "";
                        Map<String, Object>attrs =  result0.getAttributes();
                        if (attrs != null){
                            if (attrs.containsKey("OBJECTID")){
                                lineNo = attrs.get("OBJECTID").toString();
                            }
                        }
                        String pipe_id = lineNo;
                        String layer_id = ((ArcGISFeature)result0).getFeatureTable().getServiceLayerId() + "";
                        pipeAnalyzeResultBottomSheet.showStartPipeAnalyzeLayout(tabbleName, lineNo);
                        pipeAnalyzeResultBottomSheet.setOnPipeAnalyzeStartClicked( () ->
                                showCommitPointDialog(nearPoint, pipe_id, layer_id));
                    }else {
                        showToast("未点击到管网管线!");
                    }
                }else {
                    if (result0 == null)
                        showToast("未点击到管网管线!");
                }
            });
            mapController.query_pipe_online_byLayerName(screenPoint, mapView, MapController.TABLE_PIPE_NAME_CN);
        }
    }

    //提交爆管位置的点到水力分析库
    private void showCommitPointDialog(Point point, String pipe_id, String layer_id/*boolean bCommitPoint*/){
        /*if (bCommitPoint){
            commitPipeAnalyzePoint(point);
        }*/
        mapServiceTool.getLayerInfo(this, layer_id, new MapServiceCallback() {
            @Override
            public void onGetLayerInfo(boolean isSuccess, int errorCode, String errMsg, String layerdbname) {
                super.onGetLayerInfo(isSuccess, errorCode, errMsg, layerdbname);
                if (isSuccess) {
                    startPipeAnalyze(point, pipe_id, layerdbname);
                }
            }
        });
    }

    private void commitPipeAnalyzePoint(Point point){
        mapServiceTool.commitPipeAnalyzePoint(this, point, new MapServiceCallback(){
            @Override
            public void onCommitPipeAnalyzePoint(boolean isSuccess, int errorCode, String errMsg) {
                super.onCommitPipeAnalyzePoint(isSuccess, errorCode, errMsg);
            }
        });
    }

    private void startPipeAnalyze(Point point, String pipe_id, String layerDBName){
        pipeAnalyzeResultBottomSheet.updateData(null, null);
        clearPipeAnalyzeResultLayer();

        boolean bShowProgress = pipeAnalyzeResultBottomSheet.showProgressAndCanceBtn();
        mapController.pipeHttpAnalysis(this, mapView, pipe_id, layerDBName, !bShowProgress, new MapController.OnGetPipeJobMapResult() {
            @Override
            public void onGetJobHide() {
                pipeAnalyzeResultBottomSheet.setShowProgressCancelBtn();
                pipeAnalyzeResultBottomSheet.setOnPipeAnalyzeCancelClicked(() -> {
                    mapController.cancelAnalyzeTask();
                    pipeAnalyzeResultBottomSheet.hideProgressAndCanceBtn();
                    pipeAnalyzeResultBottomSheet.showStartPipeAnalyzeLayout();
                });
            }

            @Override
            public void onGetJobCanceled() {
                pipeAnalyzeResultBottomSheet.hideProgressAndCanceBtn();
                pipeAnalyzeResultBottomSheet.showStartPipeAnalyzeLayout();
            }

            @Override
            public void onGetResult(boolean isSuccess, PipeAnalysisResultBean resultBean, ArcGISMapImageLayer layer) {
                pipeAnalyzeResultBottomSheet.hideProgressAndCanceBtn();
                if (isSuccess){
                    showToast(getString(R.string.analysis_success));
                    ArcGISMap arcMap = mapView.getMap();
                    arcMap.getOperationalLayers().add(layer);
                    analysisIndexList.add(layer);
                    setPipeAnalyzeCallback();
                    if (resultBean != null){
                        pipeAnalyzeResultBottomSheet.updateData(resultBean, layer);
                        setPipeAnalyzeResultMapExtent(resultBean);
                    }
                }
            }
        });
    }

    private void setPipeAnalyzeResultMapExtent(PipeAnalysisResultBean resultBean){
        if (resultBean == null)
            return;
        PipeAnalysisResultBean.ResultBean.SummaryBean summaryBean = resultBean.getResult().getSummary();
        if (summaryBean != null){
            Envelope envelope = new Envelope(summaryBean.getXmin(), summaryBean.getYmin(),
                    summaryBean.getXmax(), summaryBean.getYmax(), mapView.getSpatialReference());
            mapView.setViewpointGeometryAsync(envelope, 300);
        }
    }

    private void setPipeAnalyzeCallback(){
        pipeAnalyzeResultBottomSheet.setPipeAnasCallback(new PipeAnalyzeResultBottomSheet.PipeAnalyzeCallback() {
            @Override
            public void showFeatureByCallout(Feature feature, List<Field> fields, String tableName) {
                mapController.clearAllSeletction();
                try {
                    if (feature != null) {
                        Callout callout = mapView.getCallout();
                        View calloutView = mapController.getPipenetCalloutViewFromFeature(mapView, feature, fields, tableName);
                        Point centerPoint = null;
                        Geometry geometry = feature.getGeometry();
                        if (geometry instanceof Polyline) {
                            Polyline polyline = (Polyline) feature.getGeometry();
                            Iterable<Point> points = polyline.getParts().getPartsAsPoints();
                            int pointCount = polyline.getParts().size();
                            double x = 0; double y = 0;
                            for (int i = 0; i < pointCount; i++) {
                                Point point = points.iterator().next();
                                x += point.getX();
                                y += point.getY();
                            }
                            centerPoint = new Point(x / pointCount, y / pointCount, polyline.getSpatialReference());
                        } else if (geometry instanceof Point) {
                            centerPoint = (Point) geometry;
                        }
                        callout.show(calloutView, centerPoint);//显示弹出框
                        //zoomToScale(centerPoint, 100);
                        android.graphics.Point screenPoint = mapView.locationToScreen(centerPoint);
                        screenPoint.y = screenPoint.y - BaseApp.dip2px(150);
                        Point locPoint = mapView.screenToLocation(screenPoint);
                        mapView.setViewpointCenterAsync(locPoint);
                    } else {
                        showToast(getString(R.string.feature_is_null));
                    }
                } catch (Exception e) {
                    showToast(e.getMessage());
                }
            }

            @Override
            public void hideCallout() {
                getArcgisUtils().hideArcgisMapCallout();
            }
        });
    }

    private boolean canOpenPipeAnalyzeMode() {
        boolean onlineMap = UiMainLayerManagerDailog.isOnlineMap();
        if (!onlineMap) {
            showToast(getResources().getString(R.string.maptool_analyze_offline_error));
            return false;
        }
        boolean isPipeOn = UiMainLayerManagerDailog.isPipeLayerOn();
        if (!isPipeOn) {
            showToast(getResources().getString(R.string.maptool_analyze_pipe_error));
            return false;
        }
        return true;
    }

    private void enterPipeAnalyzeMode(){
        isPipeAnalyzeOn = true;
        showPipeAnalyzeResultFragment();
        setPipeAnalyzeBtn();
        hideArcgisMapCallout();
    }

    private void exitPipeAnalyzeMode(){
        isPipeAnalyzeOn = false;
        clearPipeAnalyzeMap();
        hidePipeAnalyzeResultFragment();
        setPipeAnalyzeBtn();
        hideArcgisMapCallout();
    }

    private void clearPipeAnalyzeResultLayer(){
        if (analysisIndexList != null && analysisIndexList.size() > 0) {
            for (ArcGISMapImageLayer analysisLayer : analysisIndexList) {
                ArcGISMap arcMap = mapView.getMap();
                arcMap.getOperationalLayers().remove(analysisLayer);
            }
            analysisIndexList.clear();
        }
    }

    private void clearPipeAnalyzePointLayer(){
        if (troubleLayer != null) {
            mapView.getGraphicsOverlays().remove(troubleLayer);
            troubleLayer = null;
        }
    }

    private void clearPipeAnalyzeMap(){
        clearPipeAnalyzePointLayer();
        clearPipeAnalyzeResultLayer();
    }

    private void addPointLayer(Point point){
        clearPipeAnalyzePointLayer();

        troubleLayer = new GraphicsOverlay();
        Graphic graphic = new Graphic(point, symbolLoc);
        troubleLayer.getGraphics().add(graphic);
        mapView.getGraphicsOverlays().add(troubleLayer);
    }

    private void showPipeAnalyzeResultFragment() {
        pipeAnalyzeResultBottomSheet.setVisibility(View.VISIBLE);
        pipeAnalyzeResultBottomSheet.setMapController(mapController, mapView);
        pipeAnalyzeResultBottomSheet.onStart();
    }

    private void hidePipeAnalyzeResultFragment(){
        pipeAnalyzeResultBottomSheet.updateData(null, null);
        //pipeAnalyzeResultBottomSheet.onStop();
        pipeAnalyzeResultBottomSheet.setVisibility(View.GONE);
    }

    private void setPipeAnalyzeBtn(){
        imagePipeAnalyze.setSelected(isPipeAnalyzeOn);
        textPipeAnalyze.setSelected(isPipeAnalyzeOn);
    }

    private void closePipeBottomSheet() {
        mapController.clearAllSeletction();
        isPipeNetOn = false;
        imgPipenet.setImageResource(R.mipmap.float_pipenet_nor);
        BottomSheetBehavior behavior = pipeSearchManager.behavior;
        if (behavior.getState() != BottomSheetBehavior.STATE_HIDDEN)
            behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        hideArcgisMapCallout();
    }

    private void showPipeBottomSheet() {
        isPipeNetOn = true;
        imgPipenet.setImageResource(R.mipmap.float_pipenet_checked);
        pipeSearchManager.onstart(() -> closePipeBottomSheet());
        pipeSearchManager.setVisibility(View.VISIBLE);
        //pipeSearchManager.initPipeData(getAllFeatureTable());
        pipeSearchManager.initPipeDataByConfig(layerIndexConfigs);
        if (pipeSearchManager.getOnMapShowListenerIsNull()) {
            pipeSearchManager.setOnMapShowListener(feature -> mapController.showCallOutAtMap(mapView, feature));
        }
//        BottomSheetBehavior behavior = pipeSearchManager.behavior;
//        if (behavior.getBuild_state() == BottomSheetBehavior.STATE_HIDDEN){
//            behavior.setBuild_state(BottomSheetBehavior.STATE_COLLAPSED);
//        }
    }

    private void showPipeFragmentDialog() {
        isPipeNetOn = true;
        imgPipenet.setImageResource(R.mipmap.float_pipenet_checked);
        pipeSearchFragment = new PipeSearchFragment();
        pipeSearchFragment.initPipeData(getMapController().getAllFeatureTable(mapView));
        pipeSearchFragment.setOnMapShowListener(feature -> {
            if (feature != null) {
                mapController.showCallOutAtMap(mapView, feature);
            }
        });
        pipeSearchFragment.setCancelable(false);
        if (!pipeSearchFragment.isShowing()) {
            pipeSearchFragment.show(getSupportFragmentManager(), PipeSearchFragment
                    .class.getName());
            pipeSearchFragment.setHideCallback(() -> clossPipeFragmentDialog());
        }
    }

    private void clossPipeFragmentDialog() {
        isPipeNetOn = false;
        imgPipenet.setImageResource(R.mipmap.float_pipenet_nor);
        if (pipeSearchFragment.isShowing()) {
            pipeSearchFragment.dismiss();
        }
    }
    /**
     * 设置绘图工具
     */
    private void initMeasuringTool() {
        getArcgisUtils().hideArcgisMapCallout();

        measuringTool = new MeasuringTool(UiMapTool.this.mapView);
        //coordinatorLayout.startActionMode(measuringTool);
        startSupportActionMode(measuringTool);
    }

    private void checkCameraPermission(){
        String cameraPermission = Manifest.permission.CAMERA;
        String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        permissionHelper.requestPermissions("请授予[拍摄]，[读写]权限，否则无法进行拍摄", new PermissionHelper.PermissionListener() {
            @Override
            public void doAfterGrand(String... permission) {
                startQRCodeScan();
            }

            @Override
            public void doAfterDenied(String... permission) {
                showToast("获取权限失败，请授予权限后再试!");
            }
        }, cameraPermission, storagePermission);
    }
    /**
     * 二维码扫描设备信息
     */
    private final int QR_SCAN_REQUEST_CODE = 1001;
    private void startQRCodeScan() {
        Intent intent = new Intent();
        intent.setClass(this, CaptureActivity.class);
        intent.setAction(Intents.Scan.ACTION);
        startActivityForResult(intent, QR_SCAN_REQUEST_CODE);
    }

    @Override
    public void onBaseMapLoaded() {
        if (mapFlag == MapMode.analyzeMode) {
            boolean onlineMap = UiMainLayerManagerDailog.isOnlineMap();
            if (!onlineMap) {
                mapFlag = MapMode.offlineMode;
                exitPipeAnalyzeMode();
            }
        }
        if (measuringTool != null) {
            GraphicsOverlay overlay = measuringTool.getGraphicOverlay();
            if (overlay != null) {
                mapView.getGraphicsOverlays().add(overlay);
            }
        }
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public int setLayout() {
        return R.layout.ui_maptool;
    }

    @Override
    public boolean enableLoadMap() {
        return true;
    }

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

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

    @Override
    public boolean enableAmapLocationListener() {
        return true;
    }

    @Override
    public boolean enableMapMoveToLocation() {
        return true;
    }

    @Override
    public TextView getTextAddrView() {
        return null;
    }

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

        pipeSearchManager.destroy();
    }
}
