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

import ZtlApi.ZtlManager
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.annotation.RequiresApi
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.alibaba.android.arouter.launcher.ARouter
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.base.utils.XzjhSystemManagerUtlis
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.RouteUrl
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.LongClickUtils
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
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.HomeFragmentUserloginBinding
import com.quyunshuo.module.home.fragment.vm.UserLoginFragmentVM
import com.quyunshuo.module.home.model.livedata.LiveDataBean
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 UserLoginFragment : BaseFragment<HomeFragmentUserloginBinding, UserLoginFragmentVM>(),
    View.OnClickListener {
    private lateinit var usernamesNew: Array<String>

    private val TAG = "UserLoginFragment"
    private var language2ArrayAdapter: ArrayAdapter<String>? = null

    override val mViewModel: UserLoginFragmentVM by viewModels()
    override fun createVB() = HomeFragmentUserloginBinding.inflate(layoutInflater)
    private var selectUserName: String? = null
    private val myHandler: MyHandler = MyHandler(this@UserLoginFragment)
    private var CLOSE_TIME = 60
    private var backTime: Int = CLOSE_TIME //倒计时时间
    private var HANDLE_TIME = 1//设置时间
    private var isSystemBarOpen = false;//默认为false  默认关闭

    override fun HomeFragmentUserloginBinding.initView() {
        startRefreshime()
        addAllKeyboardView(mBinding.root)
        usernamesNew = arrayOf<String>("Admin", "Staff")
        selectUserName = usernamesNew[0]
        homeReturnToUpperLevel.setOnClickListener(this@UserLoginFragment)
        homeLoginSetting.setOnClickListener(this@UserLoginFragment)
        Log.d(TAG, "backstage_product_2 initView1: " + UiUtil.getStringRes(R.string.base_home_login))
        tvDeviceId.text = UiUtil.getStringRes(R.string.base_home_dev_id) + XLogUtil.getDeviceId()
        language2ArrayAdapter =
            this@UserLoginFragment.context?.let { ArrayAdapter<String>(it, R.layout.spinner_login) }
        language2ArrayAdapter!!.addAll(*usernamesNew)
        etHomeUsername.setAdapter(language2ArrayAdapter)
        etHomeUsername.setSelection(
            language2ArrayAdapter!!.getPosition(usernamesNew.get(0)),
            true
        )

        etHomeUsername.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long,
            ) {
                Log.d(TAG, "onItemSelected: " + usernamesNew[position])
                when (position) {
                    0 -> selectUserName = usernamesNew[position]
                    1 -> selectUserName = usernamesNew[position]
                }

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }
        })

        LongClickUtils.setLongClick(Handler(), ivClogo, 3000, object : View.OnLongClickListener {
            @RequiresApi(Build.VERSION_CODES.R)
            override fun onLongClick(p0: View?): Boolean {
                /*   val flag = SpUtils.getBoolean(MMKVName.LONG_CLICK_SHOW_STATUS_BAR, true)
                   if (flag == false) {
                       ToastUtil.switchToastStyleToWarn("该功能已关闭，请到后台打开")
                   }
                   //检查密码
                   val userPassword = mBinding.etHomePassword.text.toString().trim()
                   val pwdFlag = selectUserName?.let { mViewModel.checkUserReturn(it, userPassword) }
                   if (pwdFlag==false) {
                       ToastUtil.switchToastStyleToWarn(UiUtil.getStringRes(R.string.home_login_tips_1))
                       return true
                   }
                   //设置当前状态栏的状态
                   isSystemBarOpen = !isSystemBarOpen
                   ZtlManager.GetInstance().openSystemBar(isSystemBarOpen);
                   if (isSystemBarOpen) {
                       ToastUtil.switchToastStyleToSuccess("修改成功:打开")
                   }else{
                       ToastUtil.switchToastStyleToSuccess("修改成功:关闭")
                   }*/
                val userPassword = mBinding.etHomePassword.text.toString().trim()
                val pwdFlag = selectUserName?.let { mViewModel.checkUserReturn(it, userPassword) }
                if (pwdFlag == false) {
                    ToastUtil.switchToastStyleToWarn(UiUtil.getStringRes(R.string.base_home_login_tips_1))
                    return true
                }
                val flag = SpUtils.getBoolean(MMKVName.LONG_CLICK_SHOW_STATUS_BAR, true)

                if (flag != null && flag == true) {
                    isShowSar(flag = false)
                  //  SpUtils.putBoolean(MMKVName.LONG_CLICK_SHOW_STATUS_BAR, false)
                } else {
                  //  isShowSar(flag = true)
                  //  SpUtils.putBoolean(MMKVName.LONG_CLICK_SHOW_STATUS_BAR, true)
                }


                return true
            }

        })
    }

    fun isShowSar(flag: Boolean) {

        if (flag) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {  // Build.VERSION_CODES.R corresponds to Android 11
                ZtlManager.GetInstance().openSystemBar(flag)

                XzjhSystemManagerUtlis.getInstance().xzjhSetSystemBarEnable(flag)

            } else {
                ZtlManager.GetInstance().openSystemBar(flag)
                XzjhSystemManagerUtlis.getInstance().xzjhSetSystemBarEnable(flag)
            }
        } else {
            ZtlManager.GetInstance().openSystemBar(flag)
            XzjhSystemManagerUtlis.getInstance().xzjhSetSystemBarEnable(flag)
            // ToastUtil.showToast(UiUtil.getStringRes(R.string.modified_failed))
        }
    }

    override fun onResume() {
        super.onResume()
        mBinding.mlLogin.transitionToEnd()
    }

    override fun initObserve() {
        observeLiveData(mViewModel.checkResult, ::processData)
        lifecycle.addObserver(myHandler)
    }

    override fun initRequestData() {
        mViewModel.getUserInfo()
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.home_return_to_upper_level -> {
//                var bundle = Bundle()
//                bundle.putString("loginName",mBinding.etHomeUsername.toString().trim())
                val findNavController = findNavController()
                findNavController.navigate(R.id.home_action_home_userloginfragment_to_home_homefragment2)
            }

            R.id.home_login_setting -> {

                //检查密码是否合法。
                val userPassword = mBinding.etHomePassword.text.toString().trim()
                //进行密码对比。
                selectUserName?.let { mViewModel.checkUser(it, userPassword) }


            }
        }
    }

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

    private fun processData(data: LiveDataBean<String>) {
        if (data.code == 1) {
            ToastUtil.switchToastStyleToSuccess(data.data)
            ARouter.getInstance()
                .build(RouteUrl.Home.SettingActivity)
                .withString("loginName", selectUserName)
                .navigation()
            requireActivity().finish()
        } else {
            ToastUtil.switchToastStyleToWarn(data.data)

        }
    }

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

        override fun handleMessage(msg: android.os.Message) {
            //as用来强转
            var fragment: UserLoginFragment = mWeakReference.get() as UserLoginFragment
            when (msg.what) {
                fragment.HANDLE_TIME -> {
                    setTimeDate(fragment)
                }

                else -> {

                }
            }
        }

        /**
         * 设置时间
         */
        private fun setTimeDate(fragment: UserLoginFragment) {
            fragment.mBinding.tvBackTime.text = fragment.backTime.toString()
            XLogUtil.d("倒计时：" + fragment.backTime)
            fragment.backTime--
            if (fragment.backTime == 0) {
                val findNavController = fragment.findNavController()
                findNavController.navigate(R.id.home_action_home_userloginfragment_to_home_homefragment2)
            }
        }

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

    private var jobTimer: Job? = null

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

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

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