package com.casic.dcms.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.casic.dcms.R;
import com.casic.dcms.base.BaseFragment;
import com.casic.dcms.bean.OnlinePersonBean;
import com.casic.dcms.bean.PointPersonBean;
import com.casic.dcms.mvp.presenter.PersonOnlinePresenterImpl;
import com.casic.dcms.mvp.view.IPersonOnlineView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.ToastHelper;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.ArcGISTiledLayer;
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.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.util.ListenableList;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;

public class PersonOnMapFragment extends BaseFragment implements IPersonOnlineView {

    private static final String TAG = "PersonOnMapFragment";
    @BindView(R.id.mapView)
    MapView mapView;

    private PersonOnlinePresenterImpl onlinePresenter;
    private ListenableList<GraphicsOverlay> graphicsOverlays;
    private Resources resources;
    private Context context;
    private List<PointPersonBean> personBeans;
    private WeakReferenceHandler weakReferenceHandler;

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

    @Override
    protected void setupTopBarLayout() {
        context = getContext();
        resources = context.getResources();
    }

    @Override
    public void initData() {
        onlinePresenter = new PersonOnlinePresenterImpl(this);
        onlinePresenter.onReadyRetrofitRequest("", "", "");

        mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        mapView.setViewpointScaleAsync(64000);

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

        graphicsOverlays = mapView.getGraphicsOverlays();
        weakReferenceHandler = new WeakReferenceHandler(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initEvent() {
        mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(context, mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                android.graphics.Point screenPoint = new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY()));
                final 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) {
                                    Point beanPoint = dataBean.getPoint();
                                    if (Math.abs(beanPoint.getX() - point.getX()) <= Constant.DELTA_LNG_10 &&
                                            Math.abs(beanPoint.getY() - point.getY()) <= Constant.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 static class WeakReferenceHandler extends Handler {
        private WeakReference<PersonOnMapFragment> reference;

        private WeakReferenceHandler(PersonOnMapFragment mapFragment) {
            reference = new WeakReference<>(mapFragment);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            PersonOnMapFragment mapFragment = reference.get();
            Context context = mapFragment.context;
            switch (msg.what) {
                case 2021051901:
                    PointPersonBean dataBean = (PointPersonBean) msg.obj;
                    View popupView = LayoutInflater.from(context).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.getPersonPhone());
                    lastTimeView.setText(dataBean.getPointTime());

                    QMUIPopups.popup(context, QMUIDisplayHelper.dp2px(context, 250))
                            .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                            .view(popupView)
                            .edgeProtection(QMUIDisplayHelper.dp2px(context, 20))
                            .dimAmount(0.6f)
                            .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                            .onDismiss(null)
                            .show(mapFragment.mapView);
                    break;
                case 2021051902:
                    ToastHelper.showToast("附近无工作人员，请重新选点", ToastHelper.WARING);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onlineResult(OnlinePersonBean resultBean) {
        if (resultBean.isSuccess()) {
            List<OnlinePersonBean.DataBean> dataBeans = resultBean.getData();
            if (dataBeans.size() >= 1) {
                personBeans = new ArrayList<>();
                for (OnlinePersonBean.DataBean bean : dataBeans) {
                    String lng = bean.getPositionLng();
                    String lat = bean.getPositionLat();
                    if (TextUtils.isEmpty(lng) || TextUtils.isEmpty(lat)) {
                        Log.d(TAG, "经纬度异常");
                    } else {
                        PointPersonBean personBean = new PointPersonBean();
                        personBean.setPersonName(bean.getName());
                        personBean.setPersonPhone(bean.getPhone());
                        personBean.setPersonDept(bean.getDeptName());
                        personBean.setPointTime(bean.getLastTimeFmt());
                        personBean.setOnLine(bean.isOnLine());
                        personBean.setPoint(new Point(Double.parseDouble(lng), Double.parseDouble(lat), mapView.getSpatialReference()));

                        personBeans.add(personBean);
                    }
                }
                addPictureMarker(personBeans);
            } else {
                ToastHelper.showToast("当前没有人员在线", ToastHelper.ERROR);
            }
        }
    }

    private void addPictureMarker(List<PointPersonBean> personBeans) {
        Bitmap caseBitmap;
        for (PointPersonBean bean : personBeans) {
            if (bean.isOnLine()) {
                caseBitmap = BitmapFactory.decodeResource(resources, R.mipmap.on_line);
            } else {
                caseBitmap = BitmapFactory.decodeResource(resources, R.mipmap.off_line);
            }
            BitmapDrawable caseDrawable = new BitmapDrawable(resources, caseBitmap);
            PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
            pictureMarker.setWidth(64);
            pictureMarker.setHeight(42);
            pictureMarker.loadAsync();//异步加载Marker，防止阻塞

            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
            ListenableList<Graphic> graphics = graphicsOverlay.getGraphics();
            graphics.add(new Graphic(bean.getPoint(), pictureMarker));
            graphicsOverlays.add(graphicsOverlay);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (onlinePresenter != null) {
            onlinePresenter.disposeRetrofitRequest();
        }
    }
}
