package com.cheng.blzb.ui.fragment.mine.settings

import android.graphics.Color
import androidx.lifecycle.lifecycleScope
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentSettingsBinding
import com.cheng.blzb.event.LoginSuccessEvent
import com.cheng.blzb.event.LogoutSuccessEvent
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.LoginActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.TipDialog
import com.cheng.blzb.ui.fragment.mine.about.AboutFragment
import com.cheng.blzb.ui.fragment.mine.account.AccountManageFragment
import com.cheng.blzb.ui.fragment.mine.account.BindAccountFragment
import com.cheng.blzb.utils.AppUpdateUtils
import com.cheng.blzb.utils.DataCacheUtils
import com.cheng.blzb.utils.FileUtils
import com.example.base.common.RxBus
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.AppUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.backgroundColor

/**
 * 设置
 */
class SettingsFragment : BaseFragment<FragmentSettingsBinding, SettingsViewModel>() {

    override fun initView() {
        super.initView()
        mTitleBar?.backgroundColor = Color.WHITE

        if (LoginManager.isLogin()) {
            binding.tvLogOff.visible()
            binding.layoutBottom.visible()
        } else {
            binding.tvLogOff.gone()
            binding.layoutBottom.gone()
        }
    }

    override fun initData() {
        super.initData()
    }

    override fun onResume() {
        super.onResume()
        binding.tvCacheSize.text = FileUtils.toFileSize(DataCacheUtils.getCacheSize())
        binding.tvVersion.text = "v${AppUtils.getAppVersionName()}"
    }

    override fun initListener() {
        super.initListener()
        binding.layoutUpdate.onClick {
            AppUpdateUtils.checkUpdate(this, false) {}
        }

        binding.tvAbout.onClick {
            PublicActivity.start(requireContext(), AboutFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_ABOUT_US, "", "")
        }
        binding.tvLogOff.onClick {
            val f = TipDialog.newInstance("提示", "为了您的账户安全，注销账户后将会永久清除与该账户相关的所有信息，服务器不再保存")
            f.setOnSelectListener {
                if (it == DialogEnum.CLICK_OK) {
                    mViewModel.userDestroy()
                }
            }
            f.show(childFragmentManager, "")
        }
        binding.tvBindAccount.onClick {
            PublicActivity.start(requireContext(), BindAccountFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_ACCOUNT_BIND, "", "")
        }
        binding.tvManageAccount.onClick {
            PublicActivity.start(requireContext(), AccountManageFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_ACCOUNT_MANAGE, "", "")
        }
        binding.layoutCache.onClick {
            clearCache()
            binding.tvCacheSize.text = FileUtils.toFileSize(DataCacheUtils.getCacheSize())
            EventReportManager.eventReport(EventConstants.CLEAR_CACHE, "mine", "")
        }
        binding.btnLogout.onClick {
            val f = TipDialog.newInstance("提示", "是否退出登录？")
            f.setOnSelectListener {
                if (it == DialogEnum.CLICK_OK) {
                    mViewModel.logout()
                }
            }
            f.show(childFragmentManager, "")
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.logoutLiveData.observe(this) {
            EventReportManager.eventReport(EventConstants.EXIT_LOGIN, "", "")
            logout()
        }
        mViewModel.destroyLiveData.observe(this) {
            EventReportManager.eventReport(EventConstants.CANCEL_ACCOUNT, "", "")
            logout()
        }

        val loginSuccessEvent = RxBus.defaultInstance.toObservable(LoginSuccessEvent::class.java).subscribe {
            requireActivity().finish()
        }
        addDisposable(loginSuccessEvent)
    }

    private fun clearCache() {
        val f = TipDialog.newInstance("温馨提示", "您确定要清除缓存吗？")
        f.setOnSelectListener {
            if (it == DialogEnum.CLICK_OK) {
                mViewModel.showDialog()
                lifecycleScope.launch(Dispatchers.IO) {
                    val cacheSize = DataCacheUtils.getCacheSize()
                    DataCacheUtils.cleanInternalCache()
                    withContext(Dispatchers.Main) {
                        mViewModel.dismissDialog()
                        toast("已清除缓存，释放空间 ${FileUtils.toFileSize(cacheSize)}")
                        binding.tvCacheSize.text = FileUtils.toFileSize(DataCacheUtils.getCacheSize())
                    }
                }
            }
        }
        f.show(childFragmentManager, TipDialog::class.java.simpleName)
    }

    private fun logout() {
        UserConfigManager.saveLastUserinfo(UserConfigManager.userInfo)
        LoginManager.logout()
        RxBus.defaultInstance.post(LogoutSuccessEvent())
        LoginActivity.start(requireActivity())
        requireActivity().finish()
    }

}