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.provider.Settings
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.ext.parseState
import com.ypsx.base.network.manager.NetState
import com.ypsx.yppos.R
import com.ypsx.yppos.app.base.BaseActivity
import com.ypsx.yppos.app.ext.startKtxActivityFinish
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.yppos.utils.dXLog
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.viewmodel.request.RequestSplashViewModel


/**
 * 启动也
 */
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()

    // 是否需要系统权限检测
    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 -> {
//                        startLogin()
                        showError("提示", getString(R.string.pos_apply), getString(R.string.see))
                    }
                    PosStatus.ACTIVE.name -> {
                        startLogin()
                    }
                    PosStatus.APPLY_FAILED.name -> {
                        val applyFailedMessage = data.applyFailedMessage
                        "错误原因：${applyFailedMessage}".dXLog()
                        showError("提示", getString(R.string.pos_failed), getString(R.string.see))
                    }
                    PosStatus.DISABLED.name -> {
                        showError("提示", getString(R.string.pos_disabled), getString(R.string.see))
                    }

                }
        })
    }

    private fun startLogin() {
        startKtxActivityFinish<LoginActivity>()
//        startActivity(Intent(this, LoginActivity::class.java))
//        finish()
    }

    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 {

        }
    }


}