package com.rdiot.yx485.ui.bind

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import androidx.fragment.app.activityViewModels
import androidx.navigation.Navigation.findNavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.drake.net.utils.scopeNetLife
import com.king.zxing.util.LogUtils
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.BindModelFactory
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.FraBindDeviceBinding
import com.rdiot.yx485.net.DeviceCode
import com.rdiot.yx485.net.addMasterRoom
import com.rdiot.yx485.net.addRoom
import com.rdiot.yx485.net.updateFamilyData
import com.rdiot.yx485.net.updateRoomDeviceType
import com.rdiot.yx485.ui.bind.ble.BleCtrl
import com.rdiot.yx485.ui.bind.model.BindViewModel
import com.rdiot.yx485.util.loadOneTimeGif
import com.rdiot.yx485.util.setClickLimitListener
import kotlinx.coroutines.delay


/**
 * 绑定设备页面
 * @author mR2hao
 * @date 2022/11/21
 */
class BindDeviceFragment : BaseFragment<FraBindDeviceBinding>() {
    override fun getLayoutId() = R.layout.fra_bind_device
    private val bindViewModel: BindViewModel by activityViewModels { BindModelFactory() }
    private var dialog: IAlertDialog? = null

    /** 定位市名 */
//    private lateinit var cityName: String

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        binding.vm = bindViewModel
        bindViewModel.startCountDown()
        startRingAnimation()

        if (bindViewModel.isBindInfrared){
            bindViewModel.startCheckOnline()
        }

        if (bindViewModel.isBindSub) {
            startBindSubDevice()
        } else {
            startBindDevice()
        }

        if (!BuildConfig.DEBUG) {
            binding.tvDebug.visibility = View.GONE
        }

        bindViewModel.countDownTime.observe(this) {
            if (it <= 0) {
                showErrEventDialog(string = getString(R.string.add_timeout))
                BleCtrl.cancelBind()
            }
        }
        bindViewModel.deiceStatus.observe(this){
            if (it == 1) {
                bindSuccess()
            }
        }
    }

    /** 开始绑定分控 */
    private fun startBindSubDevice() {
        scopeNetLife {
            addRoom(
                bindViewModel.roomName.get()!!,
                bindViewModel.panelNum.get()!!,
                bindViewModel.deviceTypeId.get()!!
            ).await()
            delay(1500)
            bindSuccess()
        }
    }

    private fun startBindDevice() {
        /** 监听绑定事件 */
        BleCtrl.autoBind(
            this,
            bindViewModel.panelNum.get()!!,
            bindViewModel.roomName.get()!!,
            bindViewModel.wifiSsid.get()!!,
            bindViewModel.wifiPwd.get()!!,
            bindViewModel.deviceTypeId.get()!!
        ) { e ->
            if (!isResumed) return@autoBind

            val evenString = "Step:${e.getStep()} -- Code:${e.getCode()}"
            LogUtils.i(evenString)
            binding.tvDebug.text = "${binding.tvDebug.text}$evenString\n"

            if (bindViewModel.code ==  DeviceCode.INFRARED.typeCode) {
                bindViewModel.panelNum.set(e.getId())
            }
//            //添加成功
            if (e.getStep() == 5 && e.getCode() == 0) {
//                if (bindViewModel.code ==  DeviceCode.INFRARED.typeCode) {
//                    scopeNetLife {
//                        addMasterRoom(
//                            bindViewModel.roomName.get()!!,
//                            e.getId()  ,
//                            bindViewModel.deviceTypeId.get()!!
//                        ).await()
//                        delay(1500)
//                    }
//                }
                bindSuccess()
            }



            if (!e.isSuccess()) {
                showErrEventDialog(e.getCode())
                BleCtrl.cancelBind()
                bindViewModel.stopCountDown()
                bindViewModel.stopCheckOnline()
            } else {
                binding.tvSearch.setText(R.string.device_adding)
            }

        }

        lifecycle.addObserver(BleCtrl)
    }

    private fun bindSuccess() {
        bindViewModel.stopCountDown()
        bindViewModel.stopCheckOnline()
        if (!bindViewModel.isBindSub) {
            //更新定位信息
            val familyData = LocalData.familyData.value!!
            familyData.city = bindViewModel.locationName ?: ""
            scopeNetLife {
                updateFamilyData(familyData).await()
            }
        }

        if (binding.btnNext.visibility != View.VISIBLE) {
            act.loadOneTimeGif(R.mipmap.finish, binding.ivFinish)
            binding.btnNext.visibility = View.VISIBLE
            binding.tvDebug.text = getString(R.string.add_finish)
            BleCtrl.cancelBind()
        }

        if (bindViewModel.code ==  DeviceCode.INFRARED.typeCode) {
            scopeNetLife {
                addMasterRoom(
                    bindViewModel.roomName.get()!!,
                    bindViewModel.panelNum.get()!!  ,
                    bindViewModel.deviceTypeId.get()!!
                ).await()
                delay(1500)
            }
        }


        // 更新设备类型
        scopeNetLife {
            updateRoomDeviceType(bindViewModel.panelNum.get()!!, bindViewModel.deviceTypeId.get()!!).await()
        }

        binding.btnNext.setClickLimitListener { act.finish() }
    }


    /** 开始旋转动画 */
    private fun startRingAnimation() {
        val animation = RotateAnimation(
            0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f
        )
        animation.duration = 1300
        animation.repeatCount = -1
        animation.fillAfter = true
        animation.interpolator = LinearInterpolator()
        binding.ivRing.startAnimation(animation)
    }

    override fun onResume() {
        super.onResume()
        (act as BindActivity).setNBTitle(getString(R.string.bind_device))
    }

    private fun showErrEventDialog(code: Int? = null, string: String? = null) {
        dialog?.dismiss()
        dialog = IAlertDialog.build(this)
            .setTitle(R.string.add_failed)
            .setCancelOutside(false)
            .setShowNegButton(false)
            .setAlpha(1.0F)
            .setPosButtonText(R.string.got_it)
            .setPosClickListener {
                findNavController().popBackStack()
            }

        code?.let {
            dialog?.setMessage(String.format(getString(R.string.err_code), it))
        }
        string?.let {
            dialog?.setMessage(it)
        }
        dialog?.isCancelable = false
        dialog?.show()
    }
}