package com.yidian.shenghuoquan.newscontent.ui.store

import android.content.Intent
import android.location.Location
import android.os.Bundle
import android.view.View
import com.amap.api.maps.AMap
import com.amap.api.maps.AMap.OnMyLocationChangeListener
import com.amap.api.maps.MapView
import com.amap.api.maps.model.*
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener
import com.yidian.common.base.BaseActivity
import com.yidian.common.extensions.initTitleBar
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.databinding.ActivitySelectAddressBinding
import com.yidian.shenghuoquan.newscontent.ui.store.adapter.PioListAdapter
import timber.log.Timber


/**
 * 选择门店地址
 */
class SelectAddressActivity : BaseActivity<ActivitySelectAddressBinding>(), OnMyLocationChangeListener, AMap.OnMapClickListener,
  OnPoiSearchListener {

  private lateinit var mapView: MapView
  private var adapter = PioListAdapter()
  private var resultIntent = Intent()
  private var data: List<PoiItem>? = null
  private var myLocationStyle: MyLocationStyle? = null
  private var bitmapDescriptor: BitmapDescriptor? = null
  private var markerView: View? = null
  private var currentMarker: Marker? = null
  private var boundsBuilder: LatLngBounds.Builder? = null
  private var aMap: AMap? = null

  override fun createViewBinding(): ActivitySelectAddressBinding {
    return ActivitySelectAddressBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return ""
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initTitleBar(viewBind.include.toolbar, viewBind.include.tvTitle, "选择门店地址")
    initAmap(savedInstanceState)
    initList()
    initClick()
  }

  private fun initAmap(savedInstanceState: Bundle?) {
    mapView = viewBind.map
    mapView.onCreate(savedInstanceState)
    markerView = layoutInflater.inflate(R.layout.layout_service_addr_map_marker, null)
    bitmapDescriptor = BitmapDescriptorFactory.fromView(markerView)
    boundsBuilder = LatLngBounds.Builder()
    if (aMap == null) {
      aMap = mapView.map
      setUpMap()
    }
    //设置SDK 自带定位消息监听
    aMap?.setOnMyLocationChangeListener(this)
    aMap?.myLocationStyle = myLocationStyle?.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
  }

  private fun initList() {
    viewBind.poiList.adapter = adapter
    adapter.setOnItemClickListener { _, _, position ->
      data?.let {
        resultIntent.putExtra("title", it[position].title)
        resultIntent.putExtra("cityName", it[position].cityName)
        resultIntent.putExtra("adName", it[position].adName)
        resultIntent.putExtra("latitude", it[position].latLonPoint.latitude.toString())
        resultIntent.putExtra("longitude", it[position].latLonPoint.longitude.toString())
        setResult(200, resultIntent)
        finish()
      }
    }
  }

  private fun initClick() {
    viewBind.selectAddSearchText.setOnClickListener {
      startActivityForResult(Intent(this@SelectAddressActivity, SearchAddActivity::class.java), 100)
    }
  }

  override fun onPause() {
    super.onPause()
    viewBind.map.onPause()
  }

  override fun onResume() {
    super.onResume()
    viewBind.map.onResume()
  }

  override fun onDestroy() {
    super.onDestroy()
    viewBind.map.onDestroy();
  }

  override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    viewBind.map.onSaveInstanceState(outState)
  }

  /**
   * 设置一些amap的属性
   */
  private fun setUpMap() {
    // 如果要设置定位的默认状态，可以在此处进行设置
    myLocationStyle = MyLocationStyle()
    aMap?.myLocationStyle = myLocationStyle
    aMap?.isMyLocationEnabled = true // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    aMap?.setOnMapClickListener(this) // 设置点击marker事件监听器
  }

  //定位
  override fun onMyLocationChange(location: Location?) {
    // 定位回调监听
    if (location != null) {
      Timber.tag("amap").e("onMyLocationChange 定位成功， lat: " + location.latitude + " lon: " + location.longitude)
      val bundle: Bundle = location.extras
      val errorCode = bundle.getInt(MyLocationStyle.ERROR_CODE)
      val errorInfo = bundle.getString(MyLocationStyle.ERROR_INFO)
      // 定位类型，可能为GPS WIFI等，具体可以参考官网的定位SDK介绍
      val locationType = bundle.getInt(MyLocationStyle.LOCATION_TYPE)


      aMap?.isMyLocationEnabled = false // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

      updateCurrentMarker(LatLng(location.latitude, location.longitude))

      Timber.tag("amap").e("定位信息， code: $errorCode errorInfo: $errorInfo locationType: $locationType")
    } else {
      Timber.tag("amap").e("定位失败")
    }
  }

  //点击
  override fun onMapClick(latLng: LatLng?) {
    updateCurrentMarker(latLng)
  }

  //更新当前坐标
  private fun updateCurrentMarker(latLng: LatLng?) {
    val markerOption = MarkerOptions()
    markerOption.position(latLng)
    markerOption.icon(bitmapDescriptor)
    markerOption.anchor(0F, 1F)
    currentMarker?.remove()
    currentMarker = aMap?.addMarker(markerOption)
    currentMarker?.setObject(latLng)
    boundsBuilder?.include(latLng)
    queryPoi()
  }

  //poi搜索
  private fun queryPoi() {
    val latLng = currentMarker?.getObject() as LatLng
    val typeRange = "汽车服务|汽车销售|" +
      "汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|" +
      "住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|" +
      "金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施"

    val query: PoiSearch.Query = PoiSearch.Query("", typeRange, "")
    query.pageSize = 1000 // 设置每页最多返回多少条poiitem，一次加载全部
    query.pageNum = 1 //设置查第一页
    val poiSearch = PoiSearch(this, query)
    poiSearch.bound = PoiSearch.SearchBound(
      LatLonPoint(
        latLng.latitude,
        latLng.longitude
      ), 500
    ) //设置周边搜索的中心点以及区域

    poiSearch.setOnPoiSearchListener(this) //设置数据返回的监听器
    poiSearch.searchPOIAsyn()
  }

  //poi搜索结束
  override fun onPoiSearched(poiResult: PoiResult?, rCode: Int) {
    if (rCode == AMapException.CODE_AMAP_SUCCESS) {
      if (poiResult?.query != null) {
        val poiItems: List<PoiItem> = poiResult.pois // 取得第一页的poiitem数据，页数从数字0开始
        if (poiItems.isNotEmpty()) {
          data = poiItems
          adapter.setList(poiItems)
        }
      }
    }
  }

  override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == 100) {
      setResult(200, data)
      finish()
    }
  }

}
