package com.ypsx.yppos.ui.activity

import android.Manifest.permission.*
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import android.view.KeyEvent
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.ypsx.base.base.viewmodel.BaseViewModel
import com.ypsx.base.network.manager.NetState
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.ActivitySplashBinding
import com.ypsx.yppos.http.data.entity.PosStatus
import com.ypsx.yppos.room.repository.PosConfigRepository
import com.ypsx.yppos.ui.popup.MessagePopupWindow
import com.ypsx.base.util.dXLog
import com.ypsx.common.app.base.BaseActivity
import com.ypsx.common.app.ext.hideKeyboard
import com.ypsx.common.app.ext.startKtxActivity
import com.ypsx.common.app.ext.startKtxActivityFinish
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.viewmodel.request.RequestSplashViewModel
import kotlin.system.exitProcess


/**
 * 启动也
 */
class SplashActivity : BaseActivity<BaseViewModel, ActivitySplashBinding>() {
    private val PERMISSION_REQUEST_CODE = 0 // 系统权限管理页面的参数
    private val perms = arrayOf(
        READ_PHONE_STATE,
        READ_EXTERNAL_STORAGE,
        WRITE_EXTERNAL_STORAGE
    )
    private val requestSplashViewModel: RequestSplashViewModel by viewModels()
    private var messagePopupWindow: MessagePopupWindow? = null

    // 是否需要系统权限检测
    var isRequireCheck = false
    override fun layoutId(): Int = R.layout.activity_splash

    override fun initView(savedInstanceState: Bundle?) {
        isRequireCheck = true

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true
            allPermissionsGranted()
        } else {
            isRequireCheck = false

            showMissingPermissionDialog()
        }
    }

    private fun showMissingPermissionDialog() {
        val messagePopupWindow = MessagePopupWindow(this)
        messagePopupWindow.showPopupWindow()
        messagePopupWindow.setData(
            "帮助",
            "当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。",
            cancel = "退出",
            sure = "设置",
            true
        )
        messagePopupWindow.setMessageClick {
            startAppSettings()
        }
    }


    override fun onResume() {
        super.onResume()
        if (isRequireCheck) {
            if (lacksPermissions(perms)) {
                ActivityCompat.requestPermissions(
                    this,
                    perms,
                    PERMISSION_REQUEST_CODE
                )
            } else {
                allPermissionsGranted() // 全部权限都已获取
            }
        } else {
            isRequireCheck = true
        }
    }

    //全部权限以获取
    private fun allPermissionsGranted() {
        val posConfig = PosConfigRepository.getInstance().loadConfig()
        if (posConfig == null) {
            "配置信息为空".dXLog()
            startKtxActivityFinish<RegisterActivity>()
        } else {
            val id = posConfig.id
            requestSplashViewModel.getById(id)
        }


    }

    override fun onNetworkStateChanged(netState: NetState) {
        super.onNetworkStateChanged(netState)
        if (netState.isSuccess) {
            "我特么终于有网了啊!".dXLog()
        } else {
            "我特么怎么断网了!".dXLog()
        }
    }

    // 判断权限集合
    private fun lacksPermissions(permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (lacksPermission(permission)) {
                return true
            }
        }
        return false
    }

    // 判断是否缺少权限
    private fun lacksPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(this, permission) ==
                PackageManager.PERMISSION_DENIED
    }

    private fun hasAllPermissionsGranted(grantResults: IntArray): Boolean {
        for (grantResult in grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false
            }
        }
        return true
    }

    private fun startAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse("package:$packageName")
        startActivity(intent)
    }

    override fun createObserver() {
        requestSplashViewModel.posDetails.observe(this, { data ->
            val status = data.status
            requestSplashViewModel.savePosConfig(data)
            when (status) {
                PosStatus.APPLY.name -> {
                    val arrayOf = arrayOf(Pair<String, Any>("state", true),Pair<String, Any>("posId", data.id))
                    startKtxActivity<RegisterActivity>(values = arrayOf)
                    finish()
                }
                PosStatus.ACTIVE.name -> {
                    startLogin()
                }
                PosStatus.APPLY_FAILED.name -> {
                    val applyFailedMessage = data.applyFailedMessage
                    "错误原因：${applyFailedMessage}".dXLog()
                    val messagePopupWindow = MessagePopupWindow(this)
                    messagePopupWindow.showPopupWindow()

                    messagePopupWindow.setData(
                        "提示",
                        getString(R.string.pos_failed),
                        sure = getString(R.string.see),
                        gone = false
                    )
                    messagePopupWindow.setMessageClick {
                        messagePopupWindow.dismiss()
                        startKtxActivityFinish<RegisterActivity>()
                    }
                }
                PosStatus.DISABLED.name -> {
                    val messagePopupWindow = MessagePopupWindow(this)
                    messagePopupWindow.showPopupWindow()
                    messagePopupWindow.setData(
                        "提示",
                        getString(R.string.pos_disabled),
                        sure = getString(R.string.see),
                        gone = false
                    )
                    messagePopupWindow.setMessageClick {
                        messagePopupWindow.dismiss()
                        startKtxActivityFinish<RegisterActivity>()
                    }
                }

            }
        })

        requestSplashViewModel.posDetails2.observe(this, Observer { data ->
            val status = data.status
            requestSplashViewModel.savePosConfig(data)
            when (status) {
                PosStatus.APPLY.name -> {
                }
                PosStatus.ACTIVE.name -> {
                    messagePopupWindow!!.dismiss()
                    startKtxActivityFinish<LoginActivity>()
                }
                PosStatus.APPLY_FAILED.name -> {
                    val applyFailedMessage = data.applyFailedMessage
                    "错误原因：${applyFailedMessage}".dXLog()

                    startKtxActivityFinish<RegisterActivity>()
//                    showError("提示", getString(R.string.pos_failed), getString(R.string.see))
                }
                PosStatus.DISABLED.name -> {
//                        showError("提示", getString(R.string.pos_disabled), getString(R.string.see))
                    val messagePopupWindow = MessagePopupWindow(this)
                    messagePopupWindow.showPopupWindow()

                    messagePopupWindow.setData(
                        "提示",
                        getString(R.string.pos_disabled),
                        sure = getString(R.string.see),
                        gone = false
                    )
                    messagePopupWindow.setMessageClick {
                        messagePopupWindow.dismiss()
                        startKtxActivityFinish<RegisterActivity>()
                    }
                }
            }
        })
    }

    private fun startLogin() {
        startKtxActivityFinish<LoginActivity>()

    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                "再按一次退出程序".toast()
                exitTime = System.currentTimeMillis()
            } else {
                this.finish()
                exitProcess(0)
                Process.killProcess(Process.myPid())
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun showError(title: String, content: String, sure: String) {
        val messagePopupWindow = MessagePopupWindow(this)
        messagePopupWindow.showPopupWindow()

        messagePopupWindow.setData(title, content, sure = sure, gone = false)
        messagePopupWindow.setMessageClick {

        }
    }


}