package com.zxhl.shop.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.bumptech.glide.Glide
import com.umeng.analytics.MobclickAgent
import com.umeng.socialize.UMShareAPI
import com.zxbw.modulemain.fragment.CashCheckFragment
import com.zxbw.modulemain.fragment.HomeFragment
import com.zxbw.modulemain.fragment.ShoppingMallFragment
import com.zxbw.modulemain.fragment.UserCenterFragment
import com.zxbw.modulemain.view.NavigationBottomView
import com.zxbw.modulemain.view.NavigationBottomView.NavifationCallback
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.ApiClient.homeApi
import com.zxhl.cms.net.ApiClient.userInfoAPi
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.model.uc.UserInfo
import com.zxhl.cms.net.model.video.HomeAdEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.ClipboardManagerUtil.getTbLink
import com.zxhl.cms.utils.EventUtils.onEvent
import com.zxhl.cms.utils.UserDataUtils.updateUserInfo
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.shop.R
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*

/**
 * Copyright @ 2018 Bitgoose All rights reserved.
 *
 * @class name: MainActivity
 * @class describe:
 * @author: fuxin
 * @date: 2019/3/15 下午2:19
 */
class MainActivity : BaseActivity(),
    NavifationCallback /*, IDialogCloseCallback, MemberContract.View*/ {
    private val fragments: MutableList<Fragment> = ArrayList()
    private var navigationView: NavigationBottomView? = null
    private var mLoading: LoadingDialog? = null
    private var mRestartLoginObservable: Observable<String>? = null
    private var mSwitchMainObservable: Observable<Int>? = null
    private var adview: ImageView? = null
    override fun layoutID(): Int {
        return R.layout.activity_main
    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    @SuppressLint("CheckResult")
    override fun init() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        getAdinfo()
        navigationView = findViewById(R.id.id_activity_main_fragment_navigation)
        adview = findViewById(R.id.id_img_fly_ad)
        adview?.setOnClickListener {
            if(!TextUtils.isEmpty(clickUrl)){
                onEvent("ad_click",""+clickid)
                JumpUtils.webJump(adName, clickUrl)
            }

        }
        initListener()
        mRestartLoginObservable =
            RxBus.get().register(Constant.REFRESH_LOGIN_STATS, String::class.java)
        mRestartLoginObservable!!.observeOn(AndroidSchedulers.mainThread())
            .subscribe({ JumpUtils.loginJump() }) { }
        initFragment()
        mSwitchMainObservable = RxBus.get().register(Constant.SWITCH_PAGE, Int::class.java)
        mSwitchMainObservable!!.observeOn(AndroidSchedulers.mainThread())
            .subscribe({ s -> switchFragment(s) }) { }
        val firstLoginApp = SettingPreference.getFirstLoginApp()
        if (firstLoginApp) {
            val userInfoData = SettingPreference.getUserInfoData()
            if (userInfoData != null && userInfoData.member != null) {
                Constant.Switch.isOpenVip = userInfoData.member
                if (!userInfoData.member) {
                    SettingPreference.setFirstLoginApp()
                    JumpUtils.OpenMember()
                }
            }
        }
    }

    private fun initListener() {
        navigationView!!.setNavifationCallback(this)
    }

    private fun initFragment() {
        fragments.add(HomeFragment())
        fragments.add(ShoppingMallFragment())
        fragments.add(CashCheckFragment())
        fragments.add(UserCenterFragment())
        val transaction = supportFragmentManager.beginTransaction()
        for (fragment in fragments) {
            transaction.add(R.id.id_activity_main_fragment_layout, fragment)
        }
        hideFragment(transaction)
        transaction.show(fragments[0]).commit()
        onEvent("tab_imp", "home")
    }

    private fun switchFragment(index: Int) {
        getAdinfo()
        val transaction = supportFragmentManager.beginTransaction()
        hideFragment(transaction)
        transaction.show(fragments[index]).commitAllowingStateLoss()
        supportFragmentManager.executePendingTransactions()
    }

    private fun switchFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragment(transaction)
        transaction.show(fragment).commit()
    }

    private fun hideFragment(transaction: FragmentTransaction) {
        for (fragment in fragments) {
            transaction.hide(fragment)
        }
    }

    override fun onClick(v: View) {}
    override fun onNavigationClick(vId: Int) {
        if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_box) {
            switchFragment(0)
            onEvent("tab_imp", "home")
        } else if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_shop) {
            switchFragment(1)
            onEvent("tab_imp", "shop")
        } else if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_cash) {
            switchFragment(2)
            onEvent("tab_imp", "cash_check")
        }
        if (vId == com.zxbw.modulemain.R.id.id_view_navigation_bottom_user) {
            switchFragment(3)
            onEvent("tab_imp", "user")
        }
    }

    private var mPrepareExit = false
    override fun onBackPressed() {
        exitBy2Click()
    }

    private fun exitBy2Click() {
        if (!mPrepareExit) {
            mPrepareExit = true // 准备退出
            Utils.showToast(this, resources.getString(R.string.nav_back_again_finish))
            navigationView!!.postDelayed({
                mPrepareExit = false // 取消退出
            }, 1500)
        } else {
            onEvent("double_exit", "双击退出")
            exitActivity()
            // closeApp();
        }
    }

    private fun exitActivity() {
        Utils.onExit(this)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
        val userInfoData = SettingPreference.getUserInfoData()
        if (userInfoData != null && userInfoData.member != null) {
            Constant.Switch.isOpenVip = userInfoData.member
        }
        getTbLink(this)
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    private fun deviceLogin() {
        userInfoAPi.deviceLogin().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<UserInfo?>() {

                override fun onSuccess(result: UserInfo?) {
                    if (result != null) {
                        SettingPreference.saveToken(result.token)
                        updateUserInfo(null)
                    }
                }

                override fun onFailure(e: Throwable, code: String, errorMsg: String) {}

            })
    }

    private fun closeApp() {
//        homeApi.closeApp().compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<Any?>() {
//                override fun onSuccess(result: Any) {
//                    exitActivity()
//                }
//
//                override fun onFailure(e: Throwable, code: String, errorMsg: String) {
//                    exitActivity()
//                }
//            })
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.get().unregister(Constant.REFRESH_LOGIN_STATS, mRestartLoginObservable!!)
        RxBus.get().unregister(Constant.SWITCH_PAGE, mSwitchMainObservable!!)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        } catch (e: Exception) {
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onSaveInstanceState(outState: Bundle) {
//        super.onSaveInstanceState(outState);
    }
    var imgUrl: String? = ""
    var clickid: String? = ""
    var clickUrl: String? = ""
    var adName:String?=""
    fun getAdinfo() {
        ApiClient.homeApi.getHomeAdInfo().compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver<List<HomeAdEntity>>() {
                override fun onSuccess(result: List<HomeAdEntity>?) {
                    if (!result.isNullOrEmpty()) {
                        for (item in result) {
                            if (item.slotName.equals("flow")) {
                                imgUrl = item.imgUrl
                                clickid = item.id
                                clickUrl = item.url
                                adName=item.title
                                Glide.with(AppContext.get()).asGif().load(imgUrl).into(adview!!)
//                    Glide.with(this).load(imgUrl)
//                        .apply(RequestOptions.bitmapTransform(CircleCrop()))
//                        .into(id_img_banner!!)

                            }

                        }
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }
}