package com.dlc.exam.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.view.LayoutInflater
import android.view.View
import androidx.viewbinding.ViewBinding
import com.dlc.exam.BuildConfig
import com.dlc.exam.ExamApp
import com.dlc.exam.common.CommonUtils
import com.dlc.exam.databinding.ActivityMainBinding
import com.dlc.exam.iflytek.VoiceItsManager
import com.dlc.exam.mqtt.MqttService
import com.dlc.exam.mqtt.event.UpdateEvent
import com.dlc.exam.ui.certificate.CertificateManagementActivity
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.exam.SafetyExamHomeActivity
import com.dlc.exam.ui.learn.SafetyLearnActivity
import com.dlc.exam.ui.login.LoginActivity
import com.dlc.exam.ui.login.ViolationHandlingDialog
import com.dlc.exam.ui.me.PersonalCenterActivity
import com.dlc.exam.ui.mock.SelectedMockTypeActivity
import com.dlc.exam.ui.score.QueryScoreActivity
import com.dlc.exam.ui.settings.PasswordDialog
import com.dlc.exam.ui.settings.SettingsActivity
import com.dlc.exam.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.core.util.ApkUpdater
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 首页
 *
 * @author ReiChin_
 */
class MainActivity : BaseCountDownActivity<ActivityMainBinding>(), TitleBar.TitleListener {

    override fun createViewBinding() = ActivityMainBinding.inflate(LayoutInflater.from(this))

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        VoiceItsManager.initIts(this)
        VoiceItsManager.speakVoice("欢迎使用实验室安全学习与考试系统")
        EventBus.getDefault().register(this)
        bindService(Intent(this, MqttService::class.java), mConnection, BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        VoiceItsManager.release()
        EventBus.getDefault().unregister(this)
        unbindService(mConnection)
        super.onDestroy()
    }

    private val mConnection: ServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            service as MqttService.MqttBinder
            service.initMqtt()
        }

        override fun onServiceDisconnected(name: ComponentName) {
        }
    }

    override fun onResume() {
        if (null == ExamApp.sLearnLoginVo) {
            viewBinding.titleBar.showLogoutView(false)
            viewBinding.titleBar.setUsername("未登录")
        }

        super.onResume()
    }

    override fun initListener() {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setOnLongClickListener {
            PasswordDialog(this) {
                val intent = Intent(this, SettingsActivity::class.java)
                startActivity(intent)
            }.show()
            true
        }

        // 安全考试
        viewBinding.safetyExam.setOnClickListener { dispatchMenuClicked(SafetyExamHomeActivity::class.java) }

        // 证书管理
        viewBinding.certificateManagement.setOnClickListener {
            dispatchMenuClicked(
                CertificateManagementActivity::class.java
            )
        }

        // 安全学习
        viewBinding.safetyLearn.setOnClickListener { dispatchMenuClicked(SafetyLearnActivity::class.java) }

        // 模拟练习
        viewBinding.mockTest.setOnClickListener { dispatchMenuClicked(SelectedMockTypeActivity::class.java) }

        // 成绩查询
        viewBinding.examScore.setOnClickListener { dispatchMenuClicked(QueryScoreActivity::class.java) }
    }

    private fun dispatchMenuClicked(menuClass: Class<out BaseCountDownActivity<out ViewBinding>>) {
        mMenuClass = menuClass
        if (isLogin()) {
            val intent = Intent(this, mMenuClass)
            startActivity(intent)
        }
    }

    private fun isLogin(): Boolean {
        if (null != ExamApp.sLearnLoginVo) {
            return true
        }

//        showToast("请先登录")

        if (HttpClient.token==null) {
            authLogin()
        } else {
            startLoginActivity()
        }
        return false
    }

    /*
     * 登录获取token
     */
    private fun authLogin() {
        showLoading("加载中...")
        val disposable = ApiRepository.authOneLogin()
            .subscribe({ success ->
                dismissLoading()
                if (success) {
                    startLoginActivity()
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun startLoginActivity() {
        val intent = Intent(this, LoginActivity::class.java)
        startActivityForResult(intent, 100)
    }

    private var mMenuClass: Class<out BaseCountDownActivity<out ViewBinding>>? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (100 == requestCode) {
            if (RESULT_OK == resultCode) {
                // 登录成功
                queryTodoViolation()

                viewBinding.titleBar.showLogoutView(true)
                viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo!!.nickName)
            }
        }
    }

    private fun queryTodoViolation() {
        showLoading("查询中...")
        val disposable = ApiRepository.existTodoViolation()
            .subscribe({
                // 有待处理的违规，弹出提示框
                dismissLoading()
                ViolationHandlingDialog(this) { hand ->
                    if (hand) {
                        // 处理
                        startActivity(Intent(this, PersonalCenterActivity::class.java))
                    } else {
                        // 不处理
                        mMenuClass?.let {
                            startActivity(Intent(this, it))
                        }
                    }
                }.show()
            }, {
                dismissLoading()
                // 没有待处理的违规
                mMenuClass?.let {
                    startActivity(Intent(this, it))
                }
            })
        addDisposable(disposable)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUpdateEventEvent(event: UpdateEvent) {
        if (CommonUtils.stringParseInt(event.data.version) > DeviceUtils.getVersionCode(this)) {
            // 显示版本更新
            downloadApk(event.data.apkUploadFile)
        }
    }

    private var apkDownloading = false

    private fun downloadApk(downloadUrl: String) {
        if (apkDownloading) return
        apkDownloading = true
        callApkUpdateApi("2")
        ApkUpdater(applicationContext, BuildConfig.APPLICATION_ID, callback = object :
            ApkUpdater.DownloadCallback {
            override fun onProgress(progress: Int) {
            }

            override fun onFailed(errMsg: String?) {
                apkDownloading = false
                callApkUpdateApi("0")
            }

            override fun onSuccess(apkFile: String) {
                apkDownloading = false
                callApkUpdateApi("1")
            }

        }).downloadApk(downloadUrl)
    }

    /*
     * state 0:升级失败; 1:升级成功; 2:升级中
     */
    private fun callApkUpdateApi(state: String) {
        val disposable = ApiRepository.onepcApkUpdate(CommonUtils.getAndroidId(this), state)
            .subscribe({ }, { })
        addDisposable(disposable)
    }

    override fun onHomeViewClicked(view: View) {
    }

    override fun onLogoutViewClicked(view: View) {
        callLogoutApi {
            showToast("已退出登录")

            ExamApp.sLearnLoginVo = null
            HttpClient.token = null

            viewBinding.titleBar.showLogoutView(false)
            viewBinding.titleBar.setUsername("未登录")
        }
    }

    override fun onBackViewClicked(view: View) {
        RcLog.info("     HttpClient.token=====返回=="+     HttpClient.token)
    }

    override fun onUserViewClicked(view: View) {
        mMenuClass = null
        if (isLogin()) {
            val intent = Intent(this, PersonalCenterActivity::class.java)
            startActivity(intent)
        }
    }

}