package com.abbidot.tracker.deprecated.ui.activity.profile

import android.content.Intent
import android.graphics.Point
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.commit
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.FencesBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityFencesAddBinding
import com.abbidot.tracker.ui.common.map.FencesMapCommon
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.FencesManageViewModel
import com.abbidot.tracker.vm.GeoCoderViewModel
import com.abbidot.tracker.vm.ScreenshotsViewModel
import com.abbidot.tracker.vm.UserProfileViewModel
import com.abbidot.tracker.widget.FencesPolygonView
import com.abbidot.tracker.widget.OnCircleViewScaleClickListener
import com.abbidot.tracker.widget.OnRectViewRotateScaleClickListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/***
 * 添加围栏
 */
class FencesAddActivity : BaseActivity<ActivityFencesAddBinding>(ActivityFencesAddBinding::inflate),
    FencesMapCommon.OnActivityCallBack, OnRectViewRotateScaleClickListener,
    OnCircleViewScaleClickListener {

    private val mFencesManageViewModel: FencesManageViewModel by viewModels()
    private val mScreenshotsViewModel: ScreenshotsViewModel by viewModels()
    private val mUserInfoViewModel: UserProfileViewModel by viewModels()
    private val mGeoCoderViewModel: GeoCoderViewModel by viewModels()

    var isEdit = false
    private lateinit var mDeviceId: String
    private var mFenceId = ""
    private var mDeviceServiceId = ""

    //围栏样式
    var mFenceShapeType = ConstantInt.CircleShapeType

    private lateinit var mFencesMapCommon: FencesMapCommon

    //圆形半径距离
    private var mCircleRadiusDistance = 0

    //矩形长距离
    private var mRectWidthDistance = 0

    //矩形宽距离
    private var mRectHeightDistance = 0


    override fun getTopBar() = mViewBinding.fencesAddBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_add_fences)

        isEdit = intent.extras!!.getBoolean(ConstantString.Edit, false)
        mDeviceId = intent.extras!!.getString(ConstantString.DeviceId, "")

        mFencesMapCommon = FencesMapCommon()

        mViewBinding.apply {

            val fragment = mFencesMapCommon.getMapFragment(
                mContext,
                searchBaiduMapResultsView,
                mapboxSearchResultsView,
                fencesAddSearchAddress,
                this@FencesAddActivity
            )
            supportFragmentManager.commit {
                add(R.id.fences_add_map_view, fragment)
            }

            setOnClickListenerViews(
                fencesSearchAddressBtn, addFencesOkBtn, root
            )
            radiogroupFencesShowShapeType.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    R.id.selector_fence_circle_shape -> {
                        if (mFenceShapeType == ConstantInt.CircleShapeType) return@setOnCheckedChangeListener
                        mFenceShapeType = ConstantInt.CircleShapeType
                    }

                    R.id.selector_fence_rectangle_shape -> {
                        if (mFenceShapeType == ConstantInt.RectangleShapeType) return@setOnCheckedChangeListener
                        mFenceShapeType = ConstantInt.RectangleShapeType
                    }
                }
                setFenceShape(mFenceShapeType)
                //延迟计算距离
                if ((mFenceShapeType == ConstantInt.CircleShapeType && mCircleRadiusDistance == 0) || (mFenceShapeType == ConstantInt.RectangleShapeType && mRectHeightDistance == 0 && mRectWidthDistance == 0)) {
                    mViewBinding.fencesAddMapRect.postDelayed(
                        {
                            mFencesMapCommon.refreshDistance()
                        }, 500
                    )
                } else {
                    showLoading(false)
                }
            }
            fencesAddMapRect.setOnRectViewRotateScaleClickListener(this@FencesAddActivity)

            fencesAddMapCircle.setOnCircleViewScaleClickListener(this@FencesAddActivity)


            //编辑
            if (isEdit) {
                setTopBarTitle(R.string.txt_edit_fences)
                mRightImageButton = addRightImageButton(R.drawable.ico_delete)
                setOnClickListenerViews(mRightImageButton)

                Util.getParcelableAdaptive(intent, ConstantString.Fence, FencesBean::class.java)
                    ?.run {
                        mFenceId = fenceId
                        mDeviceServiceId = deviceServiceId
                        addFencesAddress.text = address
                        addFencesNameEdit.setText(name)
                        addActivateFencesCheckbox.isChecked = isOn == 1
                        mFenceShapeType = fenceType
                        if (fenceType == ConstantInt.CircleShapeType) {
                            fencesAddMapRect.initDefaultWidthHeight()
                            selectorFenceCircleShape.isChecked = true
                            mCircleRadiusDistance = radius
                            mFencesMapCommon.setCenterLatLng(latitude, longitude, radius.toDouble())
                        } else {
                            fencesAddMapCircle.initDefaultRadius()
                            selectorFenceRectangleShape.isChecked = true
                            mRectWidthDistance = longDistance
                            mRectHeightDistance = shortDistance
                            mFencesMapCommon.let {
                                it.setCenterLatLng(latitudeCenter, longitudeCenter)
                                it.setRectABCDLatLng(
                                    mContext,
                                    longitudeA,
                                    latitudeA,
                                    longitudeB,
                                    latitudeB,
                                    longitudeC,
                                    latitudeC,
                                    longitudeD,
                                    latitudeD
                                )
                            }
                        }
                    }
            } else {
                fencesAddMapCircle.initDefaultRadius()
                fencesAddMapRect.initDefaultWidthHeight()
            }
            setFenceShape(mFenceShapeType)
        }
    }

    override fun liveDataObserve() {
        //上传图片
        mUserInfoViewModel.mUploadImageLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    saveFences(it.getOrNull()!!)
                }
            })
        }

        if (isEdit) {
            mFencesManageViewModel.mDeleteFenceLiveData.observe(this) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        successTips(R.string.txt_delete_success)
                    }
                })
            }
            mFencesManageViewModel.mUpdateFenceLiveData.observe(this) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        successTips(R.string.txt_fence_saved)
                    }
                })
            }

        } else {
            mFencesManageViewModel.mFencesAddLiveData.observe(this) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        successTips(R.string.txt_fence_saved)
                    }
                })
            }
        }

        //反地理编码
        mGeoCoderViewModel.mLatLonAddressLiveData.observe(this) {
            mViewBinding.addFencesAddress.apply {
                visibility = if (TextUtils.isEmpty(it)) {
                    View.INVISIBLE
                } else {
                    View.VISIBLE
                }
                text = it
            }
        }

        //截屏后压缩的图片路径
        mScreenshotsViewModel.mMapSnapshotPathLiveData.observe(this) {
            if (!TextUtils.isEmpty(it)) {
                mUserInfoViewModel.uploadImage(this, it)
            }
        }
    }

    /**
     * 设置显示哪种围栏样式
     */
    private fun setFenceShape(shapeType: Int) {
        showLoading(true)
        when (shapeType) {
            ConstantInt.CircleShapeType -> {
                mViewBinding.fencesAddMapCircle.visibility = View.VISIBLE
                mViewBinding.fencesAddMapRect.visibility = View.GONE
            }

            ConstantInt.RectangleShapeType -> {
                mViewBinding.fencesAddMapCircle.visibility = View.GONE
                mViewBinding.fencesAddMapRect.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 修改成功提示
     */
    private fun successTips(resStringId: Int) {
        XEventBus.post(EventName.UpdateData + "FencesActivity")
        XEventBus.post(EventName.UpdateData + "MapFences")
        XEventBus.post(EventName.UpdateData + "TrackerManageSetActivity")
        showToast(resStringId, isFinish = true)
    }

    /**
     * 获取圆形/矩形中心点
     */
    fun getCentrePoint() = if (mFenceShapeType == ConstantInt.CircleShapeType) {
        Point(
            mViewBinding.fencesAddMapCircle.getCircleCentrePoint()
        )
    } else {
        Point(
            mViewBinding.fencesAddMapRect.getRectCentrePoint()
        )
    }

    /**
     * 获取圆形直虚线的最后一个点
     */
    fun getCircleLineEndPoint() = mViewBinding.fencesAddMapCircle.getCircleLineEndPoint()

    /**
     * 获取矩形4个点的某一个点
     */
    fun getRectABCDPoint(wherePoint: Int) =
        mViewBinding.fencesAddMapRect.getRectABCDPoint(wherePoint)

    /**
     * 保存围栏
     */
    private fun saveSure() {
        val fenceName = mViewBinding.addFencesNameEdit.text.toString()
        val address = mViewBinding.addFencesAddress.text.toString()
        if (TextUtils.isEmpty(fenceName) || TextUtils.isEmpty(address)) {
            showToast(R.string.txt_not_null)
            return
        }

        val hideDelayMillis = 400L
        when (mFenceShapeType) {
            ConstantInt.CircleShapeType -> {
                mViewBinding.fencesAddMapCircle.apply {
                    //隐藏距离，不被截图
                    setShowHideDisDistance(false)
                    //截屏并上传图片
                    mFencesMapCommon.snapshotImage(
                        this@FencesAddActivity, mScreenshotsViewModel, this
                    )
                    postDelayed({
                        //几秒后开始显示，截屏成功
                        setShowHideDisDistance(true)
                    }, hideDelayMillis)
                }
            }

            ConstantInt.RectangleShapeType -> {
                mViewBinding.fencesAddMapRect.apply {
                    //隐藏距离，不被截图
                    setShowHideDisDistance(false)
                    //截屏并上传图片
                    mFencesMapCommon.snapshotImage(
                        this@FencesAddActivity, mScreenshotsViewModel, this
                    )
                    postDelayed({
                        //几秒后开始显示，截屏成功
                        setShowHideDisDistance(true)
                    }, hideDelayMillis)
                }

            }
        }
    }

    private fun saveFences(imageUrl: String) {
        val fenceName = mViewBinding.addFencesNameEdit.text.toString()
        val address = mViewBinding.addFencesAddress.text.toString()
        val isOn = if (mViewBinding.addActivateFencesCheckbox.isChecked) {
            1
        } else {
            0
        }

        val latLon = mFencesMapCommon.getCenterLatLng()
        val latitude = latLon[0]
        val longitude = latLon[1]
        if (mFenceShapeType == ConstantInt.CircleShapeType) {
            val radius = mCircleRadiusDistance
            LogUtil.d("最后的经纬度是,$latitude,$longitude")
            if (isEdit) {
                mFencesManageViewModel.updateCircleFence(
                    this, FencesBean()
                )
            } else {
                mFencesManageViewModel.addCircleFence(
                    this, FencesBean()
                )
            }
        } else {
            val latLonA = mFencesMapCommon.getRectABCDLatLng(FencesPolygonView.POINT_A)
            val latitudeA = latLonA[0]
            val longitudeA = latLonA[1]
            val latLonB = mFencesMapCommon.getRectABCDLatLng(FencesPolygonView.POINT_B)
            val latitudeB = latLonB[0]
            val longitudeB = latLonB[1]
            val latLonC = mFencesMapCommon.getRectABCDLatLng(FencesPolygonView.POINT_C)
            val latitudeC = latLonC[0]
            val longitudeC = latLonC[1]
            val latLonD = mFencesMapCommon.getRectABCDLatLng(FencesPolygonView.POINT_D)
            val latitudeD = latLonD[0]
            val longitudeD = latLonD[1]
            if (isEdit) {
                mFencesManageViewModel.updateRectFence(
                    this, FencesBean()
                )
            } else {
                mFencesManageViewModel.addRectFence(
                    this, FencesBean()
                )
            }
        }

    }

    /**
     * 删除围栏
     */
    private fun deleteFences() {
        ViewUtil.instance.showDialog(
            mContext, R.string.txt_delete_tips, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    mFencesManageViewModel.deleteFence(
                        this@FencesAddActivity, mFenceId, mDeviceServiceId, 1
                    )
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    override fun onClick(v: View?) {
        when (v!!) {
            mRightImageButton -> {
                deleteFences()
            }
            //点任意位置隐藏搜索结果
            mViewBinding.root -> {
                mFencesMapCommon.setSearchResultsViewGone()
            }

            mRightImageButton -> {
                startActivity(Intent(mContext, FencesAddActivity::class.java))
            }

            mViewBinding.fencesSearchAddressBtn -> {
                mFencesMapCommon.searchAddress(mViewBinding.fencesAddSearchAddress.text.toString())
            }

            mViewBinding.addFencesOkBtn -> {
                saveSure()
            }
        }
    }

    /**
     * 选点计算距离返回
     */
    override fun calculationDistance(distances: Array<String>) {
        LogUtil.e("选点计算距离返回")
        if (mFenceShapeType == ConstantInt.CircleShapeType) {
            mCircleRadiusDistance = Utils.roundOffToInt(distances[0].toDouble())
            mViewBinding.fencesAddMapCircle.setShowDisDistance("${mCircleRadiusDistance}m")
        } else {
            mRectWidthDistance = Utils.roundOffToInt(distances[0].toDouble())
            mRectHeightDistance = Utils.roundOffToInt(distances[1].toDouble())
            mViewBinding.fencesAddMapRect.setShowDisDistance(
                "${mRectWidthDistance}m", "${mRectHeightDistance}m"
            )
        }
        //经纬度转成地址显示
        mFencesMapCommon.getLatLonAddress(mGeoCoderViewModel)
        showLoading(false)
    }

    /**
     * 地图加载完成返回
     */
    override fun mapCompletion() {
        LogUtil.e("地图加载完成返回")
        //编辑
        if (isEdit) {
            lifecycleScope.launch(Dispatchers.Main) {
                //等待地图移动摄像头动画播放结束
                delay(500)
                LogUtil.e("等待地图移动摄像头动画播放结束")
                if (mFenceShapeType == ConstantInt.RectangleShapeType) {
                    mFencesMapCommon.let {
                        val pointA = it.latLngToPotion(FencesPolygonView.POINT_A)
                        val pointB = it.latLngToPotion(FencesPolygonView.POINT_B)
                        val pointC = it.latLngToPotion(FencesPolygonView.POINT_C)
                        val pointD = it.latLngToPotion(FencesPolygonView.POINT_D)
                        pointA?.apply {
                            mViewBinding.fencesAddMapRect.apply {
                                setRectABCDXYPoint(pointA, pointA, pointB!!, pointC!!, pointD!!)
                                setShowDisDistance(
                                    "${mRectWidthDistance}m", "${mRectHeightDistance}m"
                                )
                            }
                        }
                        LogUtil.e("$pointA,$pointB,$pointC,$pointD")
                    }
                } else if (mFenceShapeType == ConstantInt.CircleShapeType) {
                    val px = mFencesMapCommon.getCircleRadiusPx(mCircleRadiusDistance.toDouble())
                    mViewBinding.fencesAddMapCircle.apply {
                        setCircleRadiusPx(px.toFloat())
                        setShowDisDistance("${mCircleRadiusDistance}m")
                    }
                }

                //经纬度转成地址显示,编辑首次进去不需要计算距离
                mFencesMapCommon.getLatLonAddress(mGeoCoderViewModel)
                showLoading(false)
            }
        }
    }

    override fun rectRotateClick() {
        mFencesMapCommon.refreshDistance()
    }

    override fun rectScaleEndClick() {
        mFencesMapCommon.refreshDistance()
    }

    override fun rectScalingClick() {

    }

    override fun rectStartDragClick() {
    }

    override fun rectEndDragClick() {
    }

    override fun circleScaleEndClick() {
        mFencesMapCommon.refreshDistance()
    }

    override fun circleStartDragClick() {
    }

    override fun circleScalingClick() {

    }

    override fun circleEndDragClick() {

    }
}