package com.tofly.ghrq_route.common.ui.fragment;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.common.ui.activity.UiBuildManageDetail;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.user.domain.UserBean;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Amu on 2017/5/24.
 */

public class BuildAddressFragment extends Fragment {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.cardview_route)
    CardView cardViewBtnRoute;
    @BindView(R.id.layer_manager)
    ImageView layerManager;
    @BindView(R.id.text_map_sketch)
    TextView textSketch;
    @BindView(R.id.text_addr)
    TextView textMyAddr;
    Unbinder unbinder;

    private static final String TAG = BuildAddressFragment.class.getName();

    private Activity mContext;

    private View mRootView;

    private UserBean mUser;

    private BuildManageBean mBuildManage;

    private UiBuildManageDetail uiBuildManageDetail;

    /*private LocationService locationService;

    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用*/

    private LocationDisplay arcgisLdm;

    private static Point mLocation = null;

    private String mLocAddr = null;

    private boolean isFirstLoc = true; // 是否首次定位

    public BuildAddressFragment(BuildManageBean buildManage, UiBuildManageDetail buildManageDetail) {
        this.mBuildManage = buildManage;
        this.uiBuildManageDetail = buildManageDetail;
    }

    public MapView getMapView(){
        return mapView;
    }

    public Point getLocation(){
        return mLocation;
    }

    public String getLocAddr(){
        return mLocAddr;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mUser = BaseApp.getInstance().getLoginUser();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mContext = getActivity();
            mRootView = inflater.inflate(R.layout.fragment_build_address, container, false);
        } else {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }
        unbinder = ButterKnife.bind(this, mRootView);
        return mRootView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        textSketch.setVisibility(View.GONE);
    }

    private void initData(){
        initArcgisLocationService();
        //initBaiduLocationService();

        uiBuildManageDetail.loadAllMap(mapView);
        //uiBuildManageDetail.mapController.loadSatelliteLayer();
    }

    private void initListener(){
        layerManager.setOnClickListener(v -> uiBuildManageDetail.showLayoutManager(mapView));

        cardViewBtnRoute.setOnClickListener(v -> onBtnRoute());
    }

    public void showBuildAddr(){
        if (mBuildManage != null){
            double lng = mBuildManage.getX();
            double lat = mBuildManage.getY();
            Point geometry = new Point(lng, lat);
            BitmapDrawable signedLoc = (BitmapDrawable) getResources().getDrawable(R.mipmap.danger_location);
            PictureMarkerSymbol symbol = new PictureMarkerSymbol(signedLoc);
            GraphicsOverlay graphicsLayer = new GraphicsOverlay();
            graphicsLayer.getGraphics().add(new Graphic(geometry, symbol));
            mapView.getGraphicsOverlays().add(graphicsLayer);

            if (mLocation != null) {
                PointCollection collection = new PointCollection(mapView.getSpatialReference());
                collection.add(mLocation);
                collection.add(geometry);
                Polyline polyline  = new Polyline(collection);
                GraphicsOverlay extentLayer = new GraphicsOverlay();
                int lineColor = getResources().getColor(R.color.transparent);
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, 0.0f);
                graphicsLayer.getGraphics().add(new Graphic(polyline, lineSymbol));
                mapView.getGraphicsOverlays().add(extentLayer);
                //mapView.setExtent(polyline, 1000);
            }

            /*String xx = Double.toString(lng);
            String yy = Double.toString(lat);
            reserveLocation(xx, yy);*/
        }
    }

    private void initArcgisLocationService() {
        arcgisLdm = mapView.getLocationDisplay();
        arcgisLdm.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
        arcgisLdm.startAsync();
        arcgisLdm.addLocationChangedListener(arcgisListener);
    }

    private LocationDisplay.LocationChangedListener arcgisListener = event -> {
        if (event == null || event.getLocation() == null)
            return;

        if (isFirstLoc) {
            LocationDataSource.Location location =  event.getLocation();
            if (location != null && location.getPosition() != null) {
                Point point = location.getPosition();
                mLocation = point;
                isFirstLoc = false;
            }
        }
    };

/*    private void initBaiduLocationService(){
        locationService = new LocationService(mContext);
        locationService.registerListener(mListener);//定位的监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();//开始定位
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                if (true) {
                    Address baiduAddress = location.getAddress();
                    if (baiduAddress == null)
                        return;

                    String text = location.getCity() + "  " +
                            location.getDistrict() + "  " + location.getStreet() +
                            location.getStreetNumber();
                    String xx = Double.toString(location.getLongitude());
                    String yy = Double.toString(location.getLatitude());
                    mLocAddr = text;
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };

    private void reserveLocation(String x, String y) {
        //将地图的中心点的坐标转化百度地图的坐标
        double lon = Double.parseDouble(x);
        double lan = Double.parseDouble(y);
        BigDecimal bg1 = new BigDecimal(lon);
        lon = bg1.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        BigDecimal bg2 = new BigDecimal(lan);
        lan = bg2.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        LatLng ptCenter = new LatLng(lan, lon);
        //使用百度地图，根据坐标点查询地理位置
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            return;

        }
        String address = result.getAddressDetail().city + "  " +
                result.getAddressDetail().district + "  " + result.getAddressDetail().street +
                result.getAddressDetail().streetNumber;
        textMyAddr.setText(address);
    }*/

    private void onBtnRoute(){
        uiBuildManageDetail.onTurnToBaiduRoute();
    }

    @Override
    public void onResume() {
        super.onResume();
        initArcgisLocationService();
        //initBaiduLocationService();
    }

    @Override
    public void onStop() {
        super.onStop();
        /*locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务*/
        arcgisLdm.stop();
    }

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

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /*locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务*/
        arcgisLdm.stop();
    }
}
