package com.casic.dcms.view.map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
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 androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityWorkerMapBinding;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.utils.callback.ILocationListener;
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.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

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

public class WorkerOnMapActivity extends AndroidxBaseActivity<ActivityWorkerMapBinding> implements Handler.Callback {

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

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText("查看位置");
        binding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {

    }

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

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

        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.removeToLocalView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoadingDialog.show(WorkerOnMapActivity.this, "定位中，请稍后");
                LocationHelper.get().getCurrentLocation(context, new ILocationListener() {

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        double[] gcjToWgs = LocationHelper.get().gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                        Point p = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                        addPictureMarker(p);
                        binding.mapView.setViewpointCenterAsync(p, 2800.0);
                        LoadingDialog.dismiss();
                    }
                }, true);
            }
        });
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (msg.what == 2021060101) {
            View popupView = LayoutInflater.from(this).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(userName);
            signInTimeView.setText(createTime);
            toiletNameView.setText(toiletName);
            QMUIPopups.popup(this, QMUIDisplayHelper.dp2px(this, 250))
                    .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                    .view(popupView)
                    .edgeProtection(QMUIDisplayHelper.dp2px(this, 20))
                    .dimAmount(0.6f)
                    .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                    .onDismiss(null)
                    .show(binding.mapView);
        } else if (msg.what == 2021060102) {
            StringKit.show(this, "附近无工作人员，请重新选点");
        }
        return true;
    }

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

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

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

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