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.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityMapCaseBinding;
import com.casic.dcms.model.CaseCheckModel;
import com.casic.dcms.model.CaseHandleBean;
import com.casic.dcms.model.PointDataBean;
import com.casic.dcms.model.VerifyCaseModel;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.view.CaseDetailActivity;
import com.casic.dcms.vm.CaseViewModel;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureLayer;
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.WeakReferenceHandler;
import com.pengxh.androidx.lite.widget.dialog.AlertControlDialog;

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

public class CaseOnMapActivity extends AndroidxBaseActivity<ActivityMapCaseBinding> implements Handler.Callback, RadioGroup.OnCheckedChangeListener {

    private static final String TAG = "CaseOnMapActivity";
    private final Context context = this;
    private final WeakReferenceHandler weakReferenceHandler = new WeakReferenceHandler(this);
    private CaseViewModel caseViewModel;
    private ListenableList<Graphic> graphics;
    private ListenableList<GraphicsOverlay> graphicsOverlays;
    private List<PointDataBean> casePointList = new ArrayList<>();

    @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) {
        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        //默认加载处置中数据
        caseViewModel.getHandleCaseList(context, 1, true);

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

        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap basemap = new Basemap(ArcGisMapCreator.createNoGridLayer());
        arcGISMap.setBasemap(basemap);
        binding.mapView.setMap(arcGISMap);

        ServiceFeatureTable communityFeatureTable = ArcGisMapCreator.createGridFeatureTable();
        communityFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        FeatureLayer communityLayer = new FeatureLayer(communityFeatureTable);

        ServiceFeatureTable pointFeatureTable = ArcGisMapCreator.createOtherFeatureTable("部件点");
        pointFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_NO_CACHE);
        FeatureLayer pointLayer = new FeatureLayer(pointFeatureTable);

        arcGISMap.getOperationalLayers().addAll(Arrays.asList(communityLayer, pointLayer));
        binding.mapView.setMap(arcGISMap);

        //Marker相关Layer
        graphicsOverlays = binding.mapView.getGraphicsOverlays();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        caseViewModel.caseCheckModel.observe(this, new Observer<CaseCheckModel>() {
            @Override
            public void onChanged(CaseCheckModel resultBean) {
                clearPictureMarker();
                if (resultBean.isSuccess()) {
                    List<CaseCheckModel.DataModel.RowsModel> rowsBeans = resultBean.getData().getRows();
                    if (rowsBeans.size() >= 1) {
                        List<PointDataBean> list = new ArrayList<>();
                        List<Point> pointList = new ArrayList<>();
                        for (CaseCheckModel.DataModel.RowsModel bean : rowsBeans) {
                            String lng = bean.getLng();
                            String lat = bean.getLat();
                            if (TextUtils.isEmpty(lng) || TextUtils.isEmpty(lat)) {
                                Log.d(TAG, "案卷经纬度异常");
                                continue;
                            }
                            relatePointToCase(list, bean.getId(), lng, lat);

                            Point point = new Point(Double.parseDouble(lng), Double.parseDouble(lat), SpatialReferences.getWgs84());
                            pointList.add(point);
                        }
                        addPictureMarker(pointList, LocaleConstant.CASE_CHECK);
                    } else {
                        StringKit.show(context, "当前没有[待核查]的案卷");
                    }
                }
            }
        });

        caseViewModel.caseHandleModel.observe(this, new Observer<CaseHandleBean>() {
            @Override
            public void onChanged(CaseHandleBean resultBean) {
                clearPictureMarker();
                if (resultBean.isSuccess()) {
                    List<CaseHandleBean.DataModel.RowsModel> rowsBeans = resultBean.getData().getRows();
                    if (rowsBeans.size() >= 1) {
                        List<PointDataBean> list = new ArrayList<>();
                        List<Point> pointList = new ArrayList<>();
                        for (CaseHandleBean.DataModel.RowsModel bean : rowsBeans) {
                            String lng = bean.getLng();
                            String lat = bean.getLat();
                            if (TextUtils.isEmpty(lng) || TextUtils.isEmpty(lat)) {
                                Log.d(TAG, "案卷经纬度异常");
                                continue;
                            }
                            relatePointToCase(list, bean.getId(), lng, lat);

                            Point point = new Point(Double.parseDouble(lng), Double.parseDouble(lat), SpatialReferences.getWgs84());
                            pointList.add(point);
                        }
                        addPictureMarker(pointList, LocaleConstant.CASE_HANDLE);
                    } else {
                        StringKit.show(context, "当前没有[处理中]的案卷");
                    }
                }
            }
        });

        caseViewModel.caseVerifyModel.observe(this, new Observer<VerifyCaseModel>() {
            @Override
            public void onChanged(VerifyCaseModel resultBean) {
                clearPictureMarker();
                if (resultBean.getCode() == 200) {
                    List<VerifyCaseModel.DataModel.RowsModel> rowsBeans = resultBean.getData().getRows();
                    if (rowsBeans.size() >= 1) {
                        List<PointDataBean> list = new ArrayList<>();
                        List<Point> pointList = new ArrayList<>();
                        for (VerifyCaseModel.DataModel.RowsModel bean : rowsBeans) {
                            String lng = bean.getLng();
                            String lat = bean.getLat();
                            if (TextUtils.isEmpty(lng) || TextUtils.isEmpty(lat)) {
                                Log.d(TAG, "案卷经纬度异常");
                                continue;
                            }
                            relatePointToCase(list, bean.getId(), lng, lat);

                            Point point = new Point(Double.parseDouble(lng), Double.parseDouble(lat), SpatialReferences.getWgs84());
                            pointList.add(point);
                        }
                        addPictureMarker(pointList, LocaleConstant.CASE_VERIFY);
                    } else {
                        StringKit.show(context, "当前没有[待核实]的案卷");
                    }
                }
            }
        });

        binding.radioGroup.setOnCheckedChangeListener(this);
        binding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, binding.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 (PointDataBean dataBean : casePointList) {
                                    double parseLng = Double.parseDouble(dataBean.getLng());
                                    double parseLat = Double.parseDouble(dataBean.getLat());
                                    if (Math.abs(parseLng - point.getX()) <= LocaleConstant.DELTA_LNG_10 &&
                                            Math.abs(parseLat - point.getY()) <= LocaleConstant.DELTA_LAT_10) {
                                        Message message = weakReferenceHandler.obtainMessage();
                                        message.what = 2021051401;
                                        message.obj = dataBean.getId();
                                        weakReferenceHandler.sendMessage(message);
                                    }
                                }
                            } else {
                                weakReferenceHandler.sendEmptyMessage(2021051402);
                            }
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        switch (msg.what) {
            case 2021051401:
                String caseId = (String) msg.obj;
                new AlertControlDialog.Builder()
                        .setContext(context)
                        .setTitle("查看案卷详情")
                        .setMessage("ID：" + caseId)
                        .setNegativeButton("取消")
                        .setPositiveButton("确定")
                        .setOnDialogButtonClickListener(new AlertControlDialog.OnDialogButtonClickListener() {
                            @Override
                            public void onConfirmClick() {
                                ContextKit.navigatePageTo(context, CaseDetailActivity.class, caseId);
                            }

                            @Override
                            public void onCancelClick() {

                            }
                        }).build().show();
                break;
            case 2021051402:
                StringKit.show(this, "此附近无案卷，请重新选点");
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.handleRadioButton) {
            resetRadioButton(0);
        } else if (checkedId == R.id.verifyRadioButton) {
            resetRadioButton(1);
        } else if (checkedId == R.id.checkRadioButton) {
            resetRadioButton(2);
        }
    }

    private void resetRadioButton(int index) {
        switch (index) {
            case 0:
                binding.handleRadioButton.setTextColor(IntKit.convertColor(this, R.color.white));
                binding.verifyRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));
                binding.checkRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));

                //请求处置中数据
                caseViewModel.getHandleCaseList(this, 1, true);
                break;
            case 1:
                binding.verifyRadioButton.setTextColor(IntKit.convertColor(this, R.color.white));
                binding.handleRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));
                binding.checkRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));

                //请求待核实数据
                caseViewModel.getVerifyCaseList(this, 1000, 1, false);
                break;
            case 2:
                binding.checkRadioButton.setTextColor(IntKit.convertColor(this, R.color.white));
                binding.verifyRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));
                binding.handleRadioButton.setTextColor(IntKit.convertColor(this, R.color.mainTextColor));

                //请求待核查数据
                caseViewModel.getCheckCaseList(this, 1000, 1, false);
                break;
            default:
                break;
        }
    }

    /**
     * 关联Marker和案卷
     *
     * @param list 临时数据集合
     */
    private void relatePointToCase(List<PointDataBean> list, String id, String lng, String lat) {
        PointDataBean casePoint = new PointDataBean();
        casePoint.setId(id);
        casePoint.setLng(lng);
        casePoint.setLat(lat);
        list.add(casePoint);
        casePointList = list;
    }

    private void addPictureMarker(List<Point> points, int caseStatus) {
        Bitmap caseBitmap;
        switch (caseStatus) {
            case LocaleConstant.CASE_HANDLE:
                caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.location_handle);
                break;
            case LocaleConstant.CASE_VERIFY:
                caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.location_verify);
                break;
            case LocaleConstant.CASE_CHECK:
                caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.location_check);
                break;
            default:
                caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.location_case);
                break;
        }

        BitmapDrawable caseDrawable = new BitmapDrawable(getResources(), caseBitmap);
        for (Point point : points) {
            PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
            pictureMarker.setHeight(24);
            pictureMarker.setWidth(24);
            pictureMarker.loadAsync();//异步加载Marker，防止阻塞
            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
            graphics = graphicsOverlay.getGraphics();
            graphics.add(new Graphic(point, pictureMarker));
            graphicsOverlays.add(graphicsOverlay);
        }
    }

    private void clearPictureMarker() {
        if (graphics != null && graphicsOverlays != null) {
            graphics.clear();
            graphicsOverlays.clear();
        }
    }

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