package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.AlarmDataBean;
import com.casic.dcms.bean.WellDetailBean;
import com.casic.dcms.databinding.ActivityMapWarningBinding;
import com.casic.dcms.mvp.presenter.impl.AlarmListPresenterImpl;
import com.casic.dcms.mvp.presenter.impl.WellDetailPresenterImpl;
import com.casic.dcms.mvp.view.IAlarmListView;
import com.casic.dcms.mvp.view.IWellDetailView;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.SaveKeyValues;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.BasemapStyle;
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.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.util.ArrayList;
import java.util.List;

public class WarningOnMapActivity extends AndroidxBaseActivity<ActivityMapWarningBinding> implements IAlarmListView, IWellDetailView {

    private static final String TAG = "WarningOnMapActivity";
    private final Context context = this;
    private final List<WellDetailBean.FeaturesBean> geometryList = new ArrayList<>();
    private AlarmListPresenterImpl alarmListPresenter;
    private WellDetailPresenterImpl detailPresenter;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("报警分布");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    public void initData() {
        viewBinding.mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        viewBinding.mapView.setViewpointScaleAsync(64000);
        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap basemap = new Basemap(ArcGisMapCreator.createNoGridLayer());
        arcGISMap.setBasemap(basemap);
        viewBinding.mapView.setMap(arcGISMap);

        int alarmTotal = (int) SaveKeyValues.getValue("alarmTotal", Constant.PAGE_LIMIT);
        alarmListPresenter = new AlarmListPresenterImpl(this);
        alarmListPresenter.onReadyRetrofitRequest(alarmTotal, 1);
        detailPresenter = new WellDetailPresenterImpl(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        viewBinding.expandMapView.setOnClickListener(v -> viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 0.5));
        viewBinding.minusMapView.setOnClickListener(v -> viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 2));

        viewBinding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, viewBinding.mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                android.graphics.Point screenPoint = new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY()));
                Point clickPoint = viewBinding.mapView.screenToLocation(screenPoint);
                if (geometryList.size() > 0) {
                    List<WellDetailBean.FeaturesBean> tempList = new ArrayList<>();
                    for (WellDetailBean.FeaturesBean featuresBean : geometryList) {
                        WellDetailBean.FeaturesBean.GeometryBean dataBean = featuresBean.getGeometry();
                        if (Math.abs(dataBean.getX() - clickPoint.getX()) <= 10 * Constant.DELTA_LNG_10 &&
                                Math.abs(dataBean.getY() - clickPoint.getY()) <= 10 * Constant.DELTA_LNG_10) {
                            tempList.add(featuresBean);
                        }
                    }
                    if (tempList.size() > 0) {
                        QMUIDialog.MenuDialogBuilder menuDialogBuilder = new QMUIDialog.MenuDialogBuilder(context);
                        menuDialogBuilder.setTitle("请选择您要查看的窨井");
                        for (WellDetailBean.FeaturesBean dataBean : tempList) {
                            menuDialogBuilder.addItem(dataBean.getAttributes().get编号(), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    View popupView = LayoutInflater.from(context).inflate(R.layout.popu_well, null);
                                    TextView wellCodeView = popupView.findViewById(R.id.wellCodeView);
                                    TextView wellTypeView = popupView.findViewById(R.id.wellTypeView);
                                    TextView wellPositionView = popupView.findViewById(R.id.wellPositionView);

                                    WellDetailBean.FeaturesBean.AttributesBean attributes = dataBean.getAttributes();
                                    wellCodeView.setText(attributes.get编号());
                                    wellTypeView.setText(attributes.get附属物名称());
                                    wellPositionView.setText(attributes.get所属道路());

                                    QMUIPopups.popup(context, QMUIDisplayHelper.dp2px(context, 290))
                                            .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                                            .view(popupView)
                                            .edgeProtection(QMUIDisplayHelper.dp2px(context, 20))
                                            .dimAmount(0.6f)
                                            .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                                            .onDismiss(null)
                                            .show(viewBinding.mapView);
                                }
                            });
                        }
                        menuDialogBuilder.create().show();
                    }
                }
                return super.onSingleTapConfirmed(e);
            }
        });
    }

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

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

    @Override
    protected void onDestroy() {
        viewBinding.mapView.dispose();
        if (alarmListPresenter != null) {
            alarmListPresenter.disposeRetrofitRequest();
        }
        if (detailPresenter != null) {
            detailPresenter.disposeRetrofitRequest();
        }
        super.onDestroy();
    }

    @Override
    public void obtainAlarmResult(AlarmDataBean resultBean) {
        if (resultBean.isSuccess()) {
            List<AlarmDataBean.DataBean.RowsBean> dataRows = resultBean.getData().getRows();
            for (AlarmDataBean.DataBean.RowsBean rowsBean : dataRows) {
                String queryParam = "编号='" + rowsBean.getWellCode() + "'";
                detailPresenter.onReadyRetrofitRequest(queryParam);
            }
        }
    }

    @Override
    public void obtainWellDetailResult(WellDetailBean resultBean) {
        List<WellDetailBean.FeaturesBean> features = resultBean.getFeatures();
        if (features.size() > 0) {
            WellDetailBean.FeaturesBean featuresBean = features.get(0);
            //将获取到的井数据缓存起来
            geometryList.add(featuresBean);
            WellDetailBean.FeaturesBean.GeometryBean geometryBean = featuresBean.getGeometry();
            //每获取一个点就绘制出
            addMarker(new Point(geometryBean.getX(), geometryBean.getY()));
        }
    }

    private void addMarker(Point point) {
        SimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 10);
        Graphic graphic = new Graphic(point, simpleMarkerSymbol);
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        ListenableList<Graphic> overlayGraphics = mGraphicsOverlay.getGraphics();
        ListenableList<GraphicsOverlay> graphicsOverlays = viewBinding.mapView.getGraphicsOverlays();
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }
}
