package com.ewei.demo.otherui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.SnapshotReadyCallback;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
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.baidu.mapapi.search.core.PoiInfo;
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.ewei.demo.R;
import com.ewei.demo.otherui.adapter.LocationPoiListAdapter;
import com.ewei.sdk.base.BaseActivity;
import com.ewei.sdk.utility.PermissionUtils;
import com.ewei.sdk.utility.TempFileManager;
import com.ewei.sdk.utility.ToastUtils;

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

/**
 * Created by ypj.
 */
public class LocationActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener, BaiduMap.OnMapStatusChangeListener {

    private LinearLayout mLLBack;
    private TextView mTvTitle;
    private ImageView mIvSearch;
    private TextView mTvSend;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    private MyLocationListenner myListener = new MyLocationListenner();

    private LocationPoiListAdapter mPoiListAdapter;
    private ListView mPois;
    private ImageView mMyPos;

    private PoiInfo mPoiInfo = new PoiInfo();
    private String cityInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        PermissionUtils.checkLocationPermission(this);
        initControl();
    }

    private void initControl() {
        mLLBack = (LinearLayout) findViewById(R.id.ll_cmn_bss_back);
        mLLBack.setOnClickListener(this);

        mTvTitle = (TextView) findViewById(R.id.tv_cmn_bss_title);
        mTvTitle.setText("位置");

        mIvSearch = (ImageView) findViewById(R.id.iv_cmn_bss_search);
        mIvSearch.setOnClickListener(this);

        mTvSend = (TextView) findViewById(R.id.tv_cmn_bss_send);
        mTvSend.setOnClickListener(this);

        mPoiListAdapter = new LocationPoiListAdapter(this, null);
        mPois = (ListView) findViewById(R.id.lv_bdmap_pois);
        mPois.setAdapter(mPoiListAdapter);
        mPois.setOnItemClickListener(this);

        mMyPos = (ImageView) findViewById(R.id.iv_bdmap_mypos);
        mMyPos.setOnClickListener(this);

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.mv_bd_map);
        mBaiduMap = mMapView.getMap();

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapStatusChangeListener(this);

        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");  // 设置坐标系类型
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        option.disableCache(true);

        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_bdmap_mypos:
                mBaiduMap.clear();
                mBaiduMap.setMyLocationEnabled(true);
                mLocClient.requestLocation();
                break;
            case R.id.ll_cmn_bss_back:
                LocationActivity.this.finish();
                break;
            case R.id.iv_cmn_bss_search:
                Intent intent = new Intent(this, LocationSearchActivity.class);
                intent.putExtra("city", cityInfo);
                startActivityForResult(intent, 0);
                break;
            case R.id.tv_cmn_bss_send:
                PoiInfo pi = mPoiListAdapter.getDataSelected();
                if (pi != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("poiinfo", pi);
                    getIntent().putExtras(bundle);
                    getMapSnapshot();
                } else {
                    ToastUtils.showToast("请选定一个地址");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                Bundle bundle = data.getExtras();
                mPoiInfo = bundle.getParcelable("poiinfo");

                mBaiduMap.setMyLocationEnabled(false);
                markLocation(mPoiInfo.location);
                getPoiInfoList(mPoiInfo.location);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取定位截图
     */
    private void getMapSnapshot() {
        showLoadingDialog("保存位置截图中...");
        mBaiduMap.snapshot(new SnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(Bitmap bitmap) {
                hideLoadingDialog();
                String locPath = TempFileManager.saveMapFile(LocationActivity.this, bitmap);
                getIntent().putExtra("path", locPath);
                setResult(RESULT_OK, getIntent());
                finish();
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mPoiListAdapter.cleanSelects();
        mPoiListAdapter.setSelectIndex(position);

        PoiInfo pi = (PoiInfo) mPoiListAdapter.getItem(position);
        markLocation(pi.location);
    }

    /**
     * 标注位置
     *
     * @param ll
     */
    private void markLocation(LatLng ll) {
        mBaiduMap.clear();

        //设置标注为地图中心点
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.setMapStatus(msu);

        //添加标注图层
        BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.mipmap.position_search);
        OverlayOptions oo = new MarkerOptions().position(ll).icon(bd).animateType(MarkerOptions.MarkerAnimateType.grow);
        mBaiduMap.addOverlay(oo);
    }

    @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) {
        getPoiInfoList(mapStatus.target);
        markLocation(mapStatus.target);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())  //定位精度
                    .direction(100)
                    .longitude(location.getLongitude())
                    .latitude(location.getLatitude())
                    .build();
            mBaiduMap.setMyLocationData(locData);

            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()));

            cityInfo = location.getCity();

            getPoiInfoList(ll);
            markLocation(ll);

        }
    }

    private void getPoiInfoList(LatLng ll) {
        GeoCoder gc = GeoCoder.newInstance();
        gc.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

                List<PoiInfo> pis = new ArrayList<>();

                if (reverseGeoCodeResult.getPoiList() != null && reverseGeoCodeResult.getPoiList().size() > 0) {
                    pis.addAll(reverseGeoCodeResult.getPoiList());
                    mPois.smoothScrollToPosition(0);
                    mPoiListAdapter.removeAllData();
                    mPoiListAdapter.addListData(pis);
                    mPoiListAdapter.setSelectIndex(0);
                }
            }
        });
        gc.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        myListener = null;
        super.onDestroy();
    }
}
