package com.develop.setting.init.ui

import android.graphics.Rect
import android.net.NetworkInfo
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.SystemClock
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.NetworkUtils
import com.develop.food.base.common.WIFI_FROM_MAIN_SETTING
import com.develop.food.base.event.FinishAtyEvent
import com.develop.food.base.event.RemoveWifiEvent
import com.develop.food.base.manager.wifi.WifiData
import com.develop.food.base.manager.wifi.WifiHelp
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.ui.PlainDialogView
import com.develop.food.base.utils.GlobalToast
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.utils.isNightTheme
import com.develop.setting.R
import com.develop.setting.databinding.ActivityWifiListBinding
import com.develop.setting.init.adapter.WifiListAdapter
import com.develop.setting.init.adapter.WifiListAdapter1
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path = Screens.Setting.WIFI)
class WifiListActivity : BaseActivity<ActivityWifiListBinding>() {
    private var wifiListAdapter = WifiListAdapter()
    private var wifiListAdapter1 = WifiListAdapter1()
    private var isFromMainSetting = false
    private var wifiDataList = mutableListOf<WifiData>()
    private lateinit var wifiHelp: WifiHelp
    private var wifiBean: WifiData? = null
    private var isWifiConnected = false
    private var isWifiDialog = false
    private var timer: CountDownTimer? = null


    private var mBackPressedTime: Long = 0  //防止客户重复点击wifi


    private val loadingDialog by lazy {
        PlainDialogView(this, R.layout.dialog_wifi_loading)
    }



    override fun createViewBinding(inflater: LayoutInflater): ActivityWifiListBinding {
        return ActivityWifiListBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isFromMainSetting = intent.extras?.getBoolean(WIFI_FROM_MAIN_SETTING) ?: false

        if (isFromMainSetting) {
            binding.tvSkin.visibility = View.GONE
        }

        binding.topBar.listenBackClick {
            finish()
        }
        binding.topBar.setTopBarTitle(getString(R.string.wifi))

        if (isNightTheme()) {
            wifiListAdapter1.apply {
                onOkClickListener = object : WifiListAdapter1.OnOkClickListener {
                    override fun onOkClick(accessPoint: WifiData) {
                        showloadingDialog()
                        isWifiConnected = false
                        isWifiDialog = false
                        wifiBean = accessPoint
                        wifiHelp.setConnectWifiDate(accessPoint)
                        wifiHelp.setIsWifiLoading(true)
//                            wifiHelp.connect(wifiData, wifiData.password)
                        wifiHelp.connectNew(accessPoint, accessPoint.password)
                        //倒计时30秒
                        countDownTimer()
                    }
                }
                setOnItemClickListener { adapter, view, position ->
                    if (SystemClock.elapsedRealtime() - mBackPressedTime < 1000) {
                        return@setOnItemClickListener
                    }
                    val clickModel = wifiDataList[position]
                    if (clickModel.isConnected) {
                        GlobalToast.showToast(this@WifiListActivity.getString(R.string.connected_successfully))
                    } else if (clickModel.password.isNotEmpty()) {
                        wifiHelp.connectNew(clickModel, clickModel.password)
                    } else if (clickModel.isSavePwd) {
                        showloadingDialog()
                        isWifiConnected = false
                        isWifiDialog = false
                        wifiBean = clickModel
                        wifiHelp.setConnectWifiDate(clickModel)
                        wifiHelp.setIsWifiLoading(true)
                        wifiHelp.connect(clickModel, true)
                        //倒计时30秒
                        countDownTimer()

                    } else {
                        updateSelectedPosition(position)
                    }
                    mBackPressedTime = SystemClock.elapsedRealtime();
                }

                setOnItemLongClickListener { adapter, view, position ->
                    wifiHelp.removeSaveWifi(wifiDataList[position])
                    true
                }
            }

            binding.wifiRecycler.apply {
                adapter = wifiListAdapter1
                addItemDecoration(object : RecyclerView.ItemDecoration() {
                    override fun getItemOffsets(
                        outRect: Rect,
                        view: View,
                        parent: RecyclerView,
                        state: RecyclerView.State
                    ) {
                        super.getItemOffsets(outRect, view, parent, state)
                        val pos = parent.getChildAdapterPosition(view)
                        if (pos == 0) {
                            outRect.top = ResDimension(R.dimen.convert_30px).toInt()
                        }
                        outRect.left = ResDimension(R.dimen.convert_45px).toInt()
                        outRect.right = ResDimension(R.dimen.convert_45px).toInt()
                        outRect.bottom = ResDimension(R.dimen.convert_50px).toInt()
                    }
                })
            }
        } else {
            wifiListAdapter.apply {
                onOkClickListener = object : WifiListAdapter.OnOkClickListener {
                    override fun onOkClick(accessPoint: WifiData) {
                        showloadingDialog()
                        isWifiConnected = false
                        isWifiDialog = false
                        wifiBean = accessPoint
                        wifiHelp.setConnectWifiDate(accessPoint)
                        wifiHelp.setIsWifiLoading(true)
//                            wifiHelp.connect(wifiData, wifiData.password)
                        wifiHelp.connectNew(accessPoint, accessPoint.password)
                        //倒计时30秒
                        countDownTimer()
                    }
                }
                setOnItemClickListener { adapter, view, position ->
                    if (SystemClock.elapsedRealtime() - mBackPressedTime < 1000) {
                         return@setOnItemClickListener
                    }
                    val clickModel = wifiDataList[position]
                    if (clickModel.isConnected) {
                        GlobalToast.showToast(this@WifiListActivity.getString(R.string.connected_successfully))
                    } else if (clickModel.password.isNotEmpty()) {
                        wifiHelp.connectNew(clickModel, clickModel.password)
                    } else if (clickModel.isSavePwd) {
                        showloadingDialog()
                        isWifiConnected = false
                        isWifiDialog = false
                        wifiBean = clickModel
                        wifiHelp.setConnectWifiDate(clickModel)
                        wifiHelp.setIsWifiLoading(true)
                        wifiHelp.connect(clickModel, true)
                        //倒计时30秒
                        countDownTimer()

                    } else {
                        updateSelectedPosition(position)
                    }
                    mBackPressedTime = SystemClock.elapsedRealtime();
                }

                setOnItemLongClickListener { adapter, view, position ->
                    wifiHelp.removeSaveWifi(wifiDataList[position])
                    true
                }
            }

            binding.wifiRecycler.apply {
                adapter = wifiListAdapter
                addItemDecoration(object : RecyclerView.ItemDecoration() {
                    override fun getItemOffsets(
                        outRect: Rect,
                        view: View,
                        parent: RecyclerView,
                        state: RecyclerView.State
                    ) {
                        super.getItemOffsets(outRect, view, parent, state)
                        val pos = parent.getChildAdapterPosition(view)
                        if (pos == 0) {
                            outRect.top = ResDimension(R.dimen.convert_30px).toInt()
                        }
                        outRect.left = ResDimension(R.dimen.convert_45px).toInt()
                        outRect.right = ResDimension(R.dimen.convert_45px).toInt()
                        outRect.bottom = ResDimension(R.dimen.convert_50px).toInt()
                    }
                })
            }
        }




        binding.tvSkin.setOnClickListener {
            if (NetworkUtils.isConnected()) {
                navigateTo(Screens.Auth.MEMBER)
            } else {
                navigateTo(Screens.Main.ENTRANCE_CHOSEN)
            }
            EventBus.getDefault().post(FinishAtyEvent())
            finish()
        }

        if (isFromMainSetting) {
            binding.tvNext.text = getText(R.string.confirm)
        }

        binding.tvNext.setOnClickListener {
            if (isFromMainSetting) {
                finish()
            } else {
                EventBus.getDefault().post(FinishAtyEvent())
                navigateTo(Screens.Auth.MEMBER)
            }

        }

        wifiHelp = WifiHelp.Build(this)
            .setErrorAuthenticating {
                dismissDialog()
            }
            .setScanCallback {

//                Log.e("TAG WIFI", "setScanCallback :")
                it?.apply {
                    wifiDataList.clear()
                    wifiDataList.addAll(it)
                    if (isNightTheme()) {
                        wifiListAdapter1.let { adapter ->
                            adapter.selectedPosition = -1
                            adapter.setList(wifiDataList)
                        }
//                        wifiListAdapter1.selectedPosition = -1
//                        wifiListAdapter1.setList(wifiDataList)
                    } else {
                        wifiListAdapter.let { adapter ->
                            adapter.selectedPosition = -1
                            adapter.setList(wifiDataList)
                        }
                    }
                }
                dismissDialog()
            }
            .setWifiStateChangedListener {
                dismissDialog()
            }
            .setAlreadyConnectionCallback {
                dismissDialog()
            }
            .setNetworkStateChangedListener {

//                Log.e("TAG WIFI", "STATE :" + it)

                if (it == NetworkInfo.DetailedState.CONNECTED) {
                    /**
                     * 当前如果有save 保存的wifi ，在输入多个错误的wifi，会导致连接上的wifi 需要FAILED 掉
                     * 估在这做处理，判断点击ok连接的wifi 如果没有连接上，需要remove掉，其他的话就保存
                     * 由于CONNECTED 回调会走几次，估多一个isWifiConnected开关来避免重复
                     * */
                    if (wifiBean != null&&!isWifiConnected) {
//                        Log.e("TAG WIFI", "forRemove------ :")
                        isWifiConnected = true
                        Handler().postDelayed({
                            forRemoveList()
                        }, 2000)
                    }

                }

                if ((it == NetworkInfo.DetailedState.CONNECTED||it == NetworkInfo.DetailedState.FAILED)&&!isWifiDialog){
                    timer?.let { timer->
                        timer.cancel()
                    }
                    isWifiDialog = true
                    var time : Long = if (isWifiConnected) 2200 else 1500
                    Handler().postDelayed({
                        dismissloadingDialog()
                        wifiHelp.setIsWifiLoading(false)
                        wifiHelp.refreshWifiData()


                    }, time)

                    if (it == NetworkInfo.DetailedState.FAILED){
                        //密码错误
                        showToast(getString(R.string.wifi_password_wrong))
                    }



                }

                dismissDialog()
            }
            .build()
    }

    private fun forRemoveList() {
        var isRemove = false
        wifiDataList.forEach { it ->
            if (it.ssid == wifiBean?.ssid) {
                //save 状态 需要remove 保存状态得wifi
//                Log.e("TAG WIFI", "wifiBean :"+it)
                if (it.isSavePwd && it.ipAddress.isNullOrEmpty()) {
//                    Log.e("TAG WIFI", "forRemoveListName :"+it.ssid)
                    isRemove = true
                    wifiHelp.removeSaveWifi(it)
                }
            }
        }
        if (isRemove){
            //获取已经保存的连接
            wifiHelp. initWork()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        wifiHelp.destroy()
    }

    override fun onResume() {
        super.onResume()
        AndPermission.with(this).runtime().permission(
            Permission.ACCESS_FINE_LOCATION,
            Permission.ACCESS_BACKGROUND_LOCATION, Permission.ACCESS_COARSE_LOCATION
        )
            .onGranted {
                wifiHelp.scan()
            }.start()
    }


    @Subscribe
    fun onRemoveWifi(event: RemoveWifiEvent) {
        wifiHelp.removeAllWifi()
    }

    //倒计时的方式一
    fun countDownTimer() {
        var num = 30

        timer = object : CountDownTimer((num + 1) * 1000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {

//                YYLogUtils.w("当时计数：" + num)
                Log.e("TAG 当时计数","当时计数 :"+num)
                if (num == 0) {
//                    YYLogUtils.w("重新开始")
//                    num = 30
                } else {
                    num--

                }

            }

            override fun onFinish() {
//                YYLogUtils.w("倒计时结束了..." + num)
                //处理 loading 没有关闭
                overtimeWifi()
            }
        }

        timer?.start()
    }
    private fun  overtimeWifi(){
        if (!isWifiDialog){
            wifiHelp.getConnectWifiDate()?.let {
                wifiHelp.removeSaveWifi(it)
            }
        }
    }

    fun showloadingDialog(cancelable: Boolean = false) {
        loadingDialog.showDialog(cancelable)
    }

    fun dismissloadingDialog() {
        loadingDialog.hideDialog()
    }
}