package com.casic.dcms.view.pipeline;

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

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityMapAlarmBinding;
import com.casic.dcms.model.WellAlarmListBean;
import com.casic.dcms.model.WellDetailBean;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.ViewGroupKit;
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.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.widget.TitleBarView;
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 AlarmOnMapActivity extends AndroidxBaseActivity<ActivityMapAlarmBinding> {

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

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);
        binding.titleView.setOnClickListener(new TitleBarView.OnClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {

            }
        });
    }

    @Override
    protected void observeRequestState() {
        wellViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(AlarmOnMapActivity.this, "数据加载中，请稍后");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

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

        wellViewModel = new ViewModelProvider(this).get(WellViewModel.class);
        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()));
                }
            }
        });

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            List<WellAlarmListBean.DataBean.RowsBean> dataBeans = extras.getParcelableArrayList("rows_list");
            if (dataBeans == null) {
                return;
            }
            for (WellAlarmListBean.DataBean.RowsBean dataBean : dataBeans) {
                String queryParam = "编号='" + dataBean.getWellCode() + "'";
                Log.d(TAG, "queryParam: " + queryParam);
                wellViewModel.getWellDetail(context, queryParam);
            }
        }
    }

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

        binding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, binding.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 = binding.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(binding.mapView);
                                }
                            });
                        }
                        menuDialogBuilder.create().show();
                    }
                }
                return super.onSingleTapConfirmed(e);
            }
        });
    }

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

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

    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 = binding.mapView.getGraphicsOverlays();
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }
}
