package com.qimai.yttgrass

import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import androidx.navigation.Navigation.findNavController
import com.qimai.android.fetch.Response.Status
import com.qimai.yttgrass.model.goodsInfoBean
import com.qimai.yttgrass.scan.ScanGun
import com.qimai.yttgrass.vm.HomeVm
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_welcome.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private var mScanGun: ScanGun? = null
    private val mVm: HomeVm by lazy {
        ViewModelProvider(this).get(HomeVm::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        hideBottomUIMenu()
        setContentView(R.layout.activity_main)
        initData()
      /*  lifecycleScope.launch{
            delay(3000)
            getInfo("8801051154436")
        }*/
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected fun hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            val v: View = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            val decorView: View = window.decorView
            val uiOptions: Int = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN)
            decorView.setSystemUiVisibility(uiOptions)
        }
    }

    private fun initData() {
        mScanGun = ScanGun(object : ScanGun.ScanGunCallBack {
            override fun onScanFinish(scanResult: String) {
                //关闭软键盘
                var code = scanResult
                if (TextUtils.isEmpty(code)) {
                    return
                } else if (scanResult.indexOf("#") != -1) {
                    // 微信提供的扫码枪 会多识别一个#
                    code = scanResult.substring(code.indexOf("#") + 1, scanResult.length)
                }
                Log.d("MainActivity", "onScanFinish: code= $code")
                getInfo(code)
                //  mVm.mCodeMutableList.value = code

            }
        })
        mScanGun?.setMaxKeysInterval(2000)
    }

    private fun getInfo(code: String) {
        mVm.getGoodsInfo(code, "0", "44764")
            .observe(this, Observer {
                when (it.status) {
                    Status.SUCCESS -> {
                        val goods = goodsInfoBean(
                            it.data?.data?.goods?.images,
                            it.data?.data?.name,
                            it.data?.data?.goods?.content?.subheading,
                            it.data?.data?.goods?.content?.content,
                            it.data?.data?.goods_id
                        )
                        mVm.mGoodsInfo = goods

                        val navigation = findNavController(nav_host_fragment)
                        val current = navigation.currentDestination

                        if (navigation.currentDestination?.getId() == R.id.detailFragment) {
                            navigation
                                .navigateUp()
                        }
                        navigation.navigate(R.id.action_welcomeFragment_to_detailFragment)
                    }
                    Status.ERROR -> {
                        Toast.makeText(this, it.message, Toast.LENGTH_LONG)
                            .show()
                    }
                }
            })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (mScanGun != null)
            mScanGun?.isMaybeScanning(event.keyCode, event)
        return super.onKeyDown(keyCode, event)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.keyCode > 6) {
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (event.keyCode == KeyEvent.KEYCODE_DEL) {//将键盘的删除键传递下去
                    return super.dispatchKeyEvent(event)
                }
                onKeyDown(event.keyCode, event)
            }
        } else {
            if (event.keyCode == KeyEvent.KEYCODE_BACK) {
                //将键盘的返回事件传递下去
                return super.dispatchKeyEvent(event)
            }
        }
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        return findNavController(this, R.id.nav_graph).navigateUp()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        Log.d("activity", "dispatchTouchEvent: ")
        mVm.mClickMutator.value = true
        return super.dispatchTouchEvent(ev)
    }
}