package com.casic.dcms.view.worker;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
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.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityOnlineWorkerBinding;
import com.casic.dcms.model.OnLinePersonMapBean;
import com.casic.dcms.model.WorkerBean;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.vm.WorkerViewModel;
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.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.widget.TitleBarView;
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 OnLineWorkerActivity extends AndroidxBaseActivity<ActivityOnlineWorkerBinding> implements Handler.Callback {
    private final WeakReferenceHandler weakReferenceHandler = new WeakReferenceHandler(this);
    private final List<OnLinePersonMapBean> onlinePersons = new ArrayList<>();
    private WorkerViewModel workerViewModel;
    private ListenableList<GraphicsOverlay> graphicsOverlays;

    @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() {
                ContextKit.navigatePageTo(OnLineWorkerActivity.this, WorkerListActivity.class);
            }
        });
    }

    @Override
    protected void observeRequestState() {
        workerViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(OnLineWorkerActivity.this, "获取数据中...");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });
    }

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

        workerViewModel = new ViewModelProvider(this).get(WorkerViewModel.class);
        workerViewModel.workerModel.observe(this, new Observer<WorkerBean>() {
            @Override
            public void onChanged(WorkerBean resultBean) {
                if (resultBean.getCode() == 200) {
                    List<WorkerBean.DataBean> dataBeans = resultBean.getData();
                    if (!dataBeans.isEmpty()) {
                        for (WorkerBean.DataBean bean : dataBeans) {
                            if (bean.isOnLine()) {
                                String lng = bean.getPositionLng();
                                String lat = bean.getPositionLat();
                                if (!TextUtils.isEmpty(lng) || !TextUtils.isEmpty(lat)) {
                                    OnLinePersonMapBean person = new OnLinePersonMapBean();
                                    person.setPersonName(bean.getName());
                                    person.setPhoneNumber(bean.getPhone());
                                    person.setPersonDept(bean.getDeptName());
                                    person.setLastOnlineTime(bean.getLastTimeFmt());
                                    person.setLastLng(Double.parseDouble(lng));
                                    person.setLastLat(Double.parseDouble(lat));
                                    onlinePersons.add(person);
                                }
                            }
                        }
                        addPictureMarker(onlinePersons);
                    }
                }
            }
        });
        workerViewModel.getWorkers(this, "", "", "");
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        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 point = identifyResult.getGraphicsOverlay().getExtent().getCenter();
                                for (OnLinePersonMapBean dataBean : onlinePersons) {
                                    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<OnLinePersonMapBean> beans) {
        BitmapDrawable caseDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.mipmap.on_line);
        for (OnLinePersonMapBean bean : beans) {
            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);
            }
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case 2021051901:
                OnLinePersonMapBean dataBean = (OnLinePersonMapBean) msg.obj;
                View popupView = LayoutInflater.from(this).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(this, (int) (ContextKit.getScreenWidth(this) * 0.8))
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(popupView)
                        .edgeProtection(IntKit.dp2px(this, 20))
                        .dimAmount(0.6f)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .onDismiss(null)
                        .show(binding.mapView);
                break;
            case 2021051902:
                StringKit.show(this, "附近无工作人员，请重新选点");
                break;
        }
        return true;
    }
}