package com.mints.goodmoney.ui.activitys

import android.content.Context
import android.media.AudioManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.ireader.ireadersdk.IreaderApi
import com.mints.goodmoney.R
import com.mints.goodmoney.ad.video.VedioAdingManager
import com.mints.goodmoney.common.AppConfig
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.mvp.views.MainView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.ui.fragment.*
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 描述：main
 * 作者：孟崔广
 * 时间：2020/10/9 10:39
 * 邮箱：mengcga@163.com
 */
class MainActivity : BaseActivity(), MainView, View.OnClickListener {

    private val audioManager by lazy { getSystemService(Context.AUDIO_SERVICE) as AudioManager }

    // 底部标签切换的Fragment
    private var moneyFragment: Fragment? = null
    private var panFragment: Fragment? = null
    private var friendsFragment: Fragment? = null
    private var myFragment: Fragment? = null
    private var channelFragment: Fragment? = null
    private var currentFragment: Fragment? = null

    override fun getContentViewLayoutID() = R.layout.activity_main

    override fun initViewsAndEvents() {
        if (moneyFragment == null) {
            moneyFragment = MoneyFragment()
        }
        if (!moneyFragment!!.isAdded) {
            // 提交事务
            supportFragmentManager.beginTransaction()
                    .add(R.id.content_layout, moneyFragment!!).commitAllowingStateLoss()

            // 记录当前Fragment
            currentFragment = moneyFragment
        }
        tab_iv_main.isSelected = true
        tab_tv_main.isSelected = true

        tab_rl_main.setOnClickListener(this)
        tab_rl_pan.setOnClickListener(this)
        tab_rl_channel.setOnClickListener(this)
        tab_rl_friends.setOnClickListener(this)
        tab_rl_my.setOnClickListener(this)
    }

    override fun isApplyKitKatTranslucency() = false

    public override fun onDestroy() {
        IreaderApi.onAppExit()

        super.onDestroy()

        VedioAdingManager.getInstance(this).setVedioAdingListener(null)
        VedioAdingManager.getInstance(this).onDestory()
    }

    public override fun onSaveInstanceState(outState: Bundle) {
        //将这一行注释掉，阻止activity保存fragment的状态，防止UI重叠
        //super.onSaveInstanceState(outState);
    }

    var oldTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP -> {
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true
            }
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true
            }
            KeyEvent.KEYCODE_BACK -> {
                // 设置为后台
                val currentTime = System.currentTimeMillis()
                if (currentTime - oldTime < 2 * 1000) {
                    baseApplication.exitApp()
                } else {
                    showToast("再次点击退出" + getString(R.string.app_name))
                    oldTime = currentTime
                }
            }
        }
        return true
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tab_rl_main -> clickTab1Layout()
            R.id.tab_rl_channel -> clickTab2Layout()
            R.id.tab_rl_pan -> clickTab3Layout()
            R.id.tab_rl_friends -> clickTab4Layout()
            R.id.tab_rl_my -> clickTab5Layout()
        }
    }

    /**
     * 点击第一个tab
     */
    fun clickTab1Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_MAIN
        if (moneyFragment == null) {
            moneyFragment = MoneyFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), moneyFragment!!)

        tab_iv_main.isSelected = true
        tab_tv_main.isSelected = true
        tab_iv_channel.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_pan.isSelected = false
        tab_tv_pan.isSelected = false
        tab_iv_friends.isSelected = false
        tab_tv_friends.isSelected = false
        tab_iv_my.isSelected = false
        tab_tv_my.isSelected = false
    }

    fun selectVedio() {
        moneyFragment?.let {
            (it as MoneyFragment).selectVedio()
        }
    }

    /**
     * 点击第二个tab
     */
    fun clickTab2Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_CHANNEL
        if (channelFragment == null) {
            channelFragment = HorizChannelFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), channelFragment!!)
        tab_iv_main.isSelected = false
        tab_tv_main.isSelected = false
        tab_iv_channel.isSelected = true
        tab_iv_channel.isSelected = true
        tab_iv_pan.isSelected = false
        tab_tv_pan.isSelected = false
        tab_iv_friends.isSelected = false
        tab_tv_friends.isSelected = false
        tab_iv_my.isSelected = false
        tab_tv_my.isSelected = false
    }

    /**
     * 点击第三个tab
     */
    fun clickTab3Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_PAN
        if (panFragment == null) {
            panFragment = PanFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), panFragment!!)
        tab_iv_main.isSelected = false
        tab_tv_main.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_pan.isSelected = true
        tab_tv_pan.isSelected = true
        tab_iv_friends.isSelected = false
        tab_tv_friends.isSelected = false
        tab_iv_my.isSelected = false
        tab_tv_my.isSelected = false
    }

    /**
     * 点击第四个tab
     */
    private fun clickTab4Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_FRIENDS
        if (friendsFragment == null) {
            friendsFragment = FriendsFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), friendsFragment!!)
        tab_iv_main.isSelected = false
        tab_tv_main.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_pan.isSelected = false
        tab_tv_pan.isSelected = false
        tab_iv_friends.isSelected = true
        tab_tv_friends.isSelected = true
        tab_iv_my.isSelected = false
        tab_tv_my.isSelected = false
    }

    /**
     * 点击第五个tab
     */
    private fun clickTab5Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_MY
        if (myFragment == null) {
            myFragment = MyFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), myFragment!!)
        tab_iv_main.isSelected = false
        tab_tv_main.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_channel.isSelected = false
        tab_iv_pan.isSelected = false
        tab_tv_pan.isSelected = false
        tab_iv_friends.isSelected = false
        tab_tv_friends.isSelected = false
        tab_iv_my.isSelected = true
        tab_tv_my.isSelected = true
    }

    /**
     * 添加或者显示碎片
     *
     * @param transaction
     * @param fragment
     */
    private fun addOrShowFragment(transaction: FragmentTransaction,
                                  fragment: Fragment) {
        if (currentFragment === fragment) return
        if (!fragment.isAdded) { // 如果当前fragment未被添加，则添加到Fragment管理器中
            transaction.hide(currentFragment!!)
                    .add(R.id.content_layout, fragment).commitAllowingStateLoss()
        } else {
            transaction.hide(currentFragment!!).show(fragment).commitAllowingStateLoss()
        }
        currentFragment = fragment
    }
}