package com.rv.home.rv.module.ui.main.home;

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 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.rv.component.utils.LocationRecord;
import com.rv.home.R;
import com.rv.home.R2;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.weight.TitleView;

import com.rv.home.rv.module.ApiConfig;
import com.rv.component.dialog.PickerDialog;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.bean.ShopListBean;

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;

/**
 * Created :Auser
 * Date: 2019/5/22.
 * Desc:门店地图
 */
@Route(path = Constance.ACTIVITY_URL_SHOPSHOW)
public class ShopShowActivity extends BaseStatusActivity<CommonPresenter> {
    @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 ShopListBean.DataBeanX.DataBean selectBean;
    private LatLng locationLatLng;

    public static Intent getIntent(Context context, double lat, double lon) {
        return new Intent(context, ShopShowActivity.class)
                .putExtra("lat", lat)
                .putExtra("lon", lon);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
//             titleView.setTitle(mActivity.getString(R.string.rv_shop_map));
        showTitle(false);
        mLat = intent.getDoubleExtra("lat", 0);
        mLon = intent.getDoubleExtra("lon", 0);
        initMap();
    }

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


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

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        processData((ShopListBean) 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.getAddrDetail());
            }
        }
    }

    /**
     * 获取门店列表
     */
    private void getShopList(int page) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("page", page);
        map.put("limit", 1000);
        if (mLat > 0) {
            map.put("lat", mLat);
            map.put("lon", mLon);
        }
        mPresenter.getData(RvFrameConfig.VEHICLE_POST, 0, ApiConfig.HTTP_URL_SHOP_LIST, ShopListBean.class, map, true);
    }

    private void processData(ShopListBean bean) {
        list = new ArrayList<>();
        Observable.fromIterable(bean.getData().getData()).subscribe(new DisposableObserver<ShopListBean.DataBeanX.DataBean>() {
            @Override
            public void onNext(ShopListBean.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) {

                if (bdLocation != null) {
                    locationLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                }
                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 = (ShopListBean.DataBeanX.DataBean) bundle.getSerializable("info");
                tvAddress.setText(String.format("%1$s%2$s", "地址：", selectBean.getAddrDetail()));
                tvPhone.setText(String.format("%1$s%2$s", "联系电话：", selectBean.getLeaderContactInfo()));
                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(ShopListBean.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 PickerDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.btn_camera, "百度地图");
                helper.setText(R.id.btn_album, "高德地图");
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.btn_camera) {
                            MapUtil.getInstance(mActivity).goToBaiduMap(latLng, address, false);
                            dismiss();

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

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

                        }

                    }
                }, R.id.btn_camera, R.id.btn_album, R.id.btn_cancel);
            }
        }.show();
    }


}


