package com.casic.dcms.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.databinding.ActivityWorkerMapBinding;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.ToastHelper;
import com.casic.dcms.utils.callback.ILocationListener;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReference;
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.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.List;
import java.util.concurrent.ExecutionException;

public class WorkerOnMapActivity extends AndroidxBaseActivity<ActivityWorkerMapBinding> {

    private final Context context = WorkerOnMapActivity.this;
    private WeakReferenceHandler weakReferenceHandler;
    private String userName;
    private String createTime;
    private String toiletName;
    private double lng = 0.0;
    private double lat = 0.0;

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("查看位置");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        userName = getIntent().getStringExtra("userName");
        createTime = getIntent().getStringExtra("createTime");
        toiletName = getIntent().getStringExtra("toiletName");
        lng = getIntent().getDoubleExtra("lng", Constant.DEFAULT_LNG);
        lat = getIntent().getDoubleExtra("lat", Constant.DEFAULT_LAT);
        viewBinding.mapView.setAttributionTextVisible(false); //去掉左下角属性标识
        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap baseMap = new Basemap(ArcGisMapCreator.createBaseLayer());
        arcGISMap.setBasemap(baseMap);
        viewBinding.mapView.setMap(arcGISMap);
        weakReferenceHandler = new WeakReferenceHandler(this);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        Point point = new Point(lng, lat, SpatialReference.create(4326));
        viewBinding.mapView.setViewpointCenterAsync(point, 64000.0); //标注到指定经纬度并放大地图显示
        addPictureMarker(point);
        viewBinding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, 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 p = identifyResult.getGraphicsOverlay().getExtent().getCenter();
                                if (Math.abs(lng - p.getX()) <= Constant.DELTA_LNG_10 && Math.abs(lat - p.getY()) <= Constant.DELTA_LAT_10) {
                                    weakReferenceHandler.sendEmptyMessage(2021060101);
                                }
                            } else {
                                weakReferenceHandler.sendEmptyMessage(2021060102);
                            }
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });

        viewBinding.expandMapView.setOnClickListener(v -> viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 0.5));

        viewBinding.minusMapView.setOnClickListener(v -> viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 2));

        viewBinding.removeToLocalView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OtherUtils.showLoadingDialog(context, "定位中，请稍后");
                LocationHelper.obtainCurrentLocationByGD(context, new ILocationListener() {
                    @Override
                    public void onLocationGet(Location location) {

                    }

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                        Point p = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReference.create(4326));
                        addPictureMarker(p);
                        viewBinding.mapView.setViewpointCenterAsync(p, 2800.0);
                        OtherUtils.dismissLoadingDialog();
                    }
                }, true);
            }
        });
    }

    private static class WeakReferenceHandler extends Handler {
        private final WeakReference<WorkerOnMapActivity> reference;

        private WeakReferenceHandler(WorkerOnMapActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            WorkerOnMapActivity mapActivity = reference.get();
            if (msg.what == 2021060101) {
                View popupView = LayoutInflater.from(mapActivity).inflate(R.layout.popu_worker, null);
                TextView userNameView = popupView.findViewById(R.id.userNameView);
                TextView signInTimeView = popupView.findViewById(R.id.signInTimeView);
                TextView toiletNameView = popupView.findViewById(R.id.toiletNameView);
                userNameView.setText(mapActivity.userName);
                signInTimeView.setText(mapActivity.createTime);
                toiletNameView.setText(mapActivity.toiletName);
                QMUIPopups.popup(mapActivity, QMUIDisplayHelper.dp2px(mapActivity, 250))
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(popupView)
                        .edgeProtection(QMUIDisplayHelper.dp2px(mapActivity, 20))
                        .dimAmount(0.6f)
                        .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                        .onDismiss(null)
                        .show(mapActivity.viewBinding.mapView);
            } else if (msg.what == 2021060102) {
                ToastHelper.showToast("附近无工作人员，请重新选点", ToastHelper.WARING);
            }
        }
    }

    private void addPictureMarker(Point point) {
        Bitmap caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.on_line);
        BitmapDrawable caseDrawable = new BitmapDrawable(getResources(), caseBitmap);
        PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
        pictureMarker.setWidth(64f);
        pictureMarker.setHeight(42f);
        pictureMarker.loadAsync(); //异步加载Marker，防止阻塞
        Graphic graphic = new Graphic(point, pictureMarker);
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        ListenableList<Graphic> overlayGraphics = mGraphicsOverlay.getGraphics();
        ListenableList<GraphicsOverlay> graphicsOverlays = viewBinding.mapView.getGraphicsOverlays();
        overlayGraphics.add(graphic);
        graphicsOverlays.add(mGraphicsOverlay);
    }

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

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

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