package com.sjkj.appthreefloor_tsgz.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.sjkj.appthreefloor_tsgz.R;
import com.sjkj.appthreefloor_tsgz.bean.ResourceVisualizationBean;
import com.sjkj.appthreefloor_tsgz.databinding.FragmentMapBinding;
import com.sjkj.appthreefloor_tsgz.fragment.viewModel.MapViewModel;
import com.sjkj.appthreefloor_tsgz.map.MapMarkBean;
import com.sjkj.base_lib.app.AppManager;
import com.sjkj.base_lib.utils.CommonUtils;
import com.sjkj.base_lib.utils.Constants;
import com.sjkj.base_lib.utils.MapUtils;
import com.sjkj.base_lib.utils.ToastUtils;
import com.sjkj.base_lib.view.BaseMapFragment;

import java.util.ArrayList;
import java.util.List;

public class CommonMapFragment extends BaseMapFragment {
    private FragmentMapBinding binding;
    private MapViewModel viewModel;
    //显示地图需要的变量
    private AMap aMap;//地图对象
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    //定位需要的声明
    private List<MapMarkBean> markBeans;
    private List<ResourceVisualizationBean> resourceVisualizationBeanList = new ArrayList<>();
    private int zoomValue = 12;//(3-19)
    /**
     * 优先级 ：1/0
     * 1：地图移动到标点位置
     * 0：地图移动到定位位置
     */
    private int priority = 0;
    private MultiPointOverlay multiPointOverlay;
    private MultiPointOverlayOptions overlayOptions;
    private Handler handler = new Handler();

    public CommonMapFragment() {

    }

    private String type = "";


    public CommonMapFragment(String type) {
        this.type = type;
    }

    public CommonMapFragment(List<MapMarkBean> markBeans, int priority) {
        this.markBeans = markBeans;
        this.priority = priority;

    }

//    private void clear() {
//        overlayOptions = null;
//        if (multiPointOverlay != null) {
//            multiPointOverlay.remove();
//            multiPointOverlay.destroy();
//        }
//    }

//    public void refreshData(List<MapMarkBean> markBeans, List<ResourceVisualizationBean> list, String type, int priority) {
//        clear();//先清除图层
//        this.markBeans = markBeans;
//        this.priority = priority;
//        this.resourceVisualizationBeanList = list;
////        changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Constants.DEFAULT_LOCATION_LAT, Constants.DEFAULT_LOCATION_LNG, true), 12, 30, 30)));
//        changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(markBeans.get(markBeans.size() - 1).getLatitude(), markBeans.get(markBeans.size() - 1).getLongitude(), true), 10, 30, 30)));
//        binding.mapView.getMap().clear();
//        overlayOptions = new MultiPointOverlayOptions();
//        setLocationIcon(type);
//        overlayOptions.anchor(0.5f, 0.5f); //设置锚点
//        multiPointOverlay = binding.mapView.getMap().addMultiPointOverlay(overlayOptions);
////        for (int i = 0; i < markBeans.size(); i++) {
////            binding.mapView.getMap().addMarker(new MarkerOptions().position(new LatLng(markBeans.get(i).getLatitude(), markBeans.get(i).getLongitude()))
////                    .visible(true)
////                    .snippet(markBeans.get(i).getId())
////                    .title(markBeans.get(i).getName())
////                    .icon(BitmapDescriptorFactory
////                            .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
////        }
//
//
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                List<MultiPointItem> list = new ArrayList<MultiPointItem>();
//                for (MapMarkBean newList : markBeans) {
//
//                    MultiPointItem multiPointItem = new MultiPointItem(new LatLng(newList.getLatitude(), newList.getLongitude()));
//                    multiPointItem.setTitle(newList.getName());
//
//                    multiPointItem.setCustomerId(newList.getId());
//
//                    list.add(multiPointItem);
//
//
//                }
//                multiPointOverlay.setItems(list);
//            }
//        });
//
//    }

    public void refreshData(List<ResourceVisualizationBean> list) {
        clear();//先清除图层
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            for (ResourceVisualizationBean visualizationBean : list) {
                                if (CommonUtils.checkLongitudeLatitude(visualizationBean.getLongitude(), visualizationBean.getLatitude())) {
                                    MapUtils.GPS gps = MapUtils.gps84_To_Gcj02(Double.parseDouble(visualizationBean.getLatitude()), Double.parseDouble(visualizationBean.getLongitude()));
                                    if (gps != null) {
                                        setLocationIcon(gps, visualizationBean.getId(), visualizationBean.getIndexName() + "", visualizationBean);
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        try {
                            changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(list.get(list.size() - 1).getLatitude()), Double.parseDouble(list.get(list.size() - 1).getLongitude()), true), 10, 30, 30)));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();

    }

    private void clear() {
        if (binding.mapView.getMap() != null)
            binding.mapView.getMap().clear();
    }

    private void setLocationIcon(MapUtils.GPS gps, String id, String type, ResourceVisualizationBean bean) {
        Log.e("ICON", type);
        MarkerOptions options = new MarkerOptions();
        options.position(new LatLng(gps.getLat(), gps.getLon()));
        options.visible(true);
        options.snippet(id);
        options.infoWindowEnable(false);
//        options.title(dataBean.getName());
        switch (type) {
            //农业
            case "centerdata_t_farm_agricultural_cooperatives"://农民合作社
                options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_agriculture_cooperatives));//设置图标
                break;

            default:
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));//设置图标
                break;

        }
        binding.mapView.getMap().addMarker(options);


    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_map;
    }

    @Override
    public View initBinding(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        binding = (FragmentMapBinding) getViewDataBing(inflater, container);
        viewModel = new ViewModelProvider((ViewModelStoreOwner) AppManager.getAppManager().currentActivity(), new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner((LifecycleOwner) this);
        binding.mapView.onCreate(bundle);
        binding.mapView.getMap().getUiSettings().setLogoBottomMargin(-50);
        binding.mapView.getMap().getUiSettings().setZoomControlsEnabled(true);
        binding.mapView.getMap().getUiSettings().setMyLocationButtonEnabled(false);
        //binding.mapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(43.911535, 125.324667), zoomValue));
        changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Constants.DEFAULT_LOCATION_LAT,Constants.DEFAULT_LOCATION_LNG, true), 10, 30, 30)));

        return binding.getRoot();
    }

    @Override
    public void initView() {

        requestPermissionsLocation();
    }

    /**
     * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
     */
    private void changeCamera(CameraUpdate update) {

        binding.mapView.getMap().moveCamera(update);

    }

    private void requestPermissionsLocation() {
        XXPermissions.with(AppManager.getAppManager().currentActivity())
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
//                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //开始定位
                            initLocation();
                        } else {
                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show("被永久拒绝授权，请手动授予权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(AppManager.getAppManager().currentActivity(), permissions);
                        } else {
                            ToastUtils.show("获取权限失败");
                        }
                    }
                });
    }

    private void initLocation() {


    }

    @Override
    public void initListener() {
        binding.mapView.getMap().setOnMultiPointClickListener(new AMap.OnMultiPointClickListener() {
            @Override
            public boolean onPointClick(MultiPointItem multiPointItem) {
                if (resourceVisualizationBeanList != null && resourceVisualizationBeanList.size() > 0) {
                    for (ResourceVisualizationBean bean : resourceVisualizationBeanList) {
                        if (multiPointItem.getCustomerId().equals(bean.getId())) {
//                            Intent intent = new Intent(getActivity(), ResourcePointDetailsActivity.class);
//                            intent.putExtra("type", type);
//                            intent.putExtra("id", bean.getId());
//                            intent.putExtra("lat",bean.getLatitude());
//                            intent.putExtra("lng",bean.getLongitude());
//                            startActivity(intent);
                        }
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void loadData() {

    }

    //自定义一个图钉，并且设置图标，当我们点击图钉时，显示设置的信息

    /**
     * @param lat 纬度
     * @param log 经度
     * @return
     */
    private MarkerOptions getMarkerOptions(double lat, double log, String address) {
        //设置图钉选项
        MarkerOptions options = new MarkerOptions();
        //图标
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_baseline_local_fire_department_24));
        //位置
        options.position(new LatLng(lat, log));
        //标题
        options.title(address);
        options.visible(true);
        //子标题
        //options.snippet("这里好火");
        //设置多少帧刷新一次图片资源
        options.period(60);
        return options;
    }

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

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

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding.mapView.onDestroy();
    }


}
