package com.casic.electric.detector.view

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.view.KeyEvent
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.CoordinateConverter
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MyLocationStyle
import com.casic.electric.detector.R
import com.casic.electric.detector.bean.LabelBean
import com.casic.electric.detector.bean.SmallLabelBean
import com.casic.electric.detector.bean.TaskBean
import com.casic.electric.detector.callback.ILocationListener
import com.casic.electric.detector.cluster.ClusterItem
import com.casic.electric.detector.cluster.ClusterOverlay
import com.casic.electric.detector.cluster.RegionItem
import com.casic.electric.detector.extensions.appendExcelDownloadUrl
import com.casic.electric.detector.extensions.drawCircle
import com.casic.electric.detector.extensions.initLayoutImmersionBar
import com.casic.electric.detector.utils.DataBaseManager
import com.casic.electric.detector.utils.ExcelHub
import com.casic.electric.detector.utils.LoadingDialogHub
import com.casic.electric.detector.utils.LocaleConstant
import com.casic.electric.detector.utils.LocationHub
import com.casic.electric.detector.utils.RouteOnMap
import com.casic.electric.detector.vm.TaskViewModel
import com.casic.electric.detector.widgets.QueryMarkerDialog
import com.casic.electric.detector.widgets.SamplePopupWindow
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.callback.OnDownloadListener
import com.pengxh.kt.lite.extensions.createDownloadFileDir
import com.pengxh.kt.lite.extensions.downloadFile
import com.pengxh.kt.lite.extensions.dp2px
import com.pengxh.kt.lite.extensions.isNetworkConnected
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.extensions.toJson
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import com.pengxh.kt.lite.widget.dialog.NoNetworkDialog
import kotlinx.android.synthetic.main.activity_main.aimButton
import kotlinx.android.synthetic.main.activity_main.currentLocationView
import kotlinx.android.synthetic.main.activity_main.detectionButton
import kotlinx.android.synthetic.main.activity_main.inspectionButton
import kotlinx.android.synthetic.main.activity_main.installButton
import kotlinx.android.synthetic.main.activity_main.mapView
import kotlinx.android.synthetic.main.activity_main.rightImageView
import kotlinx.android.synthetic.main.activity_main.rootView
import kotlinx.android.synthetic.main.activity_main.viewButton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class MainActivity : KotlinBaseActivity() {

    private val kTag = "MainActivity"
    private val context: Context = this@MainActivity
    private val samplePopupWindow by lazy { SamplePopupWindow(this) }
    private var clickTime: Long = 0
    private lateinit var wakeLock: PowerManager.WakeLock
    private lateinit var aMap: AMap
    private lateinit var taskViewModel: TaskViewModel
    private lateinit var taskBean: TaskBean
    private var latitude: Double = 0.0
    private var longitude: Double = 0.0
    private var labels = ArrayList<LabelBean>()
    private var smallLabels = ArrayList<SmallLabelBean>()
    private var clusterOverlay: ClusterOverlay? = null
    private val backDrawables = HashMap<Int, Drawable>()
    private val regionRadius by lazy { LocaleConstant.RADIUS_SIZE.dp2px(this) }

    override fun initLayoutView(): Int = R.layout.activity_main

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(false).statusBarColor(R.color.themeColor).init()
        initLayoutImmersionBar(rootView)
    }

    override fun observeRequestState() {

    }

    override fun initData(savedInstanceState: Bundle?) {
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = powerManager.run {
            newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this@MainActivity.localClassName).apply {
                acquire(60 * 60 * 1000L)
            }
        }

        initMapConfig(savedInstanceState)

        samplePopupWindow.setPopupMenuItem(LocaleConstant.POPUP_TITLES)
        samplePopupWindow.setBackgroundDrawable(null)

        taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
        taskViewModel.markerFileResult.observe(this) {
            if (it.success == "true") {
                //清空之前的数据
                DataBaseManager.get.clearLabels()
                DataBaseManager.get.clearSmallLabels()
                /**
                 * "data":"/xls/marker1.xls,/xls/smallMarker1.xls"
                 * 有两份excel表格需要下载
                 * */
                if (it.data.contains(",")) {
                    val urlArray = it.data.split(",")

                    val labelDownloadUrl = urlArray[0].appendExcelDownloadUrl()
                    val smallLabelDownloadUrl = urlArray[1].appendExcelDownloadUrl()

                    //下载标识器
                    labelDownloadUrl.downloadFile(
                        createDownloadFileDir().toString(), object : OnDownloadListener {
                            override fun onDownloadEnd(file: File?) {
                                lifecycleScope.launch {
                                    labels = ExcelHub.readLabel(file?.absolutePath)
                                    withContext(Dispatchers.IO) {
                                        labels.forEach { label ->
                                            DataBaseManager.get.insertLabel(label)
                                        }
                                    }
                                    LoadingDialogHub.dismiss()
                                    showLabelsOnMap()
                                }
                            }

                            override fun onDownloadStart(totalBytes: Long) {

                            }

                            override fun onProgressChanged(currentBytes: Long) {

                            }
                        })

                    //下载附属标识器
                    smallLabelDownloadUrl.downloadFile(
                        createDownloadFileDir().toString(), object : OnDownloadListener {
                            override fun onDownloadEnd(file: File?) {
                                lifecycleScope.launch {
                                    smallLabels = ExcelHub.readSmallLabel(file?.absolutePath)
                                    withContext(Dispatchers.IO) {
                                        smallLabels.forEach { label ->
                                            DataBaseManager.get.insertSmallLabel(label)
                                        }
                                    }
                                }
                            }

                            override fun onDownloadStart(totalBytes: Long) {

                            }

                            override fun onProgressChanged(currentBytes: Long) {

                            }
                        })
                }
            }
        }
//        taskViewModel.taskResult.observe(this) {
//            if (it.success == "true") {
//                //清空之前的数据
//                DataBaseManager.get.clearTasks()
//                AlertMessageDialog.Builder()
//                    .setContext(this)
//                    .setTitle("温馨提示")
//                    .setMessage("您有${it.message.size}个新任务！")
//                    .setPositiveButton("知道了")
//                    .setOnDialogButtonClickListener(object :
//                        AlertMessageDialog.OnDialogButtonClickListener {
//                        override fun onConfirmClick() {
//                            saveTaskInformation(it)
//                        }
//                    }).build().show()
//            }
//        }
    }

    override fun initEvent() {
        rightImageView.setOnClickListener {
            CoroutineScope(Dispatchers.Main).launch {
                val labels = withContext(Dispatchers.IO) {
                    DataBaseManager.get.queryLabelById("0")
                }
                if (labels.isNotEmpty()) {
                    samplePopupWindow.setShowPosition(4)
                }
                val x = rightImageView.width - samplePopupWindow.width - 1f.dp2px(context)
                samplePopupWindow.showAsDropDown(rightImageView, x, 1f.dp2px(context))
            }
        }

        samplePopupWindow.setOnPopupWindowClickListener(object :
            SamplePopupWindow.OnPopupWindowClickListener {
            override fun onPopupItemClicked(position: Int) {
                when (position) {
                    0 -> updateLabels()
//                    1 -> downloadTask()
                    2 -> navigatePageTo<VersionControlActivity>()
//                    3 -> uploadEvent()
//                    4 -> uploadLabel()
                }
            }
        })

        //安装。上传，然后存入本地库
        installButton.setOnClickListener {
            AlertControlDialog.Builder()
                .setContext(context)
                .setTitle("提示")
                .setMessage("请选择安装对象")
                .setPositiveButton("标识器")
                .setNegativeButton("电子标签")
                .setOnDialogButtonClickListener(object :
                    AlertControlDialog.OnDialogButtonClickListener {
                    override fun onConfirmClick() {
                        //标识器
                        navigatePageTo<InstallLabelActivity>()
                    }

                    override fun onCancelClick() {
                        //电子标签
                        navigatePageTo<InstallSmallLabelActivity>()
                    }
                }).build().show()
        }

        //查看
        viewButton.setOnClickListener {
            QueryMarkerDialog.Builder()
                .setContext(this)
                .setTitle("查看标识器")
                .setConditionArray(LocaleConstant.CONDITION_ARRAY)
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(object :
                    QueryMarkerDialog.OnDialogButtonClickListener {
                    override fun onConfirmClick(
                        selectedCondition: String, vararg contentValue: String
                    ) {
                        //查询数据库
                        lifecycleScope.launch {
                            labels = withContext(Dispatchers.IO) {
                                if (contentValue.size == 1) {
                                    DataBaseManager.get.loadLabelByCondition(
                                        selectedCondition, contentValue[0]
                                    ) as ArrayList<LabelBean>
                                } else {
                                    DataBaseManager.get.loadLabelByDate(
                                        contentValue[0], contentValue[1]
                                    ) as ArrayList<LabelBean>
                                }
                            }

                            val latitudeList = ArrayList<Double>()
                            val longitudeList = ArrayList<Double>()

                            labels.forEach {
                                val latitude = it.latitude
                                val longitude = it.longitude
                                if (latitude.isNotBlank() && longitude.isNotBlank()) {
                                    if (CoordinateConverter.isAMapDataAvailable(
                                            latitude.toDouble(), longitude.toDouble()
                                        )
                                    ) {
                                        //分别缓存经、纬度
                                        latitudeList.add(latitude.toDouble())
                                        longitudeList.add(longitude.toDouble())
                                    }
                                }
                            }

                            if (latitudeList.isNotEmpty() && longitudeList.isNotEmpty()) {
                                //移动地图到所有labelBeans的第一个点
                                val center = LatLng(latitudeList.first(), longitudeList.first())
                                //移动到指定经纬度
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 16f))
                            }

                            showLabelsOnMap()
                        }
                    }

                    override fun onCancelClick() {

                    }
                }).build().show()
        }

        //巡检
        inspectionButton.setOnClickListener {
//            val task = DataBaseManager.get.queryDistinctTask()
//            if (task.isNotEmpty()) {
//                val arrayList = ArrayList<String>()
//                task.forEachIndexed { index, taskBean ->
//                    arrayList.add("任务${index + 1}：${taskBean.taskId}，${taskBean.desc}")
//                }
//
//                BottomActionSheet.Builder()
//                    .setContext(this)
//                    .setItemTextColor(Color.BLUE)
//                    .setActionItemTitle(arrayList)
//                    .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
//                        override fun onActionItemClick(position: Int) {
//                            val taskBean = task[position]
//                            SaveKeyValues.putValue(LocaleConstant.TASK_ID, taskBean.taskId)
//                            AlertControlDialog.Builder()
//                                .setContext(context)
//                                .setTitle("提示")
//                                .setMessage("请选择操作方式")
//                                .setPositiveButton("执行工单")
//                                .setNegativeButton("提交工单")
//                                .setOnDialogButtonClickListener(object :
//                                    AlertControlDialog.OnDialogButtonClickListener {
//                                    override fun onConfirmClick() {
//                                        detectRedrawGraphic(taskBean.taskId)
//                                        aMap.moveCamera(
//                                            CameraUpdateFactory.newLatLngZoom(
//                                                LatLng(
//                                                    taskBean.lat.toDouble(), taskBean.lng.toDouble()
//                                                ), 15f
//                                            )
//                                        )
//                                        uploadTask(taskBean.taskId, "1")
//                                    }
//
//                                    override fun onCancelClick() {
//                                        uploadTask(taskBean.taskId, "2")
//                                    }
//                                }).build().show()
//                        }
//                    }).build().show()
//            } else {
//                AlertMessageDialog.Builder()
//                    .setContext(this)
//                    .setTitle("温馨提示")
//                    .setMessage("现有任务已完成，请点击右上角菜单按钮下载新工单！")
//                    .setPositiveButton("知道了")
//                    .setOnDialogButtonClickListener(object :
//                        AlertMessageDialog.OnDialogButtonClickListener {
//                        override fun onConfirmClick() {
//
//                        }
//                    }).build().show()
//            }
        }

        //探测
        detectionButton.setOnClickListener {
//            navigatePageTo<SearchLabelActivity>()
        }
    }

    private fun initMapConfig(savedInstanceState: Bundle?) {
        mapView.onCreate(savedInstanceState)
        aMap = mapView.map

        val uiSettings = aMap.uiSettings
        uiSettings.isCompassEnabled = true
        uiSettings.isMyLocationButtonEnabled = false//不显示默认定位按钮
        uiSettings.isScaleControlsEnabled = true
        uiSettings.zoomPosition = AMapOptions.ZOOM_POSITION_RIGHT_CENTER
        uiSettings.isRotateGesturesEnabled = false//不许地图随手势旋转角度
        //显示定位小蓝点
        val locationStyle = MyLocationStyle()
        locationStyle.interval(2000)
        locationStyle.radiusFillColor(Color.argb(0, 0, 0, 0))
        locationStyle.strokeColor(Color.argb(0, 0, 0, 0))
        locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)//定位、但不会移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        aMap.myLocationStyle = locationStyle//设置定位蓝点的Style
        aMap.isMyLocationEnabled = true//设置是否显示定位小蓝点
        aMap.setOnMyLocationChangeListener {
            longitude = it.longitude
            latitude = it.latitude
            //经纬度逆编码
            LocationHub.antiCodingLocation(context, it) { address ->
                currentLocationView.text = address
            }
        }

        //首次移动到定位点
        moveToCurrentLocation()

        aMap.setOnMapLongClickListener {
            lifecycleScope.launch {
                labels = withContext(Dispatchers.IO) {
                    DataBaseManager.get.loadLabels() as ArrayList<LabelBean>
                }
                //显示标签
                showLabelsOnMap()
            }

            //虽然不用显示附属标签，但是需要和标签做到数据同步，所以标签重新加载数据时候附属标签也需要重新加载
            lifecycleScope.launch {
                smallLabels = withContext(Dispatchers.IO) {
                    DataBaseManager.get.loadSmallLabels() as ArrayList<SmallLabelBean>
                }
            }
        }

        //自定义定位按钮
        aimButton.setOnClickListener { moveToCurrentLocation() }
    }

    private fun moveToCurrentLocation() {
        LocationHub.getCurrentLocation(this, object : ILocationListener {
            override fun onAMapLocationGet(location: AMapLocation?) {
                if (location != null) {
                    aMap.moveCamera(
                        CameraUpdateFactory.newLatLngZoom(
                            LatLng(location.latitude, location.longitude), 16f
                        )
                    )
                } else {
                    "当前位置信号差，无法移动地图到定位点".show(context)
                }
            }
        })
    }

    //更新数据
    private fun updateLabels() {
        AlertControlDialog.Builder()
            .setContext(this)
            .setTitle("提示")
            .setMessage("是否更新数据？")
            .setNegativeButton("取消")
            .setPositiveButton("确定")
            .setOnDialogButtonClickListener(object :
                AlertControlDialog.OnDialogButtonClickListener {
                override fun onConfirmClick() {
                    if (isNetworkConnected()) {
                        val userId = SaveKeyValues.getValue(LocaleConstant.USER_ID, "")
                        val companyId = SaveKeyValues.getValue(LocaleConstant.USER_COMPANY_ID, "")

                        LoadingDialogHub.show(this@MainActivity, "获取标识器信息中，请稍后")
                        //TODO 设计如此，都传companyId
                        taskViewModel.getMarkerFile(companyId.toString(), companyId.toString())
                    } else {
                        NoNetworkDialog.Builder()
                            .setContext(context)
                            .setOnDialogButtonClickListener(object :
                                NoNetworkDialog.OnDialogButtonClickListener {
                                override fun onButtonClick() {
                                    val intent = Intent(Settings.ACTION_SETTINGS)
                                    startActivity(intent)
                                }
                            }).build().show()
                    }
                }

                override fun onCancelClick() {

                }
            }).build().show()
    }

    private fun showLabelsOnMap() {
        clusterOverlay?.onDestroy()
        val clusterItems = ArrayList<ClusterItem>()
        labels.forEach {
            val latLng = LatLng(it.latitude.toDouble(), it.longitude.toDouble(), false)
            val regionItem = RegionItem(latLng, it.markerId.toString())
            clusterItems.add(regionItem)
        }

        clusterOverlay = ClusterOverlay(context, aMap, clusterItems, regionRadius)
        clusterOverlay?.setClusterRender { clusterNum ->
            val radius = 80f.dp2px(context)
            if (clusterNum == 0) {
                var bitmapDrawable = backDrawables[0]
                if (bitmapDrawable == null) {
                    bitmapDrawable = BitmapDrawable(
                        null, radius.drawCircle(Color.argb(159, 100, 149, 237))
                    )
                    backDrawables[0] = bitmapDrawable
                }
                bitmapDrawable
            }
            if (clusterNum == 1) {
                var bitmapDrawable = backDrawables[1]
                if (bitmapDrawable == null) {
                    bitmapDrawable = resources.getDrawable(R.mipmap.label)
                    backDrawables[1] = bitmapDrawable
                }
                bitmapDrawable
            } else if (clusterNum < 5) {
                var bitmapDrawable = backDrawables[2]
                if (bitmapDrawable == null) {
                    bitmapDrawable = BitmapDrawable(
                        null, radius.drawCircle(Color.argb(159, 100, 149, 237))
                    )
                    backDrawables[2] = bitmapDrawable
                }
                bitmapDrawable
            } else if (clusterNum < 10) {
                var bitmapDrawable = backDrawables[3]
                if (bitmapDrawable == null) {
                    bitmapDrawable = BitmapDrawable(
                        null, radius.drawCircle(Color.argb(199, 30, 144, 255))
                    )
                    backDrawables[3] = bitmapDrawable
                }
                bitmapDrawable
            } else {
                var bitmapDrawable = backDrawables[4]
                if (bitmapDrawable == null) {
                    bitmapDrawable = BitmapDrawable(
                        null, radius.drawCircle(Color.argb(235, 65, 105, 225))
                    )
                    backDrawables[4] = bitmapDrawable
                }
                bitmapDrawable
            }
        }
        clusterOverlay?.setOnClusterClickListener { _, items ->
            var item: RegionItem? = null
            val builder = LatLngBounds.Builder()
            for (clusterItem in items) {
                builder.include(clusterItem.position)
                item = clusterItem as RegionItem
            }

            if (item == null) {
                "标识器经纬度异常".show(context)
                return@setOnClusterClickListener
            }

            val latLng = LatLng(item.position.latitude, item.position.longitude)

            //移动视图
            val latLngBounds = builder.build()
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 0))

            BottomActionSheet.Builder()
                .setContext(this)
                .setItemTextColor(Color.BLUE)
                .setActionItemTitle(listOf("标识器信息", "附属电子标签信息", "到这里去"))
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        when (position) {
                            0 -> {
                                labels.forEach {
                                    if (it.markerId.toString() == item.tag) {
                                        navigatePageTo<ObjectDetailActivity>(it.toJson())
                                    }
                                }
                            }
                            1 -> {
                                val electricMarkers = ArrayList<String>()
                                smallLabels.forEach {
                                    if (it.markerId.toString() == item.tag) {
                                        electricMarkers.add(it.electricMarkerId)
                                    }
                                }

                                if (electricMarkers.isEmpty()) {
                                    "此标识器没有绑定的电子标签".show(context)
                                    return
                                }

                                //显示单选列表对话框
                                showElectricMarkers(electricMarkers)
                            }
                            2 -> {
                                RouteOnMap.startNavigation(
                                    context, item.tag,
                                    LatLng(item.position.latitude, item.position.longitude)
                                )
                            }
                        }
                    }
                }).build().show()
        }
    }

    private fun showElectricMarkers(markers: ArrayList<String>) {
        AlertDialog.Builder(context)
            .setIcon(R.mipmap.ic_launcher)
            .setTitle("电子标签列表")
            .setSingleChoiceItems(markers.toTypedArray(), -1) { _, which ->
                navigatePageTo<ElectricMarkerDetailActivity>(markers[which])
            }.show()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - clickTime > 2000) {
                "再按一次退出程序".show(this)
                clickTime = System.currentTimeMillis()
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        } else super.onKeyDown(keyCode, event)
    }

    /***以下是地图生命周期管理************************************************************************/

    override fun onResume() {
        super.onResume()
        mapView.onResume()
        lifecycleScope.launch {
            labels = withContext(Dispatchers.IO) {
                DataBaseManager.get.loadLabels() as ArrayList<LabelBean>
            }
            //显示标签
            showLabelsOnMap()
        }

        //虽然不用显示附属标签，但是需要喝标签做到数据同步，所以标签重新加载数据时候附属标签也需要重新加载
        lifecycleScope.launch {
            smallLabels = withContext(Dispatchers.IO) {
                DataBaseManager.get.loadSmallLabels() as ArrayList<SmallLabelBean>
            }
        }
    }

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

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

    override fun onDestroy() {
        wakeLock.release()
        super.onDestroy()
        mapView.onDestroy()
    }
}