package com.zj365.mime.act.electronicfence

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
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.CircleOptions
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.PoiItem
import com.xty.base.act.BaseVmAct
import com.xty.base.weight.TipDialog
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.BtFenceSettingSuccessEvent
import com.xty.network.model.EtFenceListBean
import com.zj365.mime.R
import com.zj365.mime.adapter.ElectronicFenceAdapter
import com.zj365.mime.databinding.ActivityElectronicFenceSettingBinding
import com.zj365.mime.vm.ElectronicFenceSettingVm
import org.greenrobot.eventbus.EventBus

@Route(path = ARouterUrl.ELECTRONIC_ADD_MODIFY_ACT)
class ElectronicAddOrModifyAct : BaseVmAct<ElectronicFenceSettingVm>()  {
    val binding by lazy { ActivityElectronicFenceSettingBinding.inflate(layoutInflater) }

    val mAdapter by lazy { ElectronicFenceAdapter() }

    var type: Int = 0 //0 列表页 1 设置页  2 修改已设计的电子围栏

    private var aMap: AMap? = null

    var poiItem: PoiItem? = null

    var settingType :Int =2 //	1-禁入 2-禁出

    var radius:Int = 500

    var title:String = ""

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

    var markerOptionsList = ArrayList<MarkerOptions>()

    var bean: EtFenceListBean.EtFenceChildBean? = null


    override fun liveObserver() {
        mViewModel.addOrDeleteLiveData.observe(this){
            EventBus.getDefault().post(BtFenceSettingSuccessEvent())
            finish()
        }
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "电子围栏设置"
        binding.title.mIvBack.setOnClickListener {
            finish()
        }
        aMap = binding.map.map

        initLocation()

        if (intent.hasExtra("type")){
            type = intent.getIntExtra("type",0)

        }

        if(intent.hasExtra("poiItem")){
            poiItem = intent.getParcelableExtra("poiItem")
        }

        if(intent.hasExtra("bean")){
            bean = intent.getParcelableExtra("bean")
        }

        if(type == 0){
            binding.llData.visibility = View.VISIBLE
            binding.llSetting.visibility = View.GONE

            mViewModel.getElectronicFenceList()
            binding.tvCancel.visibility = View.GONE
        }else if(type == 1){
            binding.llData.visibility = View.GONE
            binding.llSetting.visibility = View.VISIBLE
            binding.tvCancel.visibility = View.VISIBLE
            initSettingData()
        }else {
            binding.llData.visibility = View.GONE
            binding.llSetting.visibility = View.VISIBLE
            binding.tvCancel.visibility = View.VISIBLE
            binding.tvCancel.text = "删除"
            initModifyData()
        }

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

        binding.tvConfirm.setOnClickListener {
            if (type == 0){
                RouteManager.goAct(ARouterUrl.ELECTRONIC_ADDRESS_CHOOSE_ACT)

            }else if(type == 1){
                poiItem?.let {
                    mViewModel.setBtFence(title,radius,settingType,longitude,latitude,null)
                }
            }else if(type == 2){
                bean?.let {
                    mViewModel.setBtFence(title,radius,settingType,longitude,latitude,it.id)
                }
            }
        }

        binding.tvCancel.setOnClickListener {
            if(type == 2){
                TipDialog(this ,  "确定要删除该电子围栏",true ,"确认","取消") {
                    bean?.let {
                        mViewModel.deleteBtFence(it.id)
                    }
                }

            }else{
                finish()
            }

        }



        binding.clSetting.skbRadius.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                radius = p1
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
            }

        })

        binding.clSetting.rbType.setOnCheckedChangeListener { radioGroup, checkedId ->

            when(radioGroup.checkedRadioButtonId){
                R.id.rb_leave ->{
                    settingType = 2
                    aMap?.let {
                        it.clear()
                        var markerOptions = MarkerOptions().position(LatLng(latitude,longitude)).icon(
                            BitmapDescriptorFactory.fromView(View.inflate(this,
                                R.layout.layout_bt_fence_leave,null)))
                        var marker = it.addMarker(markerOptions)

                        it.addCircle(CircleOptions().center(LatLng(latitude,longitude))
                            .radius(radius.toDouble()).fillColor(Color.parseColor("#61FFAC53"))
                            .strokeColor(Color.parseColor("#FFFFFF"))
                            .strokeWidth(1.0f)
                        )
                    }

                }

                R.id.rb_enter ->{
                    settingType = 1

                    aMap?.let {
                        it.clear()
                        var markerOptions = MarkerOptions().position(LatLng(latitude,longitude)).icon(
                            BitmapDescriptorFactory.fromView(View.inflate(this,
                                R.layout.layout_bt_fence_enter,null)))
                        var marker = it.addMarker(markerOptions)

                        it.addCircle(CircleOptions().center(LatLng(latitude,longitude))
                            .radius(radius.toDouble()).fillColor(Color.parseColor("#66F04D42"))
                            .strokeColor(Color.parseColor("#FFFFFF"))
                            .strokeWidth(1.0f)
                        )
                    }

                }
            }

        }
    }

    fun initLocation(){
        var locationStyle = MyLocationStyle()
        locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        aMap?.let {
            it.clear()
            it.myLocationStyle = locationStyle
            it.uiSettings.isMyLocationButtonEnabled = false
            it.isMyLocationEnabled = false
            it.moveCamera(CameraUpdateFactory.zoomTo(20f))

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

    fun initModifyData(){
        bean?.let {
            title = "${it.title}"
            binding.clSetting.tvAddress.text = "${it.title}"
            latitude = it.lat
            longitude = it.log
            radius = it.radius
            settingType = it.type
            binding.clSetting.skbRadius.progress = radius
            if (settingType == 1){
                binding.clSetting.rbType.check(R.id.rb_enter)
            }else{
                binding.clSetting.rbType.check(R.id.rb_leave)

            }

        }

        aMap?.let {


            if(settingType == 1){
                var markerOptions = MarkerOptions().position(LatLng(latitude,longitude)).icon(
                    BitmapDescriptorFactory.fromView(View.inflate(this,
                        R.layout.layout_bt_fence_enter,null)))

                var marker = it.addMarker(markerOptions)
                it.addCircle(CircleOptions().center(LatLng(latitude,longitude))
                    .radius(radius.toDouble()).fillColor(Color.parseColor("#66F04D42"))
                    .strokeColor(Color.parseColor("#FFFFFF"))
                    .strokeWidth(1.0f)
                )
            }else{
                var markerOptions = MarkerOptions().position(LatLng(latitude,longitude)).icon(
                    BitmapDescriptorFactory.fromView(View.inflate(this,
                        R.layout.layout_bt_fence_leave,null)))

                var marker = it.addMarker(markerOptions)
                it.addCircle(CircleOptions().center(LatLng(latitude,longitude))
                    .radius(radius.toDouble()).fillColor(Color.parseColor("#61FFAC53"))
                    .strokeColor(Color.parseColor("#FFFFFF"))
                    .strokeWidth(1.0f))

            }

            it.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(latitude,longitude),14f,0f,0f)))
        }

    }

    fun initSettingData(){

        poiItem?.let {
            title = "${it.provinceName}${it.cityName}${it.adName}${it.title}"
            binding.clSetting.tvAddress.text = "${it.provinceName}${it.cityName}${it.adName}${it.title}"
            latitude = it.latLonPoint.latitude
            longitude = it.latLonPoint.longitude

        }

        binding.clSetting.skbRadius.progress = radius

        binding.clSetting.rbType.check(R.id.rb_leave)

        aMap?.let {
            var markerOptions = MarkerOptions().position(LatLng(latitude,longitude)).icon(
                BitmapDescriptorFactory.fromView(View.inflate(this,
                    R.layout.layout_bt_fence_leave,null)))
            var marker = it.addMarker(markerOptions)
            it.animateCamera(CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(latitude,longitude),15f,0f,0f)))

            it.addCircle(CircleOptions().center(LatLng(latitude,longitude))
                .radius(radius.toDouble()).fillColor(Color.parseColor("#61FFAC53"))
                .strokeColor(Color.parseColor("#FFFFFF"))
                .strokeWidth(1.0f)
            )

        }
    }

    override fun setLayout() = binding.root

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

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


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

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

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