package com.casic.dcms.fragment;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.FragmentPersonMapBinding;
import com.casic.dcms.model.PersonStatusBean;
import com.casic.dcms.model.PointPersonBean;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.vm.PersonViewModel;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
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.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.pengxh.androidx.lite.base.AndroidxBaseFragment;
import com.pengxh.androidx.lite.hub.ContextHub;
import com.pengxh.androidx.lite.hub.FloatHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class PersonOnMapFragment extends AndroidxBaseFragment<FragmentPersonMapBinding> {

    private static final String TAG = "PersonOnMapFragment";
    private WeakReferenceHandler weakReferenceHandler;
    private PersonViewModel statusViewModel;
    private ListenableList<GraphicsOverlay> graphicsOverlays;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        statusViewModel = new ViewModelProvider(this).get(PersonViewModel.class);
        statusViewModel.obtainPersonByStatus("", "", "");

        viewBinding.mapView.setAttributionTextVisible(false); //去掉左下角属性标识
        viewBinding.mapView.setViewpointScaleAsync(64000.0);
        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap baseMap = new Basemap(ArcGisMapCreator.createBaseLayer());
        arcGISMap.setBasemap(baseMap);
        viewBinding.mapView.setMap(arcGISMap);
        graphicsOverlays = viewBinding.mapView.getGraphicsOverlays();
    }

    @Override
    protected void observeRequestState() {

    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        List<PointPersonBean> personBeans = new ArrayList<>();
        statusViewModel.personStatusModel.observe(this, new Observer<PersonStatusBean>() {
            @Override
            public void onChanged(PersonStatusBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<PersonStatusBean.DataDTO> dataBeans = resultBean.getData();
                    if (!dataBeans.isEmpty()) {
                        for (PersonStatusBean.DataDTO bean : dataBeans) {
                            if (bean.isOnLine()) {
                                String lng = bean.getPositionLng();
                                String lat = bean.getPositionLat();
                                if (!TextUtils.isEmpty(lng) || !TextUtils.isEmpty(lat)) {
                                    PointPersonBean personBean = new PointPersonBean();
                                    personBean.setPersonName(bean.getName());
                                    personBean.setPhoneNumber(bean.getPhone());
                                    personBean.setPersonDept(bean.getDeptName());
                                    personBean.setLastOnlineTime(bean.getLastTimeFmt());
                                    personBean.setLastLng(Double.parseDouble(lng));
                                    personBean.setLastLat(Double.parseDouble(lat));
                                    personBeans.add(personBean);
                                }
                            }
                        }
                        addPictureMarker(personBeans);
                    }
                }
            }
        });

        viewBinding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(requireContext(), viewBinding.mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                android.graphics.Point screenPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
                ListenableFuture<List<IdentifyGraphicsOverlayResult>> overlaysAsync = mMapView.identifyGraphicsOverlaysAsync(screenPoint, 10.0, false, 1);
                overlaysAsync.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            List<IdentifyGraphicsOverlayResult> overlayResultList = overlaysAsync.get();
                            if (!overlayResultList.isEmpty()) {
                                IdentifyGraphicsOverlayResult identifyResult = overlayResultList.get(0);
                                Point point = identifyResult.getGraphicsOverlay().getExtent().getCenter();
                                for (PointPersonBean dataBean : personBeans) {
                                    if (Math.abs(dataBean.getLastLng() - point.getX()) <= LocaleConstant.DELTA_LNG_10 &&
                                            Math.abs(dataBean.getLastLat() - point.getY()) <= LocaleConstant.DELTA_LAT_10
                                    ) {
                                        Message message = weakReferenceHandler.obtainMessage();
                                        message.what = 2021051901;
                                        message.obj = dataBean;
                                        weakReferenceHandler.sendMessage(message);
                                    }
                                }
                            } else {
                                weakReferenceHandler.sendEmptyMessage(2021051902);
                            }
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    private void addPictureMarker(List<PointPersonBean> beans) {
        for (PointPersonBean bean : beans) {
            BitmapDrawable caseDrawable = (BitmapDrawable) ContextCompat.getDrawable(requireContext(), R.mipmap.on_line);
            if (caseDrawable != null) {
                PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
                pictureMarker.setWidth(64);
                pictureMarker.setHeight(42);
                pictureMarker.loadAsync(); //异步加载Marker，防止阻塞
                GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
                ListenableList<Graphic> overlayGraphics = graphicsOverlay.getGraphics();
                overlayGraphics.add(new Graphic(
                        new Point(bean.getLastLng(), bean.getLastLat(), SpatialReferences.getWgs84()),
                        pictureMarker)
                );
                graphicsOverlays.add(graphicsOverlay);
            }
        }
    }

    private final Handler.Callback callback = msg -> {
        switch (msg.what) {
            case 2021051901:
                PointPersonBean dataBean = (PointPersonBean) msg.obj;
                View popupView = LayoutInflater.from(requireContext()).inflate(R.layout.popu_person, null);
                TextView userNameView = popupView.findViewById(R.id.userNameView);
                TextView deptNameView = popupView.findViewById(R.id.deptNameView);
                TextView phoneNumberView = popupView.findViewById(R.id.phoneNumberView);
                TextView lastTimeView = popupView.findViewById(R.id.lastTimeView);
                userNameView.setText(dataBean.getPersonName());
                deptNameView.setText(dataBean.getPersonDept());
                phoneNumberView.setText(dataBean.getPhoneNumber());
                lastTimeView.setText(dataBean.getLastOnlineTime());
                QMUIPopups.popup(requireContext(), (int) (ContextHub.getScreenWidth(requireContext()) * 0.8))
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(popupView)
                        .edgeProtection(FloatHub.dp2px(requireContext(), 20))
                        .dimAmount(0.6f)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .onDismiss(null)
                        .show(viewBinding.mapView);
                break;
            case 2021051902:
                StringHub.show(requireContext(), "附近无工作人员，请重新选点");
                break;
        }
        return true;
    };
}