package com.zj365.mime.act.electronicfence

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.text.method.KeyListener
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.core.PoiItemV2
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiResultV2
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.poisearch.PoiSearchV2
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseVmAct
import com.xty.base.vm.BaseVm
import com.xty.common.LogUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.BtFenceSettingSuccessEvent
import com.xty.common.util.CommonToastUtils
import com.zj365.mime.R
import com.zj365.mime.adapter.ElectronicAddressAdapter
import com.zj365.mime.databinding.ActElectronicAddressChooseBinding
import com.zj365.mime.model.CustomerPOItem
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ELECTRONIC_ADDRESS_CHOOSE_ACT)
class ElectronicAddressChooseAct : BaseVmAct<BaseVm>(),AMapLocationListener ,GeocodeSearch.OnGeocodeSearchListener
    ,PoiSearch.OnPoiSearchListener{
    val binding by lazy { ActElectronicAddressChooseBinding.inflate(layoutInflater) }

    private var aMap: AMap? = null

    var mLocationClient:AMapLocationClient? = null
    var mLocationOption:AMapLocationClientOption? = null

    var geocodeSearch: GeocodeSearch? = null

    val mAdapter by lazy { ElectronicAddressAdapter() }

    var searchAddress:String = ""

    var latitude:Double=0.00
    var longitude:Double = 0.00

    var cityName :String = ""
    var poiList = ArrayList<CustomerPOItem>()

    var choosePoiItem: PoiItem? = null

    var isHandDrag:Boolean = false

    var page:Int = 1


    override fun liveObserver() {

    }

    override fun initView() {
        super.initView()

        binding.tvCancel.setOnClickListener {
            finish()
        }

        binding.tvConfirm.setOnClickListener {
            choosePoiItem?.let {
                bundle.clear()
                bundle.putParcelable("poiItem",it)
                bundle.putInt("type",1)
                RouteManager.goAct(ARouterUrl.ELECTRONIC_ADD_MODIFY_ACT,bundle)
            }
        }

        aMap = binding.mapView.map
        initLocation()

        binding.recycler.adapter = mAdapter
        binding.recycler.layoutManager = LinearLayoutManager(this)

        binding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(p0: TextView?, p1: Int, p2: KeyEvent?): Boolean {
                if(p1 == EditorInfo.IME_ACTION_SEARCH){
                    searchAddress =  binding.etSearch.text.toString()
                    page = 1
                    searchPOI()
                    RxKeyboardTool.hideSoftInput(this@ElectronicAddressChooseAct)
                    return true

                }
                return false
            }

        })

        mAdapter.setOnItemClickListener { adapter, view, position ->
            var bean = adapter.data[position] as CustomerPOItem
            (adapter.data as ArrayList<CustomerPOItem>).forEachIndexed { index, customerPOItem ->
                customerPOItem.isChecked = false
            }

            bean.isChecked = true
            choosePoiItem = bean.poiItem
            mAdapter.notifyDataSetChanged()
        }

        binding.mRefresh.setOnRefreshListener {
            page = 1
            searchPOI()
            binding.mRefresh.finishRefresh(1000)
        }
        binding.mRefresh.setEnableLoadMore(true)
        binding.mRefresh.setOnLoadMoreListener {
            page++
            searchPOI()
            binding.mRefresh.finishLoadMore(1000)
        }
    }

    fun searchPOI(){
        LogUtils.e("ElectronicAddressChooseAct","keyword${searchAddress}")
        var query = PoiSearch.Query(searchAddress,"",cityName)
        query.pageNum = page
        query.pageSize = 20

        var poisearch = PoiSearch(this,query)
        poisearch.bound = PoiSearch.SearchBound(LatLonPoint(latitude,longitude),50000)
        poisearch.setOnPoiSearchListener(this)
        poisearch.searchPOIAsyn()
    }


    fun initLocation(){
        var locationStyle = MyLocationStyle()
        locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        aMap?.let {
            it.myLocationStyle = locationStyle
            it.uiSettings.isMyLocationButtonEnabled = false
            it.isMyLocationEnabled = false

            it.moveCamera(CameraUpdateFactory.zoomTo(30f))

            var uiSettings = it.uiSettings
            uiSettings.isZoomControlsEnabled = false
            uiSettings.isMyLocationButtonEnabled = false
            uiSettings.isScaleControlsEnabled = false
            uiSettings.logoPosition= AMapOptions.LOGO_MARGIN_LEFT

            goLocation()

            it.setOnCameraChangeListener(object :AMap.OnCameraChangeListener{
                override fun onCameraChange(p0: CameraPosition?) {

                }

                override fun onCameraChangeFinish(cameraPosition: CameraPosition) {
                    LogUtils.e("ElectronicAddressChooseAct","onCameraChangeFinish")
                    if(isHandDrag && TextUtils.isEmpty(searchAddress)){
                        getGeocodeSearch(cameraPosition.target)

                    }
                    isHandDrag = true
                }
            })
        }
    }

    fun goLocation(){
        mLocationClient = AMapLocationClient(this)
        mLocationOption = AMapLocationClientOption()
        mLocationClient?.setLocationListener(this)
        mLocationOption?.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
        mLocationOption?.setInterval(1000)
        mLocationOption?.setOnceLocation(false)
        mLocationOption?.setGpsFirst(true)
        mLocationOption?.setNeedAddress(true)
        mLocationOption?.setOnceLocationLatest(false)
        mLocationOption?.setSensorEnable(true)

        mLocationClient?.setLocationOption(mLocationOption)
        mLocationClient?.startLocation()

    }


    fun getGeocodeSearch(targe: LatLng){
        LogUtils.e("ElectronicAddressChooseAct","getGeocodeSearch ${targe.latitude},${targe.longitude},")

        if(geocodeSearch == null) {
            geocodeSearch = GeocodeSearch(this)
        }
        searchAddress = ""
        latitude = targe.latitude
        longitude = targe.longitude
        var query = RegeocodeQuery(LatLonPoint(targe.latitude,targe.longitude),5000f,GeocodeSearch.AMAP)
        geocodeSearch?.setOnGeocodeSearchListener(this)
        geocodeSearch?.getFromLocationAsyn(query)

    }

    fun setMapCenter(amapLocation:AMapLocation){
        aMap?.let {
            var locationMark = it.addMarker(MarkerOptions().position(LatLng(amapLocation.latitude,amapLocation.longitude)).icon(
                BitmapDescriptorFactory.fromResource(R.mipmap.icon_address_location)
            ))
            locationMark.setPositionByPixels(binding.mapView.width / 2,binding.mapView.height /2)
            it.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(amapLocation.latitude,amapLocation.longitude),30f,0f,0f)))
        }
    }

    override fun setLayout() = binding.root

    override fun onDestroy() {
        super.onDestroy()
        binding.mapView.onDestroy()
    }

    override fun onPause() {
        super.onPause()
        binding.mapView.onPause()
    }


    override fun onResume() {
        super.onResume()
        binding.mapView.onResume()
    }

    @SuppressLint("MissingSuperCall")
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapView.onSaveInstanceState(outState)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.mapView.onCreate(savedInstanceState)
    }

    override fun onLocationChanged(amapLocation: AMapLocation?) {
        LogUtils.e("ElectronicAddressChooseAct","onLocationChanged：${amapLocation?.errorCode!!}")
        amapLocation?.let {
            if (it.errorCode == AMapLocation.LOCATION_SUCCESS){
                mLocationClient?.stopLocation()
                mLocationClient?.onDestroy()

                setMapCenter(it)
                latitude = it.latitude
                longitude = it.longitude
                var latLng = LatLng(latitude,longitude)
                cityName =it.city


            }else{

            }
        }

    }

    override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult?, code: Int) {
        LogUtils.e("ElectronicAddressChooseAct","onRegeocodeSearched：${code}")

        if(code == 1000){
            if(regeocodeResult != null && regeocodeResult?.regeocodeAddress != null  && regeocodeResult?.regeocodeAddress?.formatAddress != null){
                var split = regeocodeResult!!.regeocodeAddress!!.province  +regeocodeResult!!.regeocodeAddress!!.city + regeocodeResult!!.regeocodeAddress!!.district + regeocodeResult!!.regeocodeAddress!!.township
                LogUtils.e("ElectronicAddressChooseAct","split:${split}")
                searchPOI()
            }
        }

    }

    override fun onGeocodeSearched(geocodeResult: GeocodeResult?, code: Int) {
        LogUtils.e("ElectronicAddressChooseAct","onGeocodeSearched：${code}")


    }
    override fun onPoiSearched(result: PoiResult?, code: Int) {
        if(code == 1000){
            if(result != null && result?.query != null){
                LogUtils.e("ElectronicAddressChooseAct","query${result!!.pois.size}")
                if(page == 1){
                    mAdapter.data.clear()
                    poiList.clear()
                    choosePoiItem = null
                    if (result!!.pois.size > 0){
                        aMap?.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(result!!.pois[0].latLonPoint.latitude,result!!.pois[0].latLonPoint.longitude),15f,0f,30f)))
                    }
                    result!!.pois.forEach {
                        poiList.add(CustomerPOItem(it,false))
                    }
                    mAdapter.setList(poiList)
                }else{
                    result!!.pois.forEach {
                        poiList.add(CustomerPOItem(it,false))
                    }
                    mAdapter.addData(poiList)
                }

            }
        }
    }

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun settingSuccess(event: BtFenceSettingSuccessEvent){
        this.finish()
    }
}