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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
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.GeoCodeOption;
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.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
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.rv.home.R;
import com.rv.home.R2;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.SearchAdapter;
import com.rv.home.rv.module.ui.main.home.bean.SearchBean;

import java.util.ArrayList;
import java.util.List;

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

public class SelectLocationActivity extends BaseStatusActivity<CommonPresenter> implements OnGetSuggestionResultListener {

    @BindView(R2.id.bmapView)
    MapView mMapView;
    @BindView(R2.id.iv_logo)
    ImageView ivLogo;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.et_search)
    EditText etContent;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.fl_rv)
    FrameLayout mFl;
    @BindView(R2.id.tv_city)
    TextView tvCity;
    @BindView(R2.id.ll_item_car_city)
    LinearLayout llItemCarCity;

    private LocationManager locationManager;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    private SuggestionSearch mSuggestionSearch = null;
    private SearchAdapter searchAdapter;
    private String selectCity;
    private int locationType;
    private double latLatitude;
    private double lonLongitude;
    private String nowCity;
    private String mAddress;
    private int mCityId;// 头城市ID
    private int isShowCity;
    private GeoCoder geoCoder;

    public static Intent getIntent(Context context, int type, String city,int cityId, double latitude, double longitude, String now_city, int isShowCity) {
        return new Intent(context, SelectLocationActivity.class)
                .putExtra("type", type)
                .putExtra("city", city)
                .putExtra("cityId",cityId)
                .putExtra("latitude", latitude)
                .putExtra("longitude", longitude)
                .putExtra("now_city", now_city)
                .putExtra("isShowCity", isShowCity);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        mCityId = intent.getIntExtra("cityId",0);
        selectCity = intent.getStringExtra("city");
        locationType = intent.getIntExtra("type", 1);
        latLatitude = intent.getDoubleExtra("latitude", 0);
        lonLongitude = intent.getDoubleExtra("longitude", 0);
        nowCity = intent.getStringExtra("now_city");
        isShowCity = intent.getIntExtra("isShowCity", 0);
        tvCity.setText(selectCity);
        if (0 == isShowCity) {
            llItemCarCity.setVisibility(View.GONE);
        } else {
            llItemCarCity.setVisibility(View.VISIBLE);
        }
        initTitle(titleView);
        initMap();
        intiView();
        initCity();
    }

    @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() {
        // 退出时销毁定位
        if (locationManager != null) {
            locationManager.onDestroy();
        }
        // 退出时销毁定位
        mSuggestionSearch.destroy();
//        MapUtil.getInstance(this).onDestroy();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    private void initTitle(TitleView titleView) {
        titleView.setTitle(mActivity.getString(R.string.rv_select_address));
        titleView.setText(R.id.tv_title_right, mActivity.getString(R.string.rv_ok));
        titleView.setChildClickListener(R.id.tv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mAddress) && latLatitude > 0) {
                    finish();
                    return;
                }
                if (TextUtils.isEmpty(mAddress)) {
                    showToast(mActivity.getString(R.string.rv_select_address_toast));
                    return;
                }
                getIntent().putExtra("location", mAddress);
                getIntent().putExtra("type", locationType);
                getIntent().putExtra("latitude", latLatitude);
                getIntent().putExtra("longitude", lonLongitude);
                getIntent().putExtra("city",selectCity);
                getIntent().putExtra("cityId",mCityId);

                setResult(RESULT_OK, getIntent());
                finish();
            }
        });
    }



    /**
     * 初始化百度
     */
    private void initMap() {
        mBaiduMap = mMapView.getMap();
        // 初始化建议搜索模块，注册建议搜索事件监听
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        // 开启定位图层
        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);
                    if (TextUtils.isEmpty(nowCity)) {
                        nowCity = bdLocation.getCity();
                    }

                    tvContent.setVisibility(TextUtils.isEmpty(bdLocation.getAddrStr()) ? View.GONE : View.VISIBLE);
                    tvContent.setText(bdLocation.getAddrStr());
                    mAddress = bdLocation.getAddrStr();
                    locationManager.stopLocation();
//                locationManager.onDestroy();
                }
            });

        }

        //检索数据
        geoCode();
    }


    /**
     * 初始化view
     */
    private void intiView() {
        searchAdapter = new SearchAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(searchAdapter);
        /* 当输入关键字变化时，动态更新建议列表 */
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

                if (TextUtils.isEmpty(selectCity)) {
                    return;
                }
                if (cs.length() <= 0) {
                    mFl.setVisibility(View.GONE);
                    tvContent.setVisibility(View.VISIBLE);
                    return;
                }
                tvContent.setVisibility(View.GONE);
                setSearchContent(selectCity, cs.toString());

            }
        });

        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                SearchBean searchBean = searchAdapter.getItem(position);
                if (!searchBean.getSearchCity().contains(selectCity)) {
                    showToast(mActivity.getString(R.string.rv_select_address_toast1));
                    return;
                }
                etContent.setText("");
                getIntent().putExtra("location", searchBean.getSearchName());
                getIntent().putExtra("type", locationType);
                getIntent().putExtra("latitude", searchBean.getLatLng().latitude);
                getIntent().putExtra("longitude", searchBean.getLatLng().longitude);
                getIntent().putExtra("city",selectCity);
                getIntent().putExtra("cityId",mCityId);

                setResult(RESULT_OK, getIntent());
                finish();
//                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(createMapStatusBuilder(searchBean.getLatLng()).build()));
//                mFl.setVisibility(View.GONE);
            }
        });

    }


    /**
     * 初始化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;
            }
        }
    }

    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();
                tvContent.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) {
                tvContent.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) {
                tvContent.setVisibility(View.VISIBLE);
                latLatitude = mapStatus.bound.getCenter().latitude;
                lonLongitude = mapStatus.bound.getCenter().longitude;
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(mapStatus.bound.getCenter()));
            }
        });
    }


    /**
     * 动画平移
     */
    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);
    }

    /**
     * 设置搜索内容
     */
    private void setSearchContent(String city, String content) {
        /* 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新 */
        mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                .keyword(content)
                .city(city));
    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if (suggestionResult == null || suggestionResult.getAllSuggestions() == null) {
            return;
        }
        if (nowCity ==null){
            return;
        }

        if (isFirstLoc == false && !nowCity.equals(selectCity)) {
            isFirstLoc = true;
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(createMapStatusBuilder(suggestionResult.getAllSuggestions().get(0).pt).build()));
            return;
        }

        List<SearchBean> suggest = new ArrayList<>();
        for (SuggestionResult.SuggestionInfo info : suggestionResult.getAllSuggestions()) {
            if (info.key != null) {
                SearchBean searchBean = new SearchBean();
                searchBean.setLatLng(info.getPt());
                searchBean.setSearchName(info.key);
                searchBean.setSearchCity(info.getCity());
                suggest.add(searchBean);
            }
        }
        mFl.setVisibility(View.VISIBLE);
        searchAdapter.setNewData(suggest);
    }

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

    @OnClick({R2.id.ll_item_car_city})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_car_city) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_CITYLIST)
                    .withInt("mCityType", 1)
                    .withString("mNowCity", tvCity.getText().toString())
                    .withInt("mCityId", mCityId)
                    .navigation(mActivity, 113);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 113 && resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", 1);
            selectCity = data.getStringExtra("location");
            if (type == 1) {
                tvCity.setText(data.getStringExtra("location"));
                mCityId = data.getIntExtra("id", 0);
                latLatitude = 0.0;
                lonLongitude = 0.0;
                geoCoder.geocode(new GeoCodeOption()
                        .city(selectCity)
                        .address(selectCity));
            }
        }
    }

    private void initCity() {
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有检索到结果
                } else {
                    latLatitude = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(createMapStatusBuilder(new LatLng(latLatitude, lonLongitude)).build()));
                }
                //获取地理编码结果
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                } else {
                    latLatitude = result.getLocation().latitude;
                    lonLongitude = result.getLocation().longitude;
                }
            }
        });
    }

}
