package com.module.backstage.fragment


import android.os.Handler
import android.text.format.DateFormat
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.module.backstage.adapter.LocalAlarmClockAdapter
import com.module.backstage.databinding.BackstageFragmentLocalAlarmClockBinding
import com.module.backstage.dialog.LocalAlarmClockDialog
import com.module.backstage.vm.LocalAlarmClockFragmentVM
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.LocalAlarmClockBean
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.listener.AdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.AlarmManagerUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference

/**
 * 本地闹钟Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@AndroidEntryPoint
class LocalAlarmClockFragment :
    BaseFragment<BackstageFragmentLocalAlarmClockBinding, LocalAlarmClockFragmentVM>() {

    private val myHandler: MyHandler = MyHandler(this@LocalAlarmClockFragment)
    override val mViewModel: LocalAlarmClockFragmentVM by viewModels()
    override fun createVB() = BackstageFragmentLocalAlarmClockBinding.inflate(layoutInflater)
    private var localAdapter: LocalAlarmClockAdapter? = null
    var localAlarmClockDialog: LocalAlarmClockDialog? = null
    var list: ArrayList<LocalAlarmClockBean>? = null
    var addOrUpdate = 1// 1为添加 2为修改

    override fun BackstageFragmentLocalAlarmClockBinding.initView() {
        startRefreshime()
        rvLocalAlarmClock.layoutManager = LinearLayoutManager(this@LocalAlarmClockFragment.context)
        SpUtils.getString(MMKVName.LOCAL_ALARM_CLOCK, "")
        val productStr = SpUtils.getString(
            MMKVName.LOCAL_ALARM_CLOCK,
            Gson().toJson(ArrayList<LocalAlarmClockBean>())
        )

        list = Gson().fromJson(
            productStr,
            object : TypeToken<ArrayList<LocalAlarmClockBean?>?>() {}.type
        )
        localAdapter = LocalAlarmClockAdapter(list)
        localAdapter?.setItemListener(object : AdapterClickListener {
            override fun onClickListener(view: View?, position: Int, data: String?) {
                XLogUtil.d("测试 data:" + data + ":" + list)
                when (data) {
                    localAdapter?.DELETE -> {
                        var remove = list?.removeAt(position)
                        list?.let { localAdapter?.setDatas(it) }
                        // localAdapter?.notifyDataSetChanged()
                        SpUtils.putString(MMKVName.LOCAL_ALARM_CLOCK, Gson().toJson(list))
                        Log.d("backinfo", "闹钟：" + Gson().toJson(list))
                        mViewModel.setAlarmClock(list)
                        //关闭指定的闹钟。
                        /*  val number: Int = Integer.valueOf(remove?.id)
                          for (i in number * 1000 until number * 1000 + remove?.week?.size!!) { //清除所有的闹钟
                              AlarmManagerUtil.cancelAlarm(
                                  BaseApplication.context,
                                  AlarmManagerUtil.ALARM_ACTION,
                                  i
                              )

                          }*/
                    }

                    localAdapter?.UPDATE -> {
                        Log.d("backinfo","更新：UPDATE:"+position)
                        showUpdateApp(2, position)
                    }

                    else -> {}
                }
            }
        })
        rvLocalAlarmClock.adapter = localAdapter
        tvAddLock.setOnClickListener {
            list?.size?.let { it1 -> showUpdateApp(1, it1) }
        }
        cbOpenLock.isChecked = SpUtils.getBoolean(MMKVName.ALARMCLOCK_TYPE, false)!!
        cbOpenLock.setOnCheckedChangeListener { buttonView, isChecked ->
            SpUtils.putBoolean(MMKVName.ALARMCLOCK_TYPE, isChecked)
        }
        mViewModel.setAlarmClock(list)
    }

    override fun initObserve() {
    }

    override fun initRequestData() {
        mViewModel.getBanners()
        mViewModel.getArticleData()
    }

    override fun onDestroyView() {
        mBinding.rvLocalAlarmClock.adapter = null
        super.onDestroyView()
    }
    var position=-1

    private fun showUpdateApp(type: Int, id: Int) {
        addOrUpdate = type
        position=id
        if (localAlarmClockDialog == null) {
            localAlarmClockDialog = this@LocalAlarmClockFragment.context?.let {
                LocalAlarmClockDialog(
                    it
                )
            }
            localAlarmClockDialog?.setListener(object : LocalAlarmClockDialog.DialogClickListener {
                override fun onClickListener(type: Int, localAlarmClockBean: LocalAlarmClockBean) {
                    when (type) {
                        localAlarmClockDialog?.add -> {
                            list?.add(localAlarmClockBean)
                            localAdapter?.notifyDataSetChanged()
                            SpUtils.putString(MMKVName.LOCAL_ALARM_CLOCK, Gson().toJson(list))
                        }

                        localAlarmClockDialog?.update -> {
                            list?.set(position, localAlarmClockBean)
                            Log.d("backinfo","更新：$position"+Gson().toJson(list))
                            list?.let { localAdapter?.setDatas(it) }
                            SpUtils.putString(MMKVName.LOCAL_ALARM_CLOCK, Gson().toJson(list))

                        }

                        else -> {

                        }
                    }
                    mViewModel.setAlarmClock(list)

                }

            })
        }
        when (type) {
            1 -> {
                localAlarmClockDialog?.add(id, addOrUpdate)
            }

            2 -> {
                localAlarmClockDialog?.update(list?.get(id!!), addOrUpdate)
            }

            else -> {}
        }
        localAlarmClockDialog?.show()

    }

    private var jobTimer: Job? = null

    /**
     * 时间日期 隔个一秒执行一次
     */
    private fun startRefreshime() {
        stopRefreshTime()
        // 启动协程
        jobTimer = CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                myHandler.sendEmptyMessage(1)
                delay(1000) // 每隔1秒重复执行
            }
        }
    }

    private fun stopRefreshTime() {
        jobTimer?.cancel()
    }

    internal class MyHandler(fragment: Fragment) : Handler(), LifecycleObserver {
        var mWeakReference: WeakReference<Fragment> = WeakReference(fragment)

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: LocalAlarmClockFragment = mWeakReference.get() as LocalAlarmClockFragment
            setTimeDate(fragment)
        }

        /**
         * 设置时间
         */
        private fun setTimeDate(fragment: LocalAlarmClockFragment) {
            val sysTime = System.currentTimeMillis() //获取系统时间
            val sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式
            fragment.mBinding.tvTime.text = sysTimeStr //更新时间
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun disconnectListener() {
            removeCallbacksAndMessages(null)
        }
    }

    override fun onStop() {
        stopRefreshTime()
        super.onStop()
    }
}