package com.rv.camp.camp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.MapUtil;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.camp.R;
import com.rv.camp.R2;
import com.rv.camp.api.CampApi;
import com.rv.camp.bean.CampListBean;
import com.rv.camp.presenter.CampPresenter;
import com.rv.component.dialog.BottomPromptDialog;
import com.rv.component.utils.LocationRecord;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;

/**
 * 门店地图
 */
public class CampShopShowActivity extends BaseStatusActivity<CampPresenter> {
    @BindView(R2.id.bmapView)
    MapView mMapView;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_address)
    TextView tvAddress;
    @BindView(R2.id.ll_visible)
    LinearLayout rlVisible;
    @BindView(R2.id.tv_phone)
    TextView tvPhone;

    private LocationManager locationManager;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    List<OverlayOptions> list;
    private double mLat;
    private double mLon;
    private boolean isClick;//是否第一次点击
    private CampListBean.DataBeanX.DataBean selectBean;

    private LatLng locationLatLng;


    public static Intent getIntent(Context context) {
        return new Intent(context, CampShopShowActivity.class);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_act_shop_show;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
//             titleView.setTitle(mActivity.getString(R.string.rv_shop_map));
        showTitle(false);
//        initGps();
        initMap();
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getShopList(1);

    }

    /**
     * 初始化定位
     */
    public void initGps() {
        if (!isGpsOpen()) {
            Toast.makeText(getApplicationContext(), "请先打开gps", Toast.LENGTH_SHORT).show();
            return;
        }
        locationManager = new LocationManager(getApplicationContext());
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                int errorCode = location.getLocType();
                if (errorCode == 61 || errorCode == 161) {
                    double latLatitude = LocationRecord.getOrSavelatLatitude(getApplicationContext(), errorCode, location.getLatitude());
                    double lonLongitude = LocationRecord.getOrSaveLonLongitude(getApplicationContext(), errorCode, location.getLongitude());
                    locationLatLng = new LatLng(latLatitude, lonLongitude);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, "定位失败!", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private boolean isGpsOpen() {
        android.location.LocationManager lm = (android.location.LocationManager) this.getSystemService(LOCATION_SERVICE);
        return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        processData((CampListBean) result);
    }


    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        MapUtil.getInstance(mActivity).onDestroy();
        // 退出时销毁定位
        if (locationManager != null) {
            locationManager.onDestroy();
            locationManager = null;
        }
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }


    @OnClick({R2.id.iv_back, R2.id.iv_location, R2.id.rl_navigation})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.iv_location) {
            isVisible(View.GONE);
            if (locationManager != null) {
                locationManager.startLocation();
            }

        } else if (i == R.id.rl_navigation) {
            if (selectBean != null) {
                showPickerDialog(new LatLng(selectBean.getLatitude(), selectBean.getLongitude()), selectBean.getAddress());
            }
        }
    }

    /**
     * 获取门店列表
     */
    private void getShopList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("pageSize", 1000);
        mPresenter.getData(RvFrameConfig.VEHICLE_CAMPLIST, 0, CampApi.TRAVEL_CAMPSITESHOP, CampListBean.class, map, page == 1 ? false : false);
    }

    private void processData(CampListBean bean) {
        list = new ArrayList<>();
        Observable.fromIterable(bean.getData().getData()).subscribe(new DisposableObserver<CampListBean.DataBeanX.DataBean>() {
            @Override
            public void onNext(CampListBean.DataBeanX.DataBean dataBean) {
                list.add(getMark(dataBean));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                mBaiduMap.addOverlays(list);
                dispose();
            }
        });


    }

    /**
     * 初始化地图
     */
    private void initMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        locationManager = new LocationManager(this, new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {

                locationManager.stopLocation();
                if (isFirstLoc == false) {
                    updateMap(new LatLng(bdLocation.getLatitude(),
                            bdLocation.getLongitude()));
                } else {
                    intiMapLocation(bdLocation);
                }
//                locationManager.onDestroy();
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {
                isClick = true;
                isVisible(View.VISIBLE);
                Bundle bundle = marker.getExtraInfo();
                selectBean = (CampListBean.DataBeanX.DataBean) bundle.getSerializable("info");
                tvAddress.setText(String.format("%1$s%2$s", "地址：", selectBean.getAddress()));
                tvPhone.setText(String.format("%1$s%2$s", "联系电话：", selectBean.getPhone()));
                tvName.setText(selectBean.getName());
                updateMap(marker.getPosition());
                return true;
            }
        });

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                if (isClick == true) {
                    isClick = false;
                    createWin(mapStatus.bound.getCenter());
                }

            }
        });
    }


    /**
     * 初始化map
     *
     * @param location
     */
    private void intiMapLocation(BDLocation location) {
        if (location == null || mMapView == null) {
            return;
        }
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.getDirection()).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();

        mBaiduMap.setMyLocationData(locData);
        if (isFirstLoc) {
            isFirstLoc = false;

            updateMap(new LatLng(mLat > 0 ? mLat : location.getLatitude(), mLon > 0 ? 0 :
                    location.getLongitude()));

        }
    }


    /**
     * 设置mark信息
     *
     * @param bean
     * @return
     */
    private OverlayOptions getMark(CampListBean.DataBeanX.DataBean bean) {
        //定义Maker坐标点
        LatLng point = new LatLng(bean.getLatitude(), bean.getLongitude());
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.rv_map_shop);
//构建MarkerOption，用于在地图上添加Marker
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", bean);

        return new MarkerOptions()
                .position(point)
                .title(bean.getName())
                .icon(bitmap)
                .extraInfo(bundle)
                .animateType(MarkerOptions.MarkerAnimateType.drop);
    }


    /**
     * 更新地图
     *
     * @param latLng
     */
    private void updateMap(LatLng latLng) {

        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(latLng).zoom(10.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

    }

    /**
     * 是否显示
     *
     * @param visible
     */
    private void isVisible(int visible) {
        if (rlVisible == null) {
            return;
        }
        rlVisible.setVisibility(visible);
    }


    private void createWin(final LatLng latLng) {
        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setBackgroundResource(R.drawable.rv_max_map_shop);
        mBaiduMap.showInfoWindow(new InfoWindow(imageView, latLng, 0));
    }

    /**
     * 显示地图弹窗
     */
    private void showPickerDialog(final LatLng latLng, final String address) {
        new BottomPromptDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.btn1, "百度地图");
                helper.setText(R.id.btn2, "高德地图");
                helper.setText(R.id.btn3, "取消");
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.btn1) {
                            MapUtil.getInstance(mActivity).goToBaiduMap(latLng, address, false);
                            dismiss();

                        } else if (i == R.id.btn2) {
                            MapUtil.getInstance(mActivity).goToGaodeMap(locationLatLng == null ? new LatLng(LocationRecord.getLat(getApplicationContext()), LocationRecord.getLon(getApplicationContext())) : locationLatLng, latLng, address, true);
                            dismiss();

                        } else if (i == R.id.btn3) {
                            dismiss();

                        }

                    }
                }, R.id.btn1, R.id.btn2, R.id.btn3);
            }
        }.show();
    }


}


