package com.grkj.iscs.view.activity

import android.view.InputDevice
import android.view.KeyEvent
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import com.grkj.iscs.BusinessManager
import com.grkj.iscs.R
import com.grkj.iscs.databinding.ActivityHomeBinding
import com.grkj.iscs.extentions.toByteArrays
import com.grkj.iscs.extentions.toHexStrings
import com.grkj.iscs.model.Constants.USER_ROLE_ADMHDWSETTER
import com.grkj.iscs.model.Constants.USER_ROLE_ADMHDWTESTER
import com.grkj.iscs.model.Constants.USER_ROLE_COLOCKER
import com.grkj.iscs.model.Constants.USER_ROLE_DRAWER
import com.grkj.iscs.model.Constants.USER_ROLE_GUARD
import com.grkj.iscs.model.Constants.USER_ROLE_LOCKER
import com.grkj.iscs.model.vo.user.UserInfoRespVO
import com.grkj.iscs.util.log.LogUtil
import com.grkj.iscs.view.adapter.MenuAdapter
import com.grkj.iscs.view.base.BaseFragment
import com.grkj.iscs.view.base.BaseMvpActivity
import com.grkj.iscs.view.fragment.DockTestFragment
import com.grkj.iscs.view.fragment.ExceptionReportFragment
import com.grkj.iscs.view.fragment.JobManagementFragment
import com.grkj.iscs.view.fragment.SettingFragment
import com.grkj.iscs.view.fragment.SystemSettingFragment
import com.grkj.iscs.view.iview.IHomeView
import com.grkj.iscs.view.presenter.HomePresenter
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder

/**
 * 首页
 */
class HomeActivity : BaseMvpActivity<IHomeView, HomePresenter, ActivityHomeBinding>() {

    private var cardNo = ""
    val cardNoLiveData = MutableLiveData("")
    private var mMenuList = mutableListOf<Menu>()

    override val viewBinding: ActivityHomeBinding
        get() = ActivityHomeBinding.inflate(layoutInflater)

    override fun initView() {
        presenter?.registerStatusListener()

        val userInfo = intent.getSerializableExtra("userInfo")

        BusinessManager.isTestMode = false
        if (userInfo != null && (userInfo as UserInfoRespVO).roles != null) {
            if (userInfo.roles?.any { it == USER_ROLE_DRAWER || it == USER_ROLE_LOCKER || it == USER_ROLE_COLOCKER || it == USER_ROLE_GUARD } == true) {
                mMenuList.addAll(mutableListOf(
                    Menu(getString(R.string.job_management), R.mipmap.job_management, JobManagementFragment())
                ))
            }
            if (userInfo.roles?.any { it == USER_ROLE_ADMHDWTESTER } == true) {
                BusinessManager.isTestMode = true
                mMenuList.add(Menu(getString(R.string.test), R.mipmap.menu_icon_test, DockTestFragment()))
            }
            if (userInfo.roles?.any { it == USER_ROLE_ADMHDWSETTER } == true) {
                mMenuList.add(Menu(getString(R.string.system_setting), R.mipmap.menu_icon_sys_setting, SystemSettingFragment()))
            }
        }
        mMenuList.add(Menu(getString(R.string.exception_report), R.mipmap.exception_handle, ExceptionReportFragment()))
        mMenuList.add(Menu(getString(R.string.settings), R.mipmap.settings, SettingFragment()))

        mBinding?.itemSetting?.ivIcon?.setImageResource(R.mipmap.settings)
        mBinding?.itemSetting?.tvName?.text = getString(R.string.settings)
        mBinding?.itemSetting?.root?.setOnClickListener {
            mBinding?.vp?.currentItem = mMenuList.size - 1
            mBinding?.itemSetting?.root?.setBackgroundColor(getColor(R.color.common_bg_white_30))
            mBinding?.rvMenu?.adapter?.notifyDataSetChanged()
        }
        if (mMenuList.size == 1) {
            mBinding?.itemSetting?.root?.setBackgroundColor(getColor(R.color.common_bg_white_30))
        }

        mBinding?.vp?.isUserInputEnabled = false
        mBinding?.vp?.offscreenPageLimit = mMenuList.size
        mBinding?.vp?.adapter = MenuAdapter(supportFragmentManager, lifecycle, mMenuList)

        mBinding?.rvMenu?.adapter = object : CommonAdapter<Menu>(this, R.layout.item_rv_menu, mMenuList) {
            override fun convert(holder: ViewHolder, data: Menu, position: Int) {
                holder.setVisible(R.id.root, data.title != getString(R.string.settings))
                holder.setText(R.id.tv_name, data.title)
                holder.getView<ImageView>(R.id.iv_icon).setImageResource(data.icon!!)
                holder.setOnClickListener(R.id.root) {
                    mBinding?.itemSetting?.root?.setBackgroundColor(0)
                    mBinding?.vp?.currentItem = position
                    notifyDataSetChanged()
                }
                holder.setBackgroundColor(R.id.root,
                    if (position == mBinding?.vp?.currentItem)
                        getColor(R.color.common_bg_white_30)
                    else 0)
            }
        }
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.action == KeyEvent.ACTION_UP && event.source == InputDevice.SOURCE_KEYBOARD) {
            // 检测到回车开始处理
            if (event.keyCode == 66) {
                cardNo = cardNo.toLong().toByteArrays().toHexStrings(false)
                LogUtil.i("Swipe card home: $cardNo")
                cardNoLiveData.postValue(cardNo)
                // 重置cardNo
                cardNo = ""
                return super.dispatchKeyEvent(event)
            }
            cardNo += event.keyCharacterMap.getDisplayLabel(event.keyCode)
        }
        return super.dispatchKeyEvent(event)
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter?.unregisterListener()
    }

    override fun initPresenter(): HomePresenter {
        return HomePresenter()
    }

    data class Menu(val title: String? = null, val icon: Int? = null, val fragment: BaseFragment<*>)
}