package com.duben.microtribe.ui.activitys

import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.duben.microtribe.MintsApplication
import com.duben.microtribe.R
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.common.Constant
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.fragment.MainFragment
import com.duben.microtribe.ui.fragment.MyFragment
import com.duben.microtribe.ui.fragment.RecommendFragment
import com.duben.microtribe.ui.fragment.VipEnjoyFragment
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.PhoneDialog
import com.duben.microtribe.video.csj.DPHolderManager
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 描述：首页
 * 作者：孟崔广
 * 时间：2022/12/24 18:06
 */
class MainActivity : BaseActivity(), View.OnClickListener {

    private var audioManager: AudioManager? = null

    var tabIvLoan: TextView? = null
    var tabIvRecommend: TextView? = null
    var tabIvEnjoy: ImageView? = null
    var tabIvMy: TextView? = null

    private var mShowBlack = false

    // 底部标签切换的Fragment
    private var mainFragment: Fragment? = null
    private var recommendFragment: Fragment? = null
    private var myFragment: Fragment? = null
    private var vipEnjoyFragment: Fragment? = null

    private var currentFragment: Fragment? = null
    private var phoneDialog: PhoneDialog? = null

    override fun getContentViewLayoutID(): Int {
        return R.layout.activity_main
    }

    override fun initViewsAndEvents() {
        DPHolderManager.initDpSdk(MintsApplication.getContext());

        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

        tabIvLoan = findViewById(R.id.tab_iv_loan)
        tabIvRecommend = findViewById(R.id.tab_iv_recommend)
        tabIvEnjoy = findViewById(R.id.tab_iv_enjoy)
        tabIvMy = findViewById(R.id.tab_iv_my)
        findViewById<View>(R.id.tab_rl_loan).setOnClickListener(this)
        findViewById<View>(R.id.tab_rl_recommend).setOnClickListener(this)
        findViewById<View>(R.id.tab_rl_enjoy).setOnClickListener(this)
        findViewById<View>(R.id.tab_rl_my).setOnClickListener(this)

        if (AppConfig.showVipVedio) {
            // 显示尊享页面
            tab_rl_enjoy.visibility = View.VISIBLE
        } else {
            tab_rl_enjoy.visibility = View.GONE
        }

        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_ONE
        if (mainFragment == null) {
            mainFragment = MainFragment()
        }
        if (!mainFragment!!.isAdded) {
            // 提交事务
            supportFragmentManager.beginTransaction()
                .add(R.id.content_layout, mainFragment!!).commitAllowingStateLoss()

            // 记录当前Fragment
            currentFragment = mainFragment
        }
        if (tabIvLoan != null) {
            tabIvLoan!!.isSelected = true
        }


        initEditView()

    }

    override fun isApplyKitKatTranslucency(): Boolean {
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        currentFragment = null
        audioManager = null
    }

    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_loan -> clickTab1Layout()
            R.id.tab_rl_recommend -> clickTab2Layout()
            R.id.tab_rl_enjoy -> clickTab3Layout()
            R.id.tab_rl_my -> clickTab4Layout()
        }
    }

    /**
     * 点击第一个tab
     */
    fun clickTab1Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_ONE
        if (mainFragment == null) {
            mainFragment = MainFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), mainFragment!!)
        tabIvLoan!!.isSelected = true
        tabIvRecommend!!.isSelected = false
//        tabIvEnjoy!!.isSelected = false
        tabIvMy!!.isSelected = false


        tabIvEnjoy!!.scaleX = 0.9f
        tabIvEnjoy!!.scaleY = 0.9f
        changeBottomTabColor(false)
    }

    /**
     * 点击第二个tab
     */
    fun clickTab2Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_TWO
        if (recommendFragment == null) {
            recommendFragment = RecommendFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), recommendFragment!!)
        tabIvLoan!!.isSelected = false
        tabIvRecommend!!.isSelected = true
//        tabIvEnjoy!!.isSelected = false
        tabIvMy!!.isSelected = false

        tabIvEnjoy!!.scaleX = 0.9f
        tabIvEnjoy!!.scaleY = 0.9f
        changeBottomTabColor(mShowBlack)
    }

    /**
     * 点击第三个tab
     */
    fun clickTab3Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_THREE
        if (vipEnjoyFragment == null) {
            vipEnjoyFragment = VipEnjoyFragment.newInstance()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), vipEnjoyFragment!!)
        tabIvLoan!!.isSelected = false
        tabIvRecommend!!.isSelected = false
//        tabIvEnjoy!!.isSelected = true
        tabIvMy!!.isSelected = false

        tabIvEnjoy!!.scaleX = 1.0f
        tabIvEnjoy!!.scaleY = 1.0f
        changeBottomTabColor(false)
    }

    /**
     * 点击第三个tab
     */
    fun clickTab4Layout() {
        AppConfig.fragmentClickFlag = Constant.FRAGMENT_CLICK_FOUR
        if (myFragment == null) {
            myFragment = MyFragment()
        }
        addOrShowFragment(supportFragmentManager.beginTransaction(), myFragment!!)
        tabIvLoan!!.isSelected = false
        tabIvRecommend!!.isSelected = false
//        tabIvEnjoy!!.isSelected = false
        tabIvMy!!.isSelected = true

        tabIvEnjoy!!.scaleX = 0.9f
        tabIvEnjoy!!.scaleY = 0.9f
        changeBottomTabColor(false)
    }

    /**
     * 添加或者显示碎片
     *
     * @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
    }

    fun backPhoneDialog() {
        phoneDialog = PhoneDialog(context, object : DialogListener() {
            override fun onClick(v: View) {
                if (!isFinishing() && phoneDialog != null && phoneDialog!!.isShowing()) {
                    phoneDialog!!.dismiss()
                }
                when (v.id) {
                    R.id.tv_phone_dialog_phone, R.id.tv_phone_dialog_phone2 -> {
                        val intent = Intent(Intent.ACTION_DIAL)
                        intent.data = Uri.parse("tel:" + "4000969950")
                        context.startActivity(intent)
                    }
                }
            }
        })
        phoneDialog!!.show()
    }

    private fun initEditView() {
        tv_full.setOnClickListener {
            recommendFragment?.apply {
                (this as RecommendFragment).fullChoice()
            }
        }
        tv_delete.setOnClickListener {
            recommendFragment?.apply {
                (this as RecommendFragment).delete()
            }
        }
    }

    fun changeRecommendTab(index: Int) {
        recommendFragment?.apply {
            (this as RecommendFragment).changeTab(index)
        }
    }

    fun showEditView(show: Boolean) {
        recommendFragment?.let {
            (it as RecommendFragment).showEditView(show)
        }
    }

    fun hideEditView(show: Boolean) {
        recommendFragment?.let {
            (it as RecommendFragment).hideEditView(show)
        }
    }

    fun showEdit(isEdit: Boolean) {
        if (isEdit) {
            ll_edit.visibility = View.VISIBLE
        } else {
            ll_edit.visibility = View.GONE
        }
    }

    fun showBlack(showBlack: Boolean) {
        this.mShowBlack = showBlack
        changeBottomTabColor(showBlack)
    }

    private fun changeBottomTabColor(showBlack: Boolean) {
        if (showBlack) {
            tabIvRecommend?.setTextColor(
                ContextCompat.getColorStateList(
                    context,
                    R.color.item_text_sel2
                )
            )
            ll_bottom_tab.background = ContextCompat.getDrawable(context, R.color.black)
        } else {
            tabIvRecommend?.setTextColor(
                ContextCompat.getColorStateList(
                    context,
                    R.color.item_text_sel
                )
            )
            ll_bottom_tab.background = ContextCompat.getDrawable(context, R.color.white)
        }
    }
}