package com.casic.dcms.view.map;

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 androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityMapWarningBinding;
import com.casic.dcms.model.AlarmDataBean;
import com.casic.dcms.model.WellDetailBean;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.vm.AlarmViewModel;
import com.casic.dcms.vm.WellViewModel;
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.gyf.immersionbar.ImmersionBar;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.utils.SaveKeyValues;
import com.pengxh.androidx.lite.vm.LoadState;
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> {

    private static final String TAG = "WarningOnMapActivity";
    private final Context context = this;
    private final List<WellDetailBean.FeaturesBean> geometryList = new ArrayList<>();
    private AlarmViewModel alarmViewModel;
    private WellViewModel wellViewModel;

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        viewBinding.titleBarLayout.titleView.setText("报警分布");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

    @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", LocaleConstant.PAGE_LIMIT);
        alarmViewModel = new ViewModelProvider(this).get(AlarmViewModel.class);
        alarmViewModel.obtainAlarmList(alarmTotal, 1);

        wellViewModel = new ViewModelProvider(this).get(WellViewModel.class);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        viewBinding.expandMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 0.5);
            }
        });
        viewBinding.minusMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 2);
            }
        });

        alarmViewModel.resultModel.observe(this, new Observer<AlarmDataBean>() {
            @Override
            public void onChanged(AlarmDataBean alarmDataBean) {
                if (alarmDataBean.getCode() == 200) {
                    List<AlarmDataBean.DataBean.RowsBean> dataRows = alarmDataBean.getData().getRows();
                    for (AlarmDataBean.DataBean.RowsBean rowsBean : dataRows) {
                        String queryParam = "编号='" + rowsBean.getWellCode() + "'";
                        wellViewModel.obtainWellDetail(queryParam);
                    }
                }
            }
        });

        alarmViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {

            }
        });

        wellViewModel.resultModel.observe(this, new Observer<WellDetailBean>() {
            @Override
            public void onChanged(WellDetailBean wellDetailBean) {
                List<WellDetailBean.FeaturesBean> features = wellDetailBean.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()));
                }
            }
        });

        wellViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {

            }
        });

        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 * LocaleConstant.DELTA_LNG_10 &&
                                Math.abs(dataBean.getY() - clickPoint.getY()) <= 10 * LocaleConstant.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() {
        viewBinding.mapView.resume();
        super.onResume();
    }

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

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

    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);
    }
}
