package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.view.MotionEvent;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.base.BaseActivity;
import com.casic.dcms.bean.PointFutureBean;
import com.casic.dcms.bean.ShopFeatureBean;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.callback.ICommunityListener;
import com.casic.dcms.utils.callback.ILocationListener;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.BasemapStyle;
import com.esri.arcgisruntime.mapping.GeoElement;
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.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

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

import butterknife.BindView;
import butterknife.OnClick;

public class ArcGISMapActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "ArcGISMapActivity";
    private Context context = ArcGISMapActivity.this;
    @BindView(R.id.gisTopLayout)
    QMUITopBarLayout gisTopLayout;
    @BindView(R.id.mapView)
    MapView mapView;

    private FeatureLayer communityLayer, pointLayer, packageLayer;
    private Point clickPoint;
    private Gson gson;
    private String caseType;

    private ListenableList<Graphic> overlayGraphics;
    private ListenableList<GraphicsOverlay> graphicsOverlays;
    private GraphicsOverlay mGraphicsOverlay;
    private QMUITipDialog loadingDialog;

    @Override
    public int initLayoutView() {
        return R.layout.activity_gis;
    }

    @Override
    protected void setupTopBarLayout() {
        gisTopLayout.setTitle("选择点位").setTextColor(ContextCompat.getColor(this, R.color.white));
        gisTopLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.mainThemeColor));
        gisTopLayout.addLeftImageButton(R.drawable.ic_left_white, 0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        caseType = getIntent().getStringExtra("type");
        gson = new Gson();
        mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        mapView.setViewpointScaleAsync(2800);//数字越大，放大比例越小，缩放比例[36000,250]

        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        ArcGISTiledLayer baseLayer = new ArcGISTiledLayer(Constant.BASE_MAP_SERVICE_URL);
        Basemap basemap = new Basemap(baseLayer);
        arcGISMap.setBasemap(basemap);
        mapView.setMap(arcGISMap);

        //设置地图显示在中心位置
        Point point = new Point(Constant.DEFAULT_LNG, Constant.DEFAULT_LAT, mapView.getSpatialReference());
        mapView.setViewpointCenterAsync(point, 2800);//标注到指定经纬度并放大地图显示

        //网格和社区 (ID: 13)
        ServiceFeatureTable communityFeatureTable = new ServiceFeatureTable(Constant.BASE_MAP_SERVICE_URL + "/13");
        communityFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        communityLayer = new FeatureLayer(communityFeatureTable);
        /**
         * 设置地图数据图层，这里可以添加很多别的图层
         *
         * 如果是事件，加载单元网格图层，如果是部件，加载部件图层
         * */
        switch (caseType) {
            case "部件":
                //部件点图层 (ID: 0)
                ServiceFeatureTable pointFeatureTable = new ServiceFeatureTable(Constant.COMPONENT_SERVICE_URL + "/0");
                pointFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
                pointLayer = new FeatureLayer(pointFeatureTable);
                arcGISMap.getOperationalLayers().add(pointLayer);
                break;
            case "三包上报":
                //门前三包 (ID: 1)
                ServiceFeatureTable packageFeatureTable = new ServiceFeatureTable(Constant.COMPONENT_SERVICE_URL + "/1");
                packageFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
                packageLayer = new FeatureLayer(packageFeatureTable);
                arcGISMap.getOperationalLayers().add(packageLayer);
                break;
        }
        mapView.setMap(arcGISMap);

        //Marker相关Layer
        mGraphicsOverlay = new GraphicsOverlay();
        overlayGraphics = mGraphicsOverlay.getGraphics();
        graphicsOverlays = mapView.getGraphicsOverlays();

        loadingDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("定位中，请稍后")
                .create();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                android.graphics.Point screenPoint = new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY()));
                clickPoint = mapView.screenToLocation(screenPoint);
                addMarker(clickPoint);

                //查询参数
                QueryParameters queryParameters = new QueryParameters();
                queryParameters.setGeometry(clickPoint);//查询点击位置所在的社区

                //不管是事件还是部件，都的需要社区信息
                LocationHelper.obtainCurrentCommunity(communityLayer, queryParameters, new ICommunityListener() {
                    @Override
                    public void onCommunityFeatureGet(Feature feature) {
                        if (caseType.equals("事件")) {
                            Map<String, Object> attributes = feature.getAttributes();
                            showDialog((String) attributes.get("GBID"), (String) attributes.get("Note"));
                        }
                    }
                });
                switch (caseType) {
                    case "部件":
                        LocationHelper.obtainCurrentCommunity(communityLayer, queryParameters, new ICommunityListener() {
                            @Override
                            public void onCommunityFeatureGet(Feature feature) {
                                //先取社区信息，再取部件信息
                                List<Map<String, Object>> pointList = new ArrayList<>();
                                ListenableFuture<IdentifyLayerResult> pointFuture = mapView.identifyLayerAsync(pointLayer, screenPoint, 15, false, -1);
                                pointFuture.addDoneListener(() -> {
                                    try {
                                        IdentifyLayerResult identifyLayerResult = pointFuture.get();
                                        List<GeoElement> elements = identifyLayerResult.getElements();
                                        for (GeoElement element : elements) {
                                            Map<String, Object> attributes = element.getAttributes();
                                            pointList.add(attributes);
                                        }
//                                        Log.d(TAG, "onCommunityFeatureGet: " + gson.toJson(pointList));
                                        runOnUiThread(() -> {
                                            QMUIDialog.MenuDialogBuilder menuDialogBuilder = new QMUIDialog.MenuDialogBuilder(context);
                                            menuDialogBuilder.setTitle("请选择您要上报的部件");
                                            Type gridType = new TypeToken<List<PointFutureBean>>() {
                                            }.getType();
                                            List<PointFutureBean> beans = gson.fromJson(gson.toJson(pointList), gridType);
                                            for (PointFutureBean featureBean : beans) {
                                                menuDialogBuilder.addItem(featureBean.getObjid() + "（" + featureBean.getObjname() + "）", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                        showDialog(
                                                                featureBean.getBgid(),
                                                                featureBean.getObjid(),
                                                                featureBean.getObjname(),
                                                                featureBean.getDl(),
                                                                featureBean.getXl(),
                                                                (String) feature.getAttributes().get("Note"));
                                                    }
                                                });
                                            }
                                            menuDialogBuilder.create().show();
                                        });
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                });
                            }
                        });
                        break;
                    case "三包上报":
                        LocationHelper.obtainCurrentCommunity(communityLayer, queryParameters, new ICommunityListener() {
                            @Override
                            public void onCommunityFeatureGet(Feature feature) {
                                //先取社区信息，再取部件信息
                                List<Map<String, Object>> shopList = new ArrayList<>();
                                ListenableFuture<IdentifyLayerResult> packageFuture = mapView.identifyLayerAsync(packageLayer, screenPoint, 15, false, -1);
                                packageFuture.addDoneListener(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            IdentifyLayerResult identifyLayerResult = packageFuture.get();
                                            List<GeoElement> elements = identifyLayerResult.getElements();
                                            for (GeoElement element : elements) {
                                                Map<String, Object> attributes = element.getAttributes();
                                                shopList.add(attributes);
                                            }
//                                            Log.d(TAG, "shopList: " + gson.toJson(shopList));
                                            runOnUiThread(() -> {
                                                QMUIDialog.MenuDialogBuilder menuDialogBuilder = new QMUIDialog.MenuDialogBuilder(context);
                                                menuDialogBuilder.setTitle("请选择您要上报的部件");
                                                Type shopType = new TypeToken<List<ShopFeatureBean>>() {
                                                }.getType();
                                                List<ShopFeatureBean> shopBeans = gson.fromJson(gson.toJson(shopList), shopType);

                                                //设置dialog列表
                                                menuDialogBuilder.setTitle("请选择商户");
                                                for (ShopFeatureBean featureBean : shopBeans) {
                                                    menuDialogBuilder.addItem(featureBean.getObjectid() + "（" + featureBean.getDutyname() + "）", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                            showShopDialog(featureBean.getBgid(),
                                                                    (String) feature.getAttributes().get("Note"),
                                                                    featureBean.getDutyname(),
                                                                    String.valueOf(featureBean.getObjectid()));
                                                        }
                                                    });
                                                }
                                                menuDialogBuilder.create().show();
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        });
                        break;
                }
                return true;
            }
        });
    }

    /**
     * 三包
     */
    private void showShopDialog(String gridId, String communityName, String shopName, String shopID) {
        if (!this.isFinishing()) {
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("提示")
                    .setMessage("已选择商户：" + shopName + "\r\n确认提交？")
                    .setCanceledOnTouchOutside(false)
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.putExtra("shopName", shopName);
                            intent.putExtra("shopID", shopID);
                            intent.putExtra("latitude", clickPoint.getY());
                            intent.putExtra("longitude", clickPoint.getX());
                            intent.putExtra("community", communityName);
                            intent.putExtra("gridId", gridId);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    })
                    .create().show();
        }
    }

    /**
     * 部件
     */
    private void showDialog(String gridId, String objId, String objName, String largeType, String smallType, String communityName) {
        if (!this.isFinishing()) {
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("提示")
                    .setMessage("该事件地点所在网格为[" + gridId + "]"
                            + "\r\n选择部件为：" + objId + "(" + objName + ")"
                            + "\r\n部件大类为：" + largeType
                            + "\r\n小类为：" + smallType
                            + "\r\n确认提交？")
                    .setCanceledOnTouchOutside(false)
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.putExtra("latitude", clickPoint.getY());
                            intent.putExtra("longitude", clickPoint.getX());
                            intent.putExtra("community", communityName);
                            intent.putExtra("gridId", gridId);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    })
                    .create().show();
        }
    }

    /**
     * 事件
     */
    private void showDialog(String gridId, String communityName) {
        if (!this.isFinishing()) {
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("提示")
                    .setMessage("该事件所在地点网格为[" + gridId + "]"
                            + "\r\n所在社区为：" + communityName
                            + "\r\n确认选择？")
                    .setCanceledOnTouchOutside(false)
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.putExtra("latitude", clickPoint.getY());
                            intent.putExtra("longitude", clickPoint.getX());
                            intent.putExtra("community", communityName);
                            intent.putExtra("gridId", gridId);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }).create().show();
        }
    }

    /**
     * //[116.598359, 28.247870, 0.000000, NaN] SR: 4326
     */
    private void addMarker(Point clickPoint) {
        SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 15);
        if (overlayGraphics != null && graphicsOverlays != null) {
            overlayGraphics.clear();
            graphicsOverlays.clear();
        }
        Graphic graphic = new Graphic(clickPoint, simpleMarkerSymbol);
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }

    @OnClick({R.id.expandMapView, R.id.minusMapView, R.id.removeToLocalView})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.expandMapView:
                mapView.setViewpointScaleAsync(mapView.getMapScale() * 0.5);
                break;
            case R.id.minusMapView:
                mapView.setViewpointScaleAsync(mapView.getMapScale() * 2);
                break;
            case R.id.removeToLocalView:
                loadingDialog.show();
                LocationHelper.obtainCurrentLocationByGD(this, new ILocationListener() {
                    @Override
                    public void onLocationGet(Location location) {

                    }

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation != null) {
                            mapView.setViewpointCenterAsync(new Point(aMapLocation.getLongitude(), aMapLocation.getLatitude()), 1000);
                            loadingDialog.dismiss();
                        }
                    }
                }, true);
                break;
            default:
                break;
        }
    }

    protected void onResume() {
        super.onResume();
        mapView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.pause();
    }

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