package com.casic.detector.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.amap.api.location.AMapLocation
import com.casic.detector.adapter.EditableImageAdapter
import com.casic.detector.callback.ILocationListener
import com.casic.detector.callback.OnImageCompressListener
import com.casic.detector.databinding.ActivityUploadEventBinding
import com.casic.detector.extensions.compressImage
import com.casic.detector.model.EventModel
import com.casic.detector.utils.LocaleConstant
import com.casic.detector.utils.LocationHub
import com.casic.detector.vm.TaskViewModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.*
import com.pengxh.kt.lite.utils.LoadState
import com.pengxh.kt.lite.utils.LoadingDialogHub
import com.pengxh.kt.lite.utils.SaveKeyValues
import java.io.File

@SuppressLint("SetTextI18n")
class UploadEventActivity : KotlinBaseActivity<ActivityUploadEventBinding>() {

    private val context: Context = this@UploadEventActivity
    private val locationHub by lazy { LocationHub(this) }
    private lateinit var imageAdapter: EditableImageAdapter
    private val realPaths: ArrayList<String> = ArrayList() //真实图片路径
    private lateinit var taskViewModel: TaskViewModel
    private lateinit var taskId: String

    override fun initViewBinding(): ActivityUploadEventBinding {
        return ActivityUploadEventBinding.inflate(layoutInflater)
    }

    override fun setupTopBarLayout() {

    }

    override fun observeRequestState() {
        taskViewModel.loadState.observe(this) {
            when (it) {
                LoadState.Loading -> LoadingDialogHub.show(this, "事件上报中，请稍后...")
                LoadState.Success -> {
                    LoadingDialogHub.dismiss()
                    "事件上报成功！".show(this)
                    finish()
                }

                else -> LoadingDialogHub.dismiss()
            }
        }
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.decorView.setBackgroundColor(Color.TRANSPARENT)
        window.setGravity(Gravity.CENTER)
        val params = window.attributes
        params.width = ((getScreenWidth() * 0.9).toInt())
        params.height = ((getScreenHeight() * 0.8).toInt())
        window.attributes = params

        taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]

        taskId = SaveKeyValues.getValue(LocaleConstant.TASK_ID, "") as String
        val userName = SaveKeyValues.getValue(LocaleConstant.USER_NAME, "") as String
        binding.userNameView.text = userName

        binding.uploadTimeView.text = System.currentTimeMillis().timestampToCompleteDate()

        locationHub.getCurrentLocation(true, object : ILocationListener {
            override fun onAMapLocationGet(location: AMapLocation?) {
                if (location != null) {
                    binding.lngView.text = "${location.longitude}"
                    binding.latView.text = "${location.latitude}"
                } else {
                    "当前位置信号差，无法获取定位".show(context)
                }
            }
        })

        imageAdapter = EditableImageAdapter(this, 3, 3)
        binding.cameraInclude.addImageRecyclerView.adapter = imageAdapter
    }

    override fun initEvent() {
        imageAdapter.setOnItemClickListener(object : EditableImageAdapter.OnItemClickListener {
            override fun onAddImageClick() {
                takePicture()
            }

            override fun onItemClick(position: Int) {
                if (realPaths[position].isEmpty()) {
                    "图片加载失败，无法查看大图".show(context)
                } else {
                    context.navigatePageTo<BigImageActivity>(position, realPaths)
                }
            }

            override fun onItemLongClick(view: View?, position: Int) {
                imageAdapter.deleteImage(position)
            }
        })

        binding.cancelButton.setOnClickListener { finish() }

        binding.uploadEventButton.setOnClickListener {
            if (binding.eventDescriptionView.text.isNullOrBlank()) {
                "请输入事件描述！".show(this)
                return@setOnClickListener
            }

            val eventModel = EventModel()
            eventModel.description = binding.eventDescriptionView.text.toString()
            eventModel.createTime = binding.uploadTimeView.text.toString()

            eventModel.latitude = binding.lngView.text.toString().toDouble()
            eventModel.longitude = binding.latView.text.toString().toDouble()

            taskViewModel.uploadEvent(taskId, eventModel.toJson(), realPaths)
        }
    }

    private fun takePicture() {
        PictureSelector.create(this).openCamera(SelectMimeType.ofImage())
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia>?) {
                    if (result == null) {
                        "拍照失败，请重试".show(context)
                        return
                    }
                    analyticalSelectResults(result[0])
                }

                override fun onCancel() {

                }
            })
    }

    private fun analyticalSelectResults(result: LocalMedia) {
        //压缩图片
        result.realPath.compressImage(this, object : OnImageCompressListener {
            override fun onSuccess(file: File) {
                realPaths.add(file.absolutePath)
                imageAdapter.setupImage(realPaths)
            }

            override fun onError(e: Throwable) {
                e.printStackTrace()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        locationHub.stopLocation()
    }
}