package com.tofly.ghrq_route.module.trouble.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
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.Polyline;
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.google.android.material.bottomsheet.BottomSheetBehavior;
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.BaseMapController;
import com.tofly.ghrq_route.base.ui.BaseMapFileActivity;
import com.tofly.ghrq_route.module.trouble.ui.view.BottomSheetTroubleDeviceSelect;
import com.tofly.ghrq_route.common.ui.view.FloatAddressSearchBar;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
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.Location.LocationUtil;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.map.domain.PipeQueryBean;
import com.tofly.ghrq_route.module.map.service.Container;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.AttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.DeviceAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.PipeAttributesBean;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.latte_core.base.IPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Amu on 2020/8/10.
 */
public class UiTroubleSelectDevice extends BaseMapFileActivity {
    @BindView(R.id.mapview)
    MapView mapView;
/*    @BindView(R.id.layout_device_list_root)
    FrameLayout layoutDeviceRoot;
    @BindView(R.id.text_show_detail)
    TextView textShowBottomDialog;*/
    @BindView(R.id.maptool_location_ll)
    LinearLayout layoutLocation;
    @BindView(R.id.bottom_sheet_detail_header)
    RelativeLayout layoutBottomSheetHeader;
    @BindView(R.id.layout_bottom_sheet_detail)
    BottomSheetTroubleDeviceSelect bottomSheetTroubleDeviceSelect;
/*    @BindView(R.id.main_hint_text)
    TextView mainHintText;*/
    @BindView(R.id.layout_float_search)
    FloatAddressSearchBar addressSearchBar;

    //private GraphicsOverlay troubleLayer = null;

    //private TroubleDeviceSelectBottomDialog deviceSelectBottomDialog;

    private ActionBar actionBar;

    private List<PipeAttributesBean> mPipeFeatures = new ArrayList<>();

    private List<DeviceAttributesBean> mDeviceFeatures = new ArrayList<>();

    private LocationUtil_xu.CoordinateClass mTappedCoordinate = null;

    private String mTappedAddr = "";

    private int mSelectGraphicId = -1;

    private BitmapDrawable imageLoc;

    private BitmapDrawable signedLoc;

    private SimpleLineSymbol selectLineSymbol;

    private SimpleLineSymbol unselectLineSymbol;

    private GraphicsOverlay deviceGraphicOverlay;

    private GraphicsOverlay pipeGraphicOverlay;

    private Map<AttributesBean, Graphic> graphicMap;

    private TroubleBean mTroubleBean = null;

    private int mSelectType = 0;    // 0: 新建 1： 查看 2： 更新

    public static final int SELECT_DEVICE_REQUEST_CODE = 0x100;

    private BaseMapController.MapMode mapFlag;//离线地图的标记

    @Subscribe
    public void onEventCallback(MyTroubleEvent event) {
        String eventMsg = event.message;
        if (eventMsg.equals(MyTroubleEvent.TROUBLE_SAVED) || eventMsg.equals(MyTroubleEvent.TROUBLE_UPLOADED)) {
            this.finish();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_next) {

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initView() {
        super.initView();
        // Initialize the helper class to use the Toolkit
        setDarkStatusBar();

        if (mapView != null) {
            double DEFAULTSCALE = 20000;
            mapView.setViewpointScaleAsync(DEFAULTSCALE);
            mapView.setBackgroundColor(Color.WHITE);
        }

        imageLoc = (BitmapDrawable) getResources().getDrawable(R.mipmap.danger_location);
        signedLoc = (BitmapDrawable) getResources().getDrawable(R.mipmap.location_edit);
        int overColor = getResources().getColor(R.color.green);
        int notOverColor = getResources().getColor(R.color.colorAccent);
        //unselectLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, notOverColor, 5.0f);
        //selectLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, overColor, 5.0f);
        /*检测本地用户地图配置信息是否存在*/

        initBottomSheet();
    }

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

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mSelectType = bundle.getInt(TroubleBean.TROUBLE_BEAN_SELECT_DEVICE_TYPE, TroubleBean.TROUBLE_SELECT_DEVICE_CHECK);
            mTroubleBean = (TroubleBean) bundle.getSerializable(TroubleBean.TROUBLE_BEAN_KEY);
            if (mTroubleBean != null) {
                mPipeFeatures = mTroubleBean.getPipeInfos();
                mDeviceFeatures = mTroubleBean.getDeviceInfos();
                if (mSelectType == TroubleBean.TROUBLE_SELECT_DEVICE_NEW_UPDATE) {
                    if (bundle.containsKey(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY)) {
                        mPipeFeatures = (List<PipeAttributesBean>)bundle.getSerializable(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY);
                    }
                    if (bundle.containsKey(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY)) {
                        mDeviceFeatures = (List<DeviceAttributesBean>) bundle.getSerializable(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY);
                    }
                    if (bundle.containsKey(LocationUtil.CURRENT_LOCATION_KEY)) {
                        mTappedCoordinate =
                                (LocationUtil_xu.CoordinateClass) bundle.getSerializable(LocationUtil.CURRENT_LOCATION_KEY);
                        if (mTappedCoordinate != null) {
                            mTappedAddr = mTappedCoordinate.addr;
                        }
                    }
                }
                String pipeInfoDesc = mTroubleBean.getPipeInfoDesc();
                String deviceInfoDesc = mTroubleBean.getDeviceInfoDesc();
                boolean selectable = (mSelectType != TroubleBean.TROUBLE_SELECT_DEVICE_CHECK);
                showBottomSheetDetail(mPipeFeatures, pipeInfoDesc, mDeviceFeatures, deviceInfoDesc, selectable);
            }
        }

        mapFlag = BaseMapController.MapMode.offlineMode;

        initListener();
    }

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

    @OnClick({R.id.btn_back})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back: {
                this.finish();
            }
            break;
/*            case R.id.text_show_detail: {
                if (deviceSelectBottomDialog == null) {
                    showDeviceSelectDialog();
                }else {
                    if (!deviceSelectBottomDialog.isShowing()){
                        deviceSelectBottomDialog.show();
                    }
                }
            }
            break;*/
        }
        if (addressSearchBar != null)
            addressSearchBar.clearInputFocus();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        if (mapView != null) {
            mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent event) {
                    addressSearchBar.clearInputFocus();
                    onSingleTap(event.getX(), event.getY());
                    return true;
                }

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

        addressSearchBar.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(mProjLoc, lng, lat);
            }

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

        amapLocationHelper.setReserveLocListener((isSuccess, addr) -> {
            if (isSuccess) {
                mTappedAddr = addr;
            }
        });
    }

    private void onSingleTap(float x, float y) {
        android.graphics.Point screenPoint =
                new android.graphics.Point(Math.round(x), Math.round(y));
        if (mapFlag == BaseMapController.MapMode.offlineMode && mSelectType != 1) {//当现实的是离线地图，才显示管线详情
            boolean isNetConnected = NetworkStatus.isNetworkConnected(this);
            if (!isNetConnected){
                showToast(getResources().getString(R.string.connect_server_error));
                return;
            }

            baseMapController.mapController.setQueryRsultCallback(new Container.ShowQueryRsultCallback() {
                @Override
                public void showResult(Feature ff, List<Field> fields,
                                       List<Feature> whichLayerList, String tableName, List<PipeQueryBean> allResults) {
                    if (allResults != null) {
                        List<PipeAttributesBean> pipeFeatures = new ArrayList<>();
                        List<DeviceAttributesBean> deviceFeatures = new ArrayList<>();
                        Point mapPoint = mapView.screenToLocation(screenPoint);
                        Geometry geometry = null;
                        for (PipeQueryBean queryBean : allResults) {
                            List<Feature> features = queryBean.whichLayerList;
                            for (Feature feature : features) {
                                if (feature.getGeometry() instanceof Polyline) {
                                    PipeAttributesBean attributesBean = new PipeAttributesBean(feature);
                                    pipeFeatures.add(attributesBean);
                                }else {
                                    DeviceAttributesBean attributesBean = new DeviceAttributesBean(feature);
                                    deviceFeatures.add(attributesBean);
                                }
                                if (geometry == null) {
                                    geometry = feature.getGeometry();
                                }
                            }
                        }
                        if (geometry != null) {
                            mapPoint = geometry.getExtent().getCenter();
                        }
                        mPipeFeatures = pipeFeatures;
                        mDeviceFeatures = deviceFeatures;
                        mTappedCoordinate = new LocationUtil_xu.CoordinateClass(mapPoint.getX(), mapPoint.getY());
                        showBottomSheetDetail(mPipeFeatures, null, mDeviceFeatures, null, true);
                        reserveLocation(mapPoint);
                    }
                }

                @Override
                public void showOnlineResult(Feature result0, List<Feature> results, String tabbleName, Map<String, List<Feature>> allResults) {
                    if (allResults != null) {
                        List<PipeAttributesBean> pipeFeatures = new ArrayList<>();
                        List<DeviceAttributesBean> deviceFeatures = new ArrayList<>();
                        Point mapPoint = mapView.screenToLocation(screenPoint);
                        Geometry geometry = null;
                        for (Map.Entry<String, List<Feature>> entrySet : allResults.entrySet()) {
                            List<Feature> features = entrySet.getValue();
                            for (Feature feature : features) {
                                if (feature.getGeometry() instanceof Polyline) {
                                    PipeAttributesBean attributesBean = new PipeAttributesBean(feature);
                                    pipeFeatures.add(attributesBean);
                                }else {
                                    DeviceAttributesBean attributesBean = new DeviceAttributesBean(feature);
                                    deviceFeatures.add(attributesBean);
                                }
                                if (geometry == null) {
                                    geometry = feature.getGeometry();
                                }
                            }
                        }
                        if (geometry != null) {
                            mapPoint = geometry.getExtent().getCenter();
                        }
                        mPipeFeatures = pipeFeatures;
                        mDeviceFeatures = deviceFeatures;
                        mTappedCoordinate = new LocationUtil_xu.CoordinateClass(mapPoint.getX(), mapPoint.getY());
                        reserveLocation(mapPoint);
                        showBottomSheetDetail(mPipeFeatures, null, mDeviceFeatures, null, true);
                    }
                }
            });
            baseMapController.mapController.query_pipe_1(screenPoint, mapView);
            if (mPipeFeatures != null)
                mPipeFeatures.clear();
            if (deviceGraphicOverlay != null)
                deviceGraphicOverlay.getGraphics().clear();
            if (mDeviceFeatures != null)
                mDeviceFeatures.clear();
            if (pipeGraphicOverlay != null)
                pipeGraphicOverlay.getGraphics().clear();
            bottomSheetTroubleDeviceSelect.initBottomSheetDetail(mPipeFeatures, null, mDeviceFeatures, null, true);
        }
    }

    private void initBottomSheet() {
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetTroubleDeviceSelect);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED);
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    setBottomSheetBehavior(bottomSheet);
                } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    setBottomSheetBehavior(bottomSheet);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
    }

    private void setBottomSheetBehavior(View bottomSheet) {
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetTroubleDeviceSelect);
        if (bottomSheetBehavior != null) {
            if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {

            } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {

            } else if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HALF_EXPANDED) {

            }
        }
    }

    private void showBottomSheetDetail(List<PipeAttributesBean> pipeFeatures, String pipeDesc,
                                       List<DeviceAttributesBean> deviceFeatures, String deviceDesc, boolean selectable) {
        bottomSheetTroubleDeviceSelect.initBottomSheetDetail(pipeFeatures, pipeDesc, deviceFeatures, deviceDesc, selectable);
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetTroubleDeviceSelect);
        //bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HALF_EXPANDED);
        bottomSheetBehavior.setHideable(false);
        bottomSheetTroubleDeviceSelect.setEditable(mSelectType != TroubleBean.TROUBLE_SELECT_DEVICE_CHECK);

        renderDevicesOnMap();

        bottomSheetTroubleDeviceSelect.onPipeItemClicked((item, position) -> {
            PipeAttributesBean pipeAttributesBean = item;
            if (graphicMap.containsKey(pipeAttributesBean)) {
                Graphic graphic = graphicMap.get(pipeAttributesBean);
                if (graphic != null) {
                    renderSelectPipeOnMap(pipeAttributesBean, graphic);
                }
            }
        });

        bottomSheetTroubleDeviceSelect.onDeviceItemClicked((item, position) -> {
            DeviceAttributesBean deviceAttributesBean = item;
            if (graphicMap.containsKey(deviceAttributesBean)) {
                Graphic graphic = graphicMap.get(deviceAttributesBean);
                if (graphic != null) {
                    renderSelectPointOnMap(deviceAttributesBean, graphic);
                }
            }
        });

        bottomSheetTroubleDeviceSelect.onDeviceSelectConfirm(view -> {
            onDeviceConfirm();
        });
    }

    private void onDeviceConfirm() {
        List<PipeAttributesBean> pipeFeatures = new ArrayList<>();
        List<DeviceAttributesBean> deviceFeatures = new ArrayList<>();
        if (bottomSheetTroubleDeviceSelect != null) {
            pipeFeatures = bottomSheetTroubleDeviceSelect.getSelectedPipeFeatures();
            deviceFeatures = bottomSheetTroubleDeviceSelect.getSelectedDeviceFeatures();
        }

        if (pipeFeatures.isEmpty() && deviceFeatures.isEmpty()) {
            showToast("没有选中的隐患设施或管线");
        }else {
            if (mSelectType == TroubleBean.TROUBLE_SELECT_DEVICE_NEW ||
                    mSelectType == TroubleBean.TROUBLE_SELECT_DEVICE_NEW_UPDATE) {
                onSelectDeviceForReturn();
            } else if (mSelectType == TroubleBean.TROUBLE_SELECT_DEVICE_UPDATE) {
                onSelectDeviceForUpdate();
            }
        }
    }

    private void onSelectDeviceForReturn() {
        List<PipeAttributesBean> pipeFeatures = bottomSheetTroubleDeviceSelect.getSelectedPipeFeatures();
        List<DeviceAttributesBean> deviceFeatures = bottomSheetTroubleDeviceSelect.getSelectedDeviceFeatures();
        Bundle bundle = new Bundle();
        if (pipeFeatures.size() >= 0) {
            String pipeNote = bottomSheetTroubleDeviceSelect.getPipeNote();
            bundle.putSerializable(PipeAttributesBean.TROUBLE_PIPE_ATTRIBUTES_BEAN_KEY, (Serializable) pipeFeatures);
            bundle.putString(TroubleBean.TROUBLE_PIPE_NOTE_KEY, pipeNote);
        }
        if (deviceFeatures.size() >= 0) {
            String deviceNote = bottomSheetTroubleDeviceSelect.getDeviceNote();
            bundle.putSerializable(DeviceAttributesBean.TROUBLE_DEVICE_ATTRIBUTES_BEAN_KEY, (Serializable) deviceFeatures);
            bundle.putString(TroubleBean.TROUBLE_DEVICE_NOTE_KEY, deviceNote);
        }

        if (mTappedCoordinate != null) {
            mTappedCoordinate.addr = mTappedAddr;
            bundle.putSerializable(LocationUtil.CURRENT_LOCATION_KEY, mTappedCoordinate);
        }

        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    private void onSelectDeviceForUpdate() {
        updatePipeDevice();
    }

    private void renderDevicesOnMap() {
        graphicMap = new HashMap<>();
        List<Geometry> geometries = new ArrayList<>();

        if (mDeviceFeatures != null) {
            if (deviceGraphicOverlay == null) {
                deviceGraphicOverlay = new GraphicsOverlay();
                mapView.getGraphicsOverlays().add(deviceGraphicOverlay);
            }else
                deviceGraphicOverlay.getGraphics().clear();

            for (AttributesBean deviceFeature : mDeviceFeatures) {
                DeviceAttributesBean attributesBean = (DeviceAttributesBean) deviceFeature ;
                Graphic graphic = renderPointOnMap(attributesBean);
                graphicMap.put(attributesBean, graphic);

                String jsonGeo = deviceFeature.getGeometry();
                Geometry geometry = Geometry.fromJson(jsonGeo, mapView.getSpatialReference());
                if (geometry != null) {
                    geometries.add(geometry);
                }
            }
        }

        if (mPipeFeatures != null) {
            if (pipeGraphicOverlay == null) {
                pipeGraphicOverlay = new GraphicsOverlay();
                mapView.getGraphicsOverlays().add(pipeGraphicOverlay);
            }else
                pipeGraphicOverlay.getGraphics().clear();

            for (AttributesBean feature : mPipeFeatures) {
                PipeAttributesBean attributesBean = (PipeAttributesBean) feature ;
                Graphic graphic = renderPipeOnMap(attributesBean);
                graphicMap.put(attributesBean, graphic);

                String jsonGeo = feature.getGeometry();
                Geometry geometry = Geometry.fromJson(jsonGeo, mapView.getSpatialReference());
                if (geometry != null) {
                    geometries.add(geometry);
                }
            }
        }

        if (geometries.size() > 0) {
            try {
                Handler handler = new Handler(getMainLooper());
                handler.postDelayed(() -> {
                    Geometry geometry = GeometryEngine.union(geometries);
                    if (geometry != null && !geometry.getExtent().isEmpty()) {
                        ListenableFuture<Boolean> future = mapView.setViewpointGeometryAsync(geometry, ArcgisUtils.render_padding_wide);
                        future.addDoneListener(() -> {
                            try {
                                Boolean isSuccess = future.get();
                                if (isSuccess) {
                                    double scale = mapView.getMapScale();
                                    Point center = geometry.getExtent().getCenter();
                                    int offset = BaseApp.dip2px(150);
                                    Point dstPoint =  ArcgisUtils.pointAddOffset(mapView, center, 0, offset);
                                    mapView.setViewpointCenterAsync(dstPoint, scale);
                                }
                            } catch (ExecutionException | InterruptedException e) {
                                e.printStackTrace();
                            }
                        });
                    }
                }, 500);
            }catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private Graphic renderPointOnMap(DeviceAttributesBean attributes) {
        Graphic graphic = null;
        if (mapView != null && attributes != null) {
            if (attributes.getX() != null && attributes.getY() != null) {
                double lng = Double.parseDouble(attributes.getX());
                double lat = Double.parseDouble(attributes.getY());
                MarkerSymbol symbol = SizeMarkerSymbol.sizeSymbol(imageLoc, 18, 18);
                Point point = new Point(lng, lat, mapView.getSpatialReference());
                Graphic deviceGraphic = new Graphic(point, symbol);
                deviceGraphicOverlay.getGraphics().add(deviceGraphic);
                graphic = deviceGraphic;
            }
        }
        return graphic;
    }

    private Graphic renderPipeOnMap(PipeAttributesBean attributes) {
        Graphic graphic = null;
        if (mapView != null && attributes != null) {
            if (attributes.getGeometry() != null) {
                String jsonGeo = attributes.getGeometry();
                Geometry geometry = Geometry.fromJson(jsonGeo, mapView.getSpatialReference());
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, -16777216, 3.0F);//线的样式
                Graphic pipeGraphic = new Graphic(geometry, lineSymbol);
                pipeGraphicOverlay.getGraphics().add(pipeGraphic);
                graphic = pipeGraphic;
            }
        }
        return graphic;
    }

    private void renderSelectPointOnMap(DeviceAttributesBean attributes, Graphic deviceGraphic) {
        if (mapView != null && attributes != null) {
            if (pipeGraphicOverlay != null) {
                pipeGraphicOverlay.clearSelection();
            }
            if (deviceGraphicOverlay != null) {
                deviceGraphicOverlay.clearSelection();
                List<Graphic> graphics = new ArrayList<>();
                graphics.add(deviceGraphic);
                deviceGraphicOverlay.selectGraphics(graphics);
            }
            if (attributes.getGeometry() != null) {
                String jsonGeo = attributes.getGeometry();
                Geometry geometry = Geometry.fromJson(jsonGeo, mapView.getSpatialReference());
                if (geometry != null && geometry.getExtent() != null) {
                    Envelope envelope = geometry.getExtent();
                    Point center = envelope.getCenter();
                    android.graphics.Point screenPoint = mapView.locationToScreen(center);
                    screenPoint.y = screenPoint.y + BaseApp.dip2px(150);
                    Point locPoint = mapView.screenToLocation(screenPoint);
                    if (locPoint != null)
                        mapView.setViewpointCenterAsync(locPoint);
                }
            }
        }
    }

    private void renderSelectPipeOnMap(PipeAttributesBean attributes, Graphic pipeGraphic) {
        if (mapView != null && attributes != null) {
            if (deviceGraphicOverlay != null) {
                deviceGraphicOverlay.clearSelection();
            }
            if (pipeGraphicOverlay != null) {
                pipeGraphicOverlay.clearSelection();
                List<Graphic> graphics = new ArrayList<>();
                graphics.add(pipeGraphic);
                pipeGraphicOverlay.selectGraphics(graphics);
            }

            if (attributes.getGeometry() != null) {
                String jsonGeo = attributes.getGeometry();
                Geometry geometry = Geometry.fromJson(jsonGeo, mapView.getSpatialReference());
                if (geometry != null && geometry.getExtent() != null) {
                    Envelope envelope = geometry.getExtent();
                    Point center = envelope.getCenter();
                    android.graphics.Point screenPoint = mapView.locationToScreen(center);
                    screenPoint.y = screenPoint.y + BaseApp.dip2px(150);
                    Point locPoint = mapView.screenToLocation(screenPoint);
                    if (locPoint != null)
                        mapView.setViewpointCenterAsync(locPoint);
                }
            }
        }
    }

    private void reserveLocation(Point mapPoint) {
        mTappedAddr = "";
        Point location = ArcgisUtils.projectLocationDefault(mapPoint.getX(), mapPoint.getY());
        if (location != null)
            amapLocationHelper.reserveLocation(location.getX(), location.getY());
    }

    private TroubleBean collectData() {
        TroubleBean troubleUpdate = new TroubleBean();
        troubleUpdate.setId(mTroubleBean.getId());
        /*隐患地址*/
        if (mTappedCoordinate != null) {
            String lng = LocationUtil.formatLocation(mTappedCoordinate.Longtitude);
            troubleUpdate.setLocationX(lng);
            String lat = LocationUtil.formatLocation(mTappedCoordinate.Latitude);
            troubleUpdate.setLocationY(lat);
            String addr = mTappedAddr;
            troubleUpdate.setAddress(addr);
        }

        List<PipeAttributesBean> pipeFeatures = bottomSheetTroubleDeviceSelect.getSelectedPipeFeatures();
        List<DeviceAttributesBean> deviceFeatures = bottomSheetTroubleDeviceSelect.getSelectedDeviceFeatures();
        String pipeNote = bottomSheetTroubleDeviceSelect.getPipeNote();
        String deviceNote = bottomSheetTroubleDeviceSelect.getDeviceNote();
        if (pipeFeatures != null && pipeFeatures.size() > 0) {
           troubleUpdate.setPipeInfos(pipeFeatures);
        }
        if (pipeNote != null && !pipeNote.isEmpty()) {
            troubleUpdate.setPipeInfoDesc(pipeNote);
        }
        if (deviceFeatures != null && deviceFeatures.size() > 0) {
            troubleUpdate.setDeviceInfos(deviceFeatures);
        }
        if (deviceNote != null && !deviceNote.isEmpty()) {
            troubleUpdate.setDeviceInfoDesc(deviceNote);
        }
        return troubleUpdate;
    }

    private void updatePipeDevice() {
        TroubleBean troubleUpdate = collectData();
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        TroubleTool troubleTool = TroubleTool.getInstance();
        troubleTool.updatePipeDeviceNoSave(this, troubleUpdate, new TroubleCallBack(){
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MyTroubleEvent(MyTroubleEvent.TROUBLE_DEVICE_UPDATED));
                    showUpdatedFinishedDialog();
                }
            }
        });
    }

    private void showUpdatedFinishedDialog() {
        int title = R.string.trouble_select_device_title;
        int msg = R.string.trouble_select_device_update_ok;
        DialogUtil.showAlertWithConfirmButton(this, title, msg, false, (dialogInterface, i) -> this.finish());
    }

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

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

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

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

    @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
    public Button getAddPhotoBtn() {
        return null;
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return null;
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return null;
    }

    @Override
    protected void onStop() {
        BaseApp.cancelRequest(getClass().getName());
        super.onStop();
    }

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