package com.quyunshuo.module.home.fragment.fragment

import android.content.Intent
import android.os.Build
import android.os.Handler
import android.provider.Settings
import android.text.format.DateFormat
import android.util.Log
import android.view.MotionEvent
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.navigation.fragment.findNavController
import com.hboxs.serialport.sbc.SBCHeartbeat
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.databinding.HomeFragmentBuyBinding
import com.quyunshuo.module.home.enums.LogoEnum
import com.quyunshuo.module.home.fragment.vm.BuyFragmentVM
import com.quyunshuo.module.home.utils.CommodityManage
import com.quyunshuo.module.home.utils.SimplePlayerUtil
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.io.File
import java.lang.ref.WeakReference


/**
 * 首页Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@AndroidEntryPoint
class BuyFragment : BaseFragment<HomeFragmentBuyBinding, BuyFragmentVM>() ,
    View.OnTouchListener,LifecycleObserver  {
    private val TAG = "BuyFragment"
    private var HANDLE_TIME = 1//设置时间
    private var simplePlayerUtil:SimplePlayerUtil? = null
    override val mViewModel: BuyFragmentVM by viewModels()
    private var playVideos: ArrayList<File>? = null
    override fun createVB() = HomeFragmentBuyBinding.inflate(layoutInflater)
    private val myHandler: MyHandler =
        MyHandler(this@BuyFragment)

    override fun HomeFragmentBuyBinding.initView() {
        startRefreshime()
/*        CommodityManage.getInstance()
            .init(BaseApplication.context, "version_${SBCHeartbeat.customizedVersion}.json")*/
        val deviceId = XLogUtil.getDeviceId()
        if (deviceId.isNotEmpty()) {
            tvClientId.text =
                UiUtil.getStringRes(R.string.base_home_dev_id) + deviceId.substring(deviceId.length - 6)
        }
        simplePlayerUtil = SimplePlayerUtil(svVideo)
        svVideo.setOnTouchListener(this@BuyFragment)

        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(this@BuyFragment.context)) {
                //悬浮窗权限
                val intent: Intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivityForResult(intent, 1)
            } else {
                //TODO do something you need
            }
        }
        //联系人
        ilContact.tvContact.text = SpUtils.getString(MMKVName.CONTACT,"name")
        ilContact.tvContactWay.text = SpUtils.getString(MMKVName.CONTACT_WAY,"123456")

        val logoIcon = SpUtils.getString(MMKVName.LOGO_TEXT, "1")
        val enumByValue = LogoEnum.getEnumByValue(logoIcon!!)
        val layoutParams = ivLogo.layoutParams
        enumByValue?.navId?.let { ivLogo.setImageResource(it) }
        enumByValue?.width?.let { layoutParams.width = it }
        enumByValue?.height?.let { layoutParams.height = it }

    }

    override fun initObserve() {
        lifecycle.addObserver(myHandler)
        lifecycle.addObserver(this)
    }

    override fun initRequestData() {
        Log.d(TAG, "initRequestData: ")
            simplePlayerUtil?.let { mViewModel.playvideo(it) }

    }


    override fun onTouch(v: View, event: MotionEvent): Boolean {
        Log.d(TAG, "onTouch: ")
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                CommodityManage.getInstance().init(BaseApplication.context, "version_${SBCHeartbeat.customizedVersion}.json")
                val findNavController = findNavController()
                findNavController.navigate(R.id.home_action_home_buyfragment_to_home_homefragment)
                Log.d(TAG, "onClick: ")
            }
            else -> {}
        }
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy: ")
    }

    override fun onDestroyView() {
        jobTimer?.cancel()
        simplePlayerUtil?.onDestroy()
        Log.d(TAG, "onDestroyView: ")
        super.onDestroyView()

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

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: BuyFragment? = mWeakReference.get() as BuyFragment
            when (msg.what) {
                1 -> {
                    val sysTime = System.currentTimeMillis() //获取系统时间
                    val sysTimeStr = DateFormat.format("yyyy-MM-dd HH:mm:ss", sysTime) //时间显示格式
                    fragment?.mBinding?.tvTime?.text = sysTimeStr //更新时间
                }

                else -> {

                }
            }
        }

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


    private var jobTimer: Job? = null

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopRefreshTime() {
        jobTimer?.cancel()
        Log.d(TAG, "stopRefreshTime: ")
    }
}