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

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

import com.alibaba.android.arouter.facade.annotation.Autowired;
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.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
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.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.swipe.SwipeBackActivity;
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.home.R;
import com.rv.home.R2;
import com.rv.component.dialog.PickerDialog;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created :Auser
 * Date: 2019/6/5.
 * Desc:详情地图
 */
@Route(path = Constance.ACTIVITY_URL_CARDETAILMAP)
public class CarDetailMapActivity extends SwipeBackActivity<CommonPresenter> {


    @BindView(R2.id.bmapView)
    MapView mMapView;
    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.iv_location)
    ImageView ivLocation;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_address)
    TextView tvAddress;
    @BindView(R2.id.tv_phone)
    TextView tvPhone;
    @BindView(R2.id.rl_navigation)
    RelativeLayout rlNavigation;
    @BindView(R2.id.ll_visible)
    LinearLayout llVisible;
    private LocationManager locationManager;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位

    @Autowired()
    String addrDetail;
    @Autowired()
    String phone;
    @Autowired()
    String name;
    @Autowired()
    double latitude;
    @Autowired()
    double longitude;


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

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

        tvAddress.setText(String.format("%1$s%2$s", "地址：", addrDetail));
        tvPhone.setText(String.format("%1$s%2$s", "联系电话：", phone));
        tvName.setText(name);
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    public void onShowResult(int requestType, BaseBean 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) {
        if (view.getId() == R.id.iv_back) {
            finish();
        } else if (view.getId() == R.id.iv_location) {
            if (locationManager != null) {
                locationManager.startLocation();
            }
        } else if (view.getId() == R.id.rl_navigation) {
            showPickerDialog(new LatLng(latitude, longitude), addrDetail);

        }
    }

    /**
     * 初始化地图
     */
    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();
            }
        });

    }

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

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

    }

    /**
     * 初始化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;
            mBaiduMap.addOverlay(getMark());
            updateMap(new LatLng(latitude, longitude));

        }
    }

    /**
     * 设置mark信息
     *
     * @return
     */
    private OverlayOptions getMark() {
        //定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.rv_map_shop);
        return new MarkerOptions()
                .position(point)
                .title(name)
                .icon(bitmap)
                .animateType(MarkerOptions.MarkerAnimateType.drop);
    }

    /**
     * 显示地图弹窗
     */
    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) {

                        if (v.getId() == R.id.btn_camera) {
                            MapUtil.getInstance(mActivity).goToBaiduMap(latLng, address, false);
                            dismiss();
                        } else if (v.getId() == R.id.btn_album) {
                            MapUtil.getInstance(mActivity).goToGaodeMap(latLng, address, true);
                            dismiss();
                        } else if (v.getId() == R.id.btn_cancel) {
                            dismiss();
                        }

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


}
