package com.xxfc.discovery.other;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.frame.base.url.Constance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.presenter.DiscoveryPresenter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = Constance.ACTIVITY_URL_MAPLOCATION)
public class MapLocationActivity extends BaseStatusActivity<DiscoveryPresenter> {
    @BindView(R2.id.bmapView)
    MapView mMapView;
    @BindView(R2.id.iv_logo)
    ImageView ivLogo;
    @BindView(R2.id.tv_pat_name)
    TextView tvPatName;
    @BindView(R2.id.tv_pat_address)
    TextView tvPatAddress;
    @BindView(R2.id.ll_layout_address)
    LinearLayout llLayoutAddress;

    BaiduMap mBaiduMap;

    private LocationManager locationManager;
    boolean isFirstLoc = true; // 是否首次定位
    @Autowired()
    double latLatitude;
    @Autowired()
    double lonLongitude;

    private String mAddress;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("所在位置");
        initMap();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }

    /**
     * 初始化百度
     */
    private void initMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        if (latLatitude > 0) {
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(createMapStatusBuilder(new LatLng(latLatitude, lonLongitude)).build()));
        } else {
            locationManager = new LocationManager(this, new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation bdLocation) {
                    intiMapLocation(bdLocation);
                    tvPatAddress.setText(bdLocation.getAddrStr());
                    mAddress = bdLocation.getAddrStr();
                    locationManager.stopLocation();
//                locationManager.onDestroy();
                }
            });
        }

        //检索数据
        geoCode();
    }

    private void geoCode() {
        final GeoCoder geoCoder = GeoCoder.newInstance();
        // 创建地理编码检索实例
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            // 反地理编码查询结果回调函数
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                }
                mAddress = result.getSematicDescription();
                tvPatName.setText(result.getBusinessCircle());
                tvPatAddress.setText(result.getSematicDescription());//这里的addressText就是我们要的地址
//                Log.i("info===",""+result.getAddress()+"=="+result.getBusinessCircle()+"=="+result.getSematicDescription()+"=="+result.toString());
            }

            // 地理编码查询结果回调函数
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null
                        || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                }
            }
        };
        // 设置地理编码检索监听者
        geoCoder.setOnGetGeoCodeResultListener(listener);
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                tvPatAddress.setVisibility(View.GONE);
                Translate();
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
//                LatLng latLng=mapStatus.bound.getCenter();
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
//              LatLng latLng=mapStatus.bound.getCenter();
                ivLogo.clearAnimation();
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                tvPatAddress.setVisibility(View.VISIBLE);
                latLatitude = mapStatus.bound.getCenter().latitude;
                lonLongitude = mapStatus.bound.getCenter().longitude;
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(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;

            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//            if (!selectCity.equals(nowCity)) {
//                setSearchContent(selectCity, selectCity.equals("北京") ? "故宫" : selectCity);
//                return;
//            }
        }
    }

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

    /**
     * 动画平移
     */
    public void Translate() {
        /*
         * TranslateAnimation translateAni = new TranslateAnimation(fromXType,
         * fromXValue, toXType, toXValue, fromYType, fromYValue, toYType,
         * toYValue);
         */
        //参数1～2：x轴的开始位置
        //参数3～4：y轴的开始位置
        //参数5～6：x轴的结束位置
        //参数7～8：x轴的结束位置
        TranslateAnimation translateAni = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
                0f, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, -0.1f);

        //设置动画执行的时间，单位是毫秒
        translateAni.setDuration(500);

        // 设置动画重复次数
        // -1或者Animation.INFINITE表示无限重复，正数表示重复次数，0表示不重复只播放一次
        translateAni.setRepeatCount(Animation.INFINITE);

        // 设置动画模式（Animation.REVERSE设置循环反转播放动画,Animation.RESTART每次都从头开始）
        translateAni.setRepeatMode(Animation.REVERSE);

        // 启动动画
        ivLogo.startAnimation(translateAni);
    }

    /**
     * 通过经纬度获得最新的地址
     *
     * @param latLng
     * @return
     */
    private MapStatus.Builder createMapStatusBuilder(LatLng latLng) {

        return new MapStatus.Builder().target(latLng).zoom(18.0f);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R2.id.tv_pat_ok})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_pat_ok){
            if (TextUtils.isEmpty(mAddress) && latLatitude > 0) {
                finish();
                return;
            }

            getIntent().putExtra("location", mAddress);
            getIntent().putExtra("latitude", latLatitude);
            getIntent().putExtra("longitude", lonLongitude);
            setResult(RESULT_OK, getIntent());
            finish();
        }
    }
}
