package com.casic.dcms.fragment;

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

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.base.BaseApplication;
import com.casic.dcms.bean.LightLocalBean;
import com.casic.dcms.databinding.FragmentLightMapBinding;
import com.casic.dcms.greendao.LightLocalBeanDao;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.LightMapBean;
import com.casic.dcms.utils.ArcGisMapCreator;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.HttpRequestHelper;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.callback.IHttpRequestListener;
import com.casic.dcms.utils.callback.ILocationListener;
import com.casic.dcms.vm.LightViewModel;
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.AndroidxBaseFragment;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.WeakReferenceHandler;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import okhttp3.ResponseBody;

public class LightOnMapFragment extends AndroidxBaseFragment<FragmentLightMapBinding> {

    private static final String TAG = "LightOnMapFragment";
    private LightViewModel lightViewModel;
    private ListenableList<GraphicsOverlay> graphicsOverlays;
    private ListenableList<Graphic> graphics;
    private double DELTA_L = LocaleConstant.DELTA_LNG_75;
    private LightLocalBeanDao lightLocalBeanDao;
    private WeakReferenceHandler weakReferenceHandler;

    @Override
    protected void setupTopBarLayout() {

    }

    @Override
    protected void observeRequestState() {

    }

    @Override
    protected void initData() {
        weakReferenceHandler = new WeakReferenceHandler(callback);
        lightLocalBeanDao = BaseApplication.getDaoSession().getLightLocalBeanDao();

        lightViewModel = new ViewModelProvider(this).get(LightViewModel.class);
        lightViewModel.obtainLightOnMap();
        lightViewModel.lightMapModel.observe(this, new Observer<LightMapBean>() {
            @Override
            public void onChanged(LightMapBean resultBean) {
                if (resultBean.getCode() == 200) {
                    for (LightMapBean.DataBean dataBean : resultBean.getData()) {
                        LightLocalBean bean = new LightLocalBean();
                        bean.setControllerCode(dataBean.getControllerCode());
                        bean.setLampCode(dataBean.getLampCode());
                        String lampId = dataBean.getLampId();
                        bean.setLampId(lampId);
                        bean.setLatitude(dataBean.getLatitude());
                        bean.setDeptId(dataBean.getDeptId());
                        bean.setStatusName(dataBean.getStatusName());
                        bean.setLampName(dataBean.getLampName());
                        bean.setLatestTime(dataBean.getLatestTime());
                        bean.setLongitude(dataBean.getLongitude());
                        bean.setStatus(dataBean.getStatus());

                        LightLocalBean uniqueBean = lightLocalBeanDao.queryBuilder()
                                .where(LightLocalBeanDao.Properties.LampId.eq(lampId)).unique();
                        if (uniqueBean == null) {
                            lightLocalBeanDao.insert(bean);
                        } else {
                            lightLocalBeanDao.update(bean);
                        }
                    }
                }
            }
        });

        lightViewModel.lightControlModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    //开灯指令发下去之后，虽然返回成功，但仅仅表示app发送指令到后台成功，但是开没开灯无法确定，所以，只能延迟几秒再刷新列表
                    StringHub.show(requireContext(), "指令发送成功");
                    weakReferenceHandler.sendEmptyMessageDelayed(20210624, 3000);
                }
            }
        });
        lightViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(requireContext(), "处理中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        viewBinding.mapView.setAttributionTextVisible(false);//去掉左下角属性标识
        ArcGISMap arcGISMap = new ArcGISMap(BasemapStyle.ARCGIS_STREETS);
        //创建底图、并设置底图图层
        Basemap basemap = new Basemap(ArcGisMapCreator.createBaseLayer());
        arcGISMap.setBasemap(basemap);
        Point point = new Point(LocaleConstant.DEFAULT_LNG, LocaleConstant.DEFAULT_LAT, SpatialReferences.getWgs84());
        viewBinding.mapView.setViewpointCenterAsync(point, 2800);//标注到指定经纬度并放大地图显示
        viewBinding.mapView.setMap(arcGISMap);

        //Marker相关Layer
        graphicsOverlays = viewBinding.mapView.getGraphicsOverlays();
        //显示定位点附近路灯
        LocationHelper.obtainCurrentLocation(requireContext(), new ILocationListener() {

            @Override
            public void onAMapLocationGet(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                    Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                    viewBinding.mapView.setViewpointCenterAsync(point, 2800);

                    List<LightLocalBean> streetLightBeans = lightLocalBeanDao.loadAll();
                    List<Point> pointList = new ArrayList<>();
                    for (LightLocalBean bean : streetLightBeans) {
                        double longitude = bean.getLongitude();
                        double latitude = bean.getLatitude();
                        if (Math.abs(longitude - gcjToWgs[0]) <= LocaleConstant.DELTA_LNG_75 &&
                                Math.abs(latitude - gcjToWgs[1]) <= LocaleConstant.DELTA_LAT_75) {
                            pointList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
                        }
//                        if (Math.abs(longitude - Constant.DEFAULT_LNG) <= Constant.DELTA_LNG_75 &&
//                                Math.abs(latitude - Constant.DEFAULT_LAT) <= Constant.DELTA_LAT_75) {
//                            pointList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
//                        }
                    }
                    addPictureMarker(pointList);
                }
            }
        }, true);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {
        viewBinding.expandMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 0.5);
                clearPictureMarker();
                //计算比例尺
                DELTA_L -= 0.0001;
                if (DELTA_L < 0) {
                    DELTA_L = 0;
                }
//                List<Point> minusList = new ArrayList<>();
//                for (StreetLightLocalBean bean : lightBeans) {
//                    double longitude = bean.getLongitude();
//                    double latitude = bean.getLatitude();
//                    if (Math.abs(longitude - Constant.DEFAULT_LNG) > DELTA_L ||
//                            Math.abs(latitude - Constant.DEFAULT_LAT) > DELTA_L) {
//                        continue;
//                    }
//                    minusList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
//                }
//                addPictureMarker(minusList);
                LocationHelper.obtainCurrentLocation(requireContext(), new ILocationListener() {

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation != null) {
                            double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                            Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                            List<Point> minusList = new ArrayList<>();
                            for (LightLocalBean bean : lightLocalBeanDao.loadAll()) {
                                double longitude = bean.getLongitude();
                                double latitude = bean.getLatitude();
                                if (Math.abs(longitude - gcjToWgs[0]) <= DELTA_L &&
                                        Math.abs(latitude - gcjToWgs[1]) <= DELTA_L) {
                                    minusList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
                                }
                            }
                            addPictureMarker(minusList);
                        }
                    }
                }, true);
            }
        });

        viewBinding.minusMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewBinding.mapView.setViewpointScaleAsync(viewBinding.mapView.getMapScale() * 2);
                clearPictureMarker();
                //计算比例尺
                DELTA_L += 0.0001;
                if (DELTA_L > 0.01) {
                    DELTA_L = LocaleConstant.DELTA_LNG_75;
                }
//                List<Point> expandList = new ArrayList<>();
//                for (StreetLightLocalBean bean : lightBeans) {
//                    double longitude = bean.getLongitude();
//                    double latitude = bean.getLatitude();
//                    if (Math.abs(longitude - Constant.DEFAULT_LNG) > DELTA_L ||
//                            Math.abs(latitude - Constant.DEFAULT_LAT) > DELTA_L) {
//                        continue;
//                    }
//                    expandList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
//                }
//                addPictureMarker(expandList);
                LocationHelper.obtainCurrentLocation(requireContext(), new ILocationListener() {

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation != null) {
                            double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                            Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                            List<Point> expandList = new ArrayList<>();
                            for (LightLocalBean bean : lightLocalBeanDao.loadAll()) {
                                double longitude = bean.getLongitude();
                                double latitude = bean.getLatitude();
                                if (Math.abs(longitude - gcjToWgs[0]) <= DELTA_L &&
                                        Math.abs(latitude - gcjToWgs[1]) <= DELTA_L) {
                                    expandList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
                                }
                            }
                            addPictureMarker(expandList);
                        }
                    }
                }, true);
            }
        });

        viewBinding.removeToLocalView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearPictureMarker();
                DialogHelper.showLoadingDialog(requireContext(), "定位中，请稍后");
                LocationHelper.obtainCurrentLocation(requireContext(), new ILocationListener() {

                    @Override
                    public void onAMapLocationGet(AMapLocation aMapLocation) {
                        if (aMapLocation != null) {
                            double[] gcjToWgs = LocationHelper.gcjToWgs(aMapLocation.getLongitude(), aMapLocation.getLatitude());
                            Point point = new Point(gcjToWgs[0], gcjToWgs[1], SpatialReferences.getWgs84());
                            List<Point> pointList = new ArrayList<>();
                            for (LightLocalBean bean : lightLocalBeanDao.loadAll()) {
                                double longitude = bean.getLongitude();
                                double latitude = bean.getLatitude();
                                if (Math.abs(longitude - gcjToWgs[0]) <= LocaleConstant.DELTA_LNG_75 &&
                                        Math.abs(latitude - gcjToWgs[1]) <= LocaleConstant.DELTA_LAT_75) {
                                    pointList.add(new Point(longitude, latitude, SpatialReferences.getWgs84()));
                                }
                            }
                            addPictureMarker(pointList);
                            viewBinding.mapView.setViewpointCenterAsync(point, 3000);
                            DialogHelper.dismissLoadingDialog();
                        }
                    }
                }, true);
            }
        });

        viewBinding.mapView.setOnTouchListener(new DefaultMapViewOnTouchListener(requireContext(), viewBinding.mapView) {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                List<LightLocalBean> lightBeans = lightLocalBeanDao.loadAll();
                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 (LightLocalBean dataBean : lightBeans) {
                                    if (Math.abs(dataBean.getLongitude() - point.getX()) <= LocaleConstant.DELTA_LNG_10 &&
                                            Math.abs(dataBean.getLatitude() - point.getY()) <= LocaleConstant.DELTA_LAT_10) {
                                        Message message = weakReferenceHandler.obtainMessage();
                                        message.what = 2021062401;
                                        message.obj = dataBean.getLampId();
                                        weakReferenceHandler.sendMessage(message);
                                    }
                                }
                            } else {
                                weakReferenceHandler.sendEmptyMessage(2021062402);
                            }
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapConfirmed(e);
            }
        });
    }

    private final Handler.Callback callback = msg -> {
        switch (msg.what) {
            case 2021062401:
                String lampId = (String) msg.obj;

                View popupView = LayoutInflater.from(requireContext()).inflate(R.layout.popu_street_light, null);
                TextView lightStateView = popupView.findViewById(R.id.lightStateView);
                TextView lightAddressView = popupView.findViewById(R.id.lightAddressView);
                TextView lightStreetView = popupView.findViewById(R.id.lightStreetView);
                TextView lightElecView = popupView.findViewById(R.id.lightElecView);
                TextView lightVolView = popupView.findViewById(R.id.lightVolView);
                TextView lightTimeView = popupView.findViewById(R.id.lightTimeView);
                ImageView lightSwitch = popupView.findViewById(R.id.lightSwitch);

                DialogHelper.showLoadingDialog(requireContext(), "路灯详情获取中，请稍后...");
                HttpRequestHelper.doRequest(LocaleConstant.LIGHT_DETAIL, lampId, new IHttpRequestListener() {
                    @Override
                    public void onSuccess(ResponseBody resultBean) {
                        DialogHelper.dismissLoadingDialog();
                        try {
                            String string = resultBean.string();
                            JSONObject jsonObject = new JSONObject(string);
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject dataObject = jsonObject.getJSONObject("data");

                                String statusName = dataObject.getString("statusName");
                                lightStateView.setText(statusName);
                                lightAddressView.setText(dataObject.getString("address"));
                                lightStreetView.setText(dataObject.getString("streetName"));
                                lightElecView.setText(String.valueOf(dataObject.getDouble("latestElec")));
                                lightVolView.setText(String.valueOf(dataObject.getDouble("latestVol")));
                                lightTimeView.setText(dataObject.getString("latestTime"));

                                QMUIPopups.popup(requireContext(), QMUIDisplayHelper.dp2px(requireContext(), 280))
                                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                                        .view(popupView)
                                        .edgeProtection(QMUIDisplayHelper.dp2px(requireContext(), 20))
                                        .dimAmount(0.6f)
                                        .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                                        .onDismiss(null)
                                        .show(viewBinding.mapView);

                                lightSwitch.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        List<Long> lampIds = new ArrayList<>();
                                        lampIds.add(Long.parseLong(lampId));

                                        String controlType;
                                        if (statusName.equals("离线")) {
                                            controlType = "1";
                                        } else {
                                            controlType = "0";
                                        }
                                        lightViewModel.controlLight(lampIds, controlType);
                                    }
                                });
                            } else {
                                StringHub.show(requireContext(), "服务器异常，请重新选点");
                            }
                        } catch (JSONException | IOException e) {
                            StringHub.show(requireContext(), "解析失败，请重新选点");
                        }
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        DialogHelper.dismissLoadingDialog();
                        StringHub.show(requireContext(), "网络连接失败，请重新选点");
                    }
                });
                break;
            case 2021062402:
                StringHub.show(requireContext(), "此附近无路灯，请重新选点");
                break;
            default:
                break;
        }
        return true;
    };

    private void addPictureMarker(List<Point> points) {
        for (Point point : points) {
            Bitmap caseBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.location_verify);
            BitmapDrawable caseDrawable = new BitmapDrawable(getResources(), caseBitmap);
            PictureMarkerSymbol pictureMarker = new PictureMarkerSymbol(caseDrawable);
            pictureMarker.setWidth(24);
            pictureMarker.setHeight(24);
            pictureMarker.loadAsync();

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

    @Override
    public void onDestroyView() {
        viewBinding.mapView.dispose();
        super.onDestroyView();
    }
}
