package com.sjkj.base_lib.map;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;

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

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.model.BitmapDescriptor;
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.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.sjkj.base_lib.R;
import com.sjkj.base_lib.databinding.ActivityChooseMapBinding;
import com.sjkj.base_lib.utils.AppTools;
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.BaseActivity;

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

public class ChooseMapActivity extends BaseActivity implements GeoFenceListener, AMap.OnMapClickListener, LocationSource, AMapLocationListener {
    //private MapViewModel viewModel;
    private MapViewModel viewModel;
    private ActivityChooseMapBinding binding;
    private AMapLocationClient mlocationClient;
    private OnLocationChangedListener mListener;
    private AMapLocationClientOption mLocationOption;


    // 中心点坐标
    private LatLng centerLatLng = null;
    // 中心点marker
    private Marker centerMarker;
    List<GeoFence> fenceList = new ArrayList<GeoFence>();

    private BitmapDescriptor ICON_YELLOW = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW);
    private BitmapDescriptor ICON_RED = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE);
    private MarkerOptions markerOption = null;
    private List<Marker> markerList = new ArrayList<Marker>();
    private String address;
    private GeocodeSearch geocodeSearch;

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        super.initBinding();
        binding = (ActivityChooseMapBinding) getViewDataBinding();
       // viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);
        //binding.setViewModel(viewModel);
        viewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        binding.mapView.getMap().getUiSettings().setLogoBottomMargin(-50);
        binding.mapView.getMap().getUiSettings().setZoomControlsEnabled(true);
        binding.mapView.getMap().getUiSettings().setMyLocationButtonEnabled(true);
        binding.mapView.getMap().getUiSettings().setRotateGesturesEnabled(false);
        binding.mapView.getMap().moveCamera(CameraUpdateFactory.zoomBy(5));

    }

    @Override
    public void initView() {
        super.initView();
        getTitleView().setText("经纬度选择");
        if (AppTools.isGhb()){
            binding.tvResult.setTextSize(20);
            binding.tvResult.getPaint().setFakeBoldText(true);
        }
        markerOption = new MarkerOptions().draggable(true);
        binding.mapView.getMap().setOnMapClickListener(this);
        binding.mapView.getMap().setLocationSource(this);// 设置定位监听
        binding.mapView.getMap().getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(
                BitmapDescriptorFactory.fromResource(R.drawable.ic_baseline_location_on_24));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 将自定义的 myLocationStyle 对象添加到地图上
        binding.mapView.getMap().setMyLocationStyle(myLocationStyle);
        binding.mapView.getMap().setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        binding.mapView.getMap().setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(AppTools.getDefaultLat(), AppTools.getDefaultLng(), true), 12, 30, 30)));
        /*geocodeSearch = null;
        try {
            geocodeSearch = new GeocodeSearch(this);
            geocodeSearch.setOnGeocodeSearchListener(this);
        } catch (AMapException e) {
            e.printStackTrace();
        }*/
        binding.tvResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (centerLatLng != null) {
                    Intent intent = new Intent();
                    MapUtils.GPS gps = MapUtils.gcj_To_Gps84(centerLatLng.latitude, centerLatLng.longitude);
                    LatLng latLng = new LatLng(gps.getLat(), gps.getLon());
                    intent.putExtra("LatLng", latLng);
                    intent.putExtra("address", address);
                    setResult(Constants.SYSTEM_100, intent);
                    finish();
                } else {
                    ToastUtils.show("定位失败,请稍后重试");
                }
            }
        });
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        binding.mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        binding.mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapView.onSaveInstanceState(outState);
    }


    private void changeCamera(CameraUpdate newCameraPosition) {
        binding.mapView.getMap().moveCamera(newCameraPosition);

    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();


        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }


    @Override
    public void onGeoFenceCreateFinished(final List<GeoFence> geoFenceList,
                                         int errorCode, String customId) {
        Message msg = Message.obtain();
        if (errorCode == GeoFence.ADDGEOFENCE_SUCCESS) {
            fenceList = geoFenceList;
            msg.obj = customId;
            msg.what = 0;
        } else {
            msg.arg1 = errorCode;
            msg.what = 1;
        }

    }

    @Override
    public void onMapClick(LatLng latLng) {
        markerOption.icon(ICON_RED);
        address = "";
        centerLatLng = latLng;
        addCenterMarker(centerLatLng);
//
        LatLonPoint latLonPoint = new LatLonPoint(centerLatLng.latitude, centerLatLng.longitude);
        //第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        GeocodeSearch myGeocodeSearch = null;
        try {
            myGeocodeSearch = new GeocodeSearch(this);

            //添加检索结果监听器
            myGeocodeSearch.setOnGeocodeSearchListener(
                    new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            String myAddress = regeocodeResult.getRegeocodeAddress()
                                    .getFormatAddress();
                           /* MarkerOptions myMarkerOptions = new MarkerOptions();
                            myMarkerOptions.position(new LatLng(centerLatLng.latitude, centerLatLng.longitude));
                            myMarkerOptions.title("该地的详细地址如下：");
                            myMarkerOptions.snippet(myAddress);
                            Marker myMarker = binding.mapView.getMap().addMarker(myMarkerOptions);
                            myMarker.showInfoWindow();
                            binding.mapView.getMap().moveCamera(CameraUpdateFactory.changeLatLng(
                                    new LatLng(centerLatLng.latitude, centerLatLng.longitude))); //设置该地址为高德地图中心*/
                            address = myAddress;
                        }

                        @Override
                        public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                        }
                    });
            //通过RegeocodeQuery封装查询的地址信息，并指定坐标系类型和搜索范围
            RegeocodeQuery RegeocodeQuery =
                    new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
            //查询指定经纬度，并将结果传入回调接口
            myGeocodeSearch.getFromLocationAsyn(RegeocodeQuery);
        } catch (AMapException e) {
            e.printStackTrace();

        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                centerLatLng = null;
                MapUtils.GPS gps = MapUtils.gcj_To_Gps84(amapLocation.getLatitude(), amapLocation.getLongitude());
                centerLatLng = new LatLng(gps.getLat(), gps.getLon());
                address = amapLocation.getAddress();
            } else {
                String errText1 = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                String errText = "定位失败，请重试";
                ToastUtils.show(errText);
                //   tvResult.setVisibility(View.VISIBLE);
                //tvResult.setText(errText);
            }
        }
    }

    /**
     * **定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            try {
                mlocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mlocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            // 只是为了获取当前位置，所以设置为单次定位
            mLocationOption.setOnceLocation(true);
            // 设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    private void addCenterMarker(LatLng latlng) {
        if (null == centerMarker) {
            centerMarker = binding.mapView.getMap().addMarker(markerOption);
        }
        centerMarker.setPosition(latlng);

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


}
