package com.atmob.map_amap_android.overlays.marker;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.atmob.map_amap_android.R;
import com.atmob.map_amap_android.bean.MakerInfo;
import com.atmob.map_amap_android.contants.Constants;
import com.atmob.map_amap_android.databinding.ItemElectricMarkerBinding;
import com.atmob.map_amap_android.databinding.ItemLocationMarkerBinding;
import com.atmob.map_amap_android.databinding.ItemTrackErrorMarkerBinding;
import com.atmob.map_amap_android.databinding.ItemTrackPassingMarkerBinding;
import com.atmob.map_amap_android.databinding.ItemTrackSelectedMarkerBinding;
import com.atmob.map_amap_android.databinding.ItemTrackStartMarkerBinding;
import com.atmob.map_amap_android.overlays.MyMethodCallHandler;
import com.atmob.map_amap_android.util.BitmapCallback;
import com.atmob.map_amap_android.util.GsonUtil;
import com.atmob.map_amap_android.util.ImageCacheLoader;
import com.atmob.map_amap_android.util.LogUtil;
import com.atmob.map_amap_android.util.ParamUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MarkersController implements MyMethodCallHandler, AMap.OnMarkerClickListener {

    private final String TAG = "MarkersController";

    private final AMap map;

    private final Context context;

    private final MethodChannel methodChannel;

    private final HashMap<String, Marker> currentMarkers = new HashMap<>(10);

    private ItemLocationMarkerBinding markerBinding;
    private ItemElectricMarkerBinding electricMarkerBinding;

    private final Gson gson;


    public MarkersController(Context context, MethodChannel methodChannel, AMap map) {
        this.context = context;
        this.methodChannel = methodChannel;
        this.map = map;
        gson = GsonUtil.getInstance();
        map.setOnMarkerClickListener(this);
    }

    @Override
    public void doMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        LogUtil.i(TAG, "doMethodCall===>" + call.method);
        switch (call.method) {
            case Constants.METHOD_UPDATE_OR_ADD_MARKERS:
                updateMarkers(call, result);
                break;
            case Constants.METHOD_REPLACE_ALL_MARKERS:
                replaceAllMarkers(call, result);
                break;
            case Constants.METHOD_REMOVE_MARKER:
                removeMarker(call, result);
                break;
        }
    }


    private void removeMarker(MethodCall call, MethodChannel.Result result) {
        LogUtil.d(TAG, "removeMarker===>" + call.arguments());
        Map<String, Object> arguments = call.arguments();
        if (arguments == null || arguments.isEmpty()) {
            result.error("-1", "removeMarker.arguments is empty", null);
            return;
        }
        String markerId = ParamUtil.getString(arguments, "markerId");
        Marker marker = currentMarkers.get(markerId);
        if (marker != null) {
            marker.remove();
            currentMarkers.remove(markerId);
            LogUtil.d(TAG, "removeMarker===>成功删除marker:" + markerId);
        }
        result.success(null);
    }

    private void replaceAllMarkers(MethodCall call, MethodChannel.Result result) {
        LogUtil.d(TAG, "replaceAllMarkers===>" + call.arguments());
        try {
            String arguments = call.arguments();
            List<MakerInfo> list = null;
            if (!TextUtils.isEmpty(arguments)) {
                list = gson.fromJson(arguments, new TypeToken<List<MakerInfo>>() {
                });
            }
            if (list == null || list.isEmpty()) {
                clearAllMarkers();
            } else {
                for (MakerInfo makerInfo : list) {
                    updateMarker(makerInfo);
                }
                //删除多余的marker
                Iterator<String> iterator = currentMarkers.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    boolean isExist = false;
                    for (MakerInfo makerInfo : list) {
                        if (Objects.equals(key, makerInfo.getId())) {
                            isExist = true;
                            break;
                        }
                    }
                    if (!isExist) {
                        Marker marker = currentMarkers.get(key);
                        if (marker != null) {
                            marker.remove();
                        }
                        iterator.remove();
                    }
                }
            }
            result.success(null);
        } catch (Exception e) {
            result.error("-1", "deleteAllMarkers.error", e.getMessage());
        }
    }


    private void clearAllMarkers() {
        for (Marker marker : currentMarkers.values()) {
            marker.remove();
        }
        currentMarkers.clear();
    }

    private void updateMarkers(MethodCall call, MethodChannel.Result result) {
        LogUtil.d(TAG, "updateMarkers===>" + call.arguments());
        String arguments = call.arguments();
        if (arguments == null || TextUtils.isEmpty(arguments)) {
            result.error("-1", "updateMarkers.arguments is empty", null);
            return;
        }
        List<MakerInfo> list = gson.fromJson(arguments, new TypeToken<List<MakerInfo>>() {
        });
        if (list == null || list.isEmpty()) {
            result.error("-1", "updateFriendMarkers.list is empty", null);
            return;
        }
        for (MakerInfo makerInfo : list) {
            updateMarker(makerInfo);
        }
        result.success(null);
    }


    private void updateMarker(final MakerInfo makerInfo) {
        final LatLng latLng = new LatLng(makerInfo.getLatitude(), makerInfo.getLongitude());
        final Marker marker = currentMarkers.get(makerInfo.getId());

        if (marker != null) {
            marker.setPosition(latLng);

            Object object = marker.getObject();
            if (object instanceof MakerInfo) {
                MakerInfo cacheInfo = (MakerInfo) object;
                if (cacheInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_POPUP_POINT) {
                    BitmapDescriptor markerBitmap = getMarkerBitmap(makerInfo, null);
                    marker.setIcon(markerBitmap);
                    marker.setZIndex(999);
                } else {
                    boolean nameChanged = !Objects.equals(cacheInfo.getMarkerName(), makerInfo.getMarkerName());
                    boolean selectedChanged = cacheInfo.isSelected() != makerInfo.isSelected();
                    boolean avatarChanged = !Objects.equals(cacheInfo.getCustomAvatarUrl(), makerInfo.getCustomAvatarUrl());
                    boolean tagsChanged = checkMarkerTagsChanged(cacheInfo,makerInfo);

                    if (nameChanged || selectedChanged || avatarChanged || tagsChanged) {
                        LogUtil.d(TAG, "updateMarkers==marker内容发生变化，更新样式");
                        ImageCacheLoader.loadBitmapAsync(context, makerInfo.getCustomAvatarUrl(), new BitmapCallback() {
                            @Override
                            public void onStartLoading() {
                            }

                            @Override
                            public void onBitmapLoaded(Bitmap bitmap) {
                                BitmapDescriptor markerBitmap = getMarkerBitmap(makerInfo, bitmap);
                                marker.setIcon(markerBitmap);
                                LogUtil.d(TAG, "updateMarkers=url头像:id=" + makerInfo.getId());
                            }

                            @Override
                            public void onError(String errorMessage) {
                                LogUtil.d(TAG, "updateMarkers==url头像失败:" + errorMessage);
                                BitmapDescriptor markerBitmap = getMarkerBitmap(makerInfo, null);
                                marker.setIcon(markerBitmap);
                            }
                        });
                    }
                    marker.setZIndex(makerInfo.isSelected() ? 100 : 0);
                }
            }
            marker.setObject(makerInfo);
        } else {
            LogUtil.d(TAG, "updateMarkers==>marker不存在，创建新 marker:" + makerInfo);
            // 创建新 marker
            loadAvatarAndCreateMarker(makerInfo, latLng);
        }
    }

    private boolean checkMarkerTagsChanged(MakerInfo cacheInfo, MakerInfo makerInfo) {
        if(makerInfo.getMarkerType() == MakerInfo.MarkerType.FRIEND){
            if(!Objects.equals(cacheInfo.getTags(), makerInfo.getTags())){
                return true;
            }
        }
        return false;
    }

    private void loadAvatarAndCreateMarker(final MakerInfo makerInfo, final LatLng latLng) {
        Marker marker = addMarkerToMap(makerInfo, latLng, null);
        if (!TextUtils.isEmpty(makerInfo.getCustomAvatarUrl())) {
            // 加载头像后再添加 marker
            ImageCacheLoader.loadBitmapAsync(context, makerInfo.getCustomAvatarUrl(), new BitmapCallback() {
                @Override
                public void onStartLoading() {
                }

                @Override
                public void onBitmapLoaded(Bitmap bitmap) {
                    BitmapDescriptor markerBitmap = getMarkerBitmap(makerInfo, bitmap);
                    marker.setIcon(markerBitmap);
                }

                @Override
                public void onError(String errorMessage) {

                }
            });
        }
    }


    private Marker addMarkerToMap(MakerInfo makerInfo, LatLng latLng, Bitmap avatarBitmap) {
        BitmapDescriptor markerBitmap = getMarkerBitmap(makerInfo, avatarBitmap);
        MarkerOptions markerOption = new MarkerOptions()
                .position(latLng)
                .icon(markerBitmap)
                .anchor(0.5f, 0.9f);

        if (makerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_PASSING_POINT || makerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_ERROR_POINT) {
            markerOption.anchor(0.5f, 0.5f);
        } else if (makerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_POPUP_POINT) {
            markerOption.anchor(0.5f, 1.1f);
        }

        Marker newMarker = map.addMarker(markerOption);
        newMarker.setObject(makerInfo);
        newMarker.setZIndex(makerInfo.isSelected() ? 999 : 0);
        currentMarkers.put(makerInfo.getId(), newMarker);
        return newMarker;
    }


    @Override
    public String[] getRegisterMethodIdArray() {
        return Constants.METHOD_ID_LIST_FOR_MARKER;
    }


    @SuppressLint("SetTextI18n")
    public BitmapDescriptor getMarkerBitmap(MakerInfo markerInfo, Bitmap customAvatarBitmap) {
        if (markerInfo.getMarkerType() == MakerInfo.MarkerType.MINE) {
            if (markerBinding == null) {
                markerBinding = ItemLocationMarkerBinding.inflate(LayoutInflater.from(context));
            }
            ConstraintLayout view = markerBinding.getRoot();
            markerBinding.locationMarkerTvName.setText(markerInfo.getMarkerName());
            if (customAvatarBitmap == null) {
                markerBinding.ivMarkerAvatar.setImageResource(R.drawable.icon_default_mine_avatar);
            } else {
                markerBinding.ivMarkerAvatar.setImageBitmap(customAvatarBitmap);
            }
            markerBinding.vBottom.setBackgroundResource(markerInfo.isSelected() ? R.drawable.icon_mine_marker_selected_bottom_circle : R.drawable.icon_mine_marker_normal_bottom_circle);
            markerBinding.locationMarkerIvBg.setImageResource(markerInfo.isSelected() ? R.drawable.icon_location_mine_marker_selected : R.drawable.icon_location_marker_normal);

            return viewGetBitmapDescriptor(view);
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.FRIEND) {
            Object tags = markerInfo.getTags();
            Integer electric = null;
            if (tags instanceof Map) {
                Map<String, Object> tagsMap = (Map<String, Object>) tags;
                electric = ParamUtil.getInt(tagsMap, "electric");
            }
            if (!markerInfo.isSelected() || electric == null) {
                if (markerBinding == null) {
                    markerBinding = ItemLocationMarkerBinding.inflate(LayoutInflater.from(context));
                }
                ConstraintLayout view = markerBinding.getRoot();
                markerBinding.locationMarkerTvName.setText(markerInfo.getMarkerName());
                if (customAvatarBitmap == null) {
                    markerBinding.ivMarkerAvatar.setImageResource(R.drawable.icon_default_friend_avatar);
                } else {
                    markerBinding.ivMarkerAvatar.setImageBitmap(customAvatarBitmap);
                }
                markerBinding.vBottom.setBackgroundResource(markerInfo.isSelected() ? R.drawable.icon_marker_selected_bottom_circle : R.drawable.icon_marker_normal_bottom_circle);
                markerBinding.locationMarkerIvBg.setImageResource(markerInfo.isSelected() ? R.drawable.icon_location_marker_selected : R.drawable.icon_location_marker_normal);

                return viewGetBitmapDescriptor(view);
            } else {
                if (electricMarkerBinding == null) {
                    electricMarkerBinding = ItemElectricMarkerBinding.inflate(LayoutInflater.from(context));
                }
                ConstraintLayout view = electricMarkerBinding.getRoot();
                electricMarkerBinding.batteryView.setBatteryLevel(electric);
                electricMarkerBinding.tvElectric.setText(electric + "%");
                if (customAvatarBitmap == null) {
                    electricMarkerBinding.ivMarkerAvatar.setImageResource(R.drawable.icon_default_friend_avatar);
                } else {
                    electricMarkerBinding.ivMarkerAvatar.setImageBitmap(customAvatarBitmap);
                }
                electricMarkerBinding.vBottom.setBackgroundResource(markerInfo.isSelected() ? R.drawable.icon_marker_selected_bottom_circle : R.drawable.icon_marker_normal_bottom_circle);
                electricMarkerBinding.locationMarkerIvBg.setImageResource(markerInfo.isSelected() ? R.drawable.icon_location_marker_selected : R.drawable.icon_location_marker_normal);

                return viewGetBitmapDescriptor(view);
            }
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_START_POINT) {
            ItemTrackStartMarkerBinding trackStartPointMarkerBinding = ItemTrackStartMarkerBinding.inflate(LayoutInflater.from(context));
            ConstraintLayout view = trackStartPointMarkerBinding.getRoot();
            return viewGetBitmapDescriptor(view);
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_END_MINE_POINT || markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_END_FRIEND_POINT) {
            ItemLocationMarkerBinding trackEndPointMarkerBinding = ItemLocationMarkerBinding.inflate(LayoutInflater.from(context));
            ConstraintLayout view = trackEndPointMarkerBinding.getRoot();
            trackEndPointMarkerBinding.locationMarkerTvName.setText(markerInfo.getMarkerName());
            if (customAvatarBitmap == null) {
                trackEndPointMarkerBinding.ivMarkerAvatar.setImageResource(markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_END_MINE_POINT ? R.drawable.icon_default_mine_avatar : R.drawable.icon_default_friend_avatar);
            } else {
                trackEndPointMarkerBinding.ivMarkerAvatar.setImageBitmap(customAvatarBitmap);
            }
            trackEndPointMarkerBinding.locationMarkerIvBg.setImageResource(R.drawable.icon_location_marker_normal);
            trackEndPointMarkerBinding.vBottom.setBackgroundResource(R.drawable.icon_marker_track_bottom_circle);
            return viewGetBitmapDescriptor(view);
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_PASSING_POINT) {
            ItemTrackPassingMarkerBinding trackPassingMarkerBinding = ItemTrackPassingMarkerBinding.inflate(LayoutInflater.from(context));
            ConstraintLayout view = trackPassingMarkerBinding.getRoot();
            return viewGetBitmapDescriptor(view);
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_POPUP_POINT) {
            ItemTrackSelectedMarkerBinding trackSelectedMarkerBinding = ItemTrackSelectedMarkerBinding.inflate(LayoutInflater.from(context));
            Object tags = markerInfo.getTags();
            if (tags instanceof Map) {
                Map<String, Object> tagsMap = (Map<String, Object>) tags;
                trackSelectedMarkerBinding.tvPopupTitle.setText(ParamUtil.getString(tagsMap, "title"));
                trackSelectedMarkerBinding.tvPopupDesc.setText(ParamUtil.getString(tagsMap, "desc"));
            }
            ConstraintLayout view = trackSelectedMarkerBinding.getRoot();
            return viewGetBitmapDescriptor(view);
        } else if (markerInfo.getMarkerType() == MakerInfo.MarkerType.TRACE_ERROR_POINT) {
            ItemTrackErrorMarkerBinding trackPassingMarkerBinding = ItemTrackErrorMarkerBinding.inflate(LayoutInflater.from(context));
            ConstraintLayout view = trackPassingMarkerBinding.getRoot();
            return viewGetBitmapDescriptor(view);
        }
        return null;
    }

    private BitmapDescriptor viewGetBitmapDescriptor(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        Bitmap markerBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas markerCanvas = new Canvas(markerBitmap);
        view.draw(markerCanvas);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(markerBitmap);
        markerCanvas.setBitmap(null);
        markerBitmap.recycle();
        return bitmapDescriptor;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        Object object = marker.getObject();
        if (object == null) {
            return false;
        }
        if (object instanceof MakerInfo) {
            MakerInfo markerInfo = (MakerInfo) object;
            markerInfo.setLatitude(marker.getPosition().latitude);
            markerInfo.setLongitude(marker.getPosition().longitude);
            LogUtil.d(TAG, "onMarkerClick==>" + markerInfo);
            methodChannel.invokeMethod(Constants.METHOD_MARKER_ON_TAP, gson.toJson(markerInfo));
            return true;
        }
        return false;
    }
}
