package com.hongyegroup.cpt_parttime.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.guadou.cs_cptservices.base.activity.YYBaseVDBLoadingActivity
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.engine.toast
import com.guadou.lib_baselib.ext.bindFragment
import com.guadou.lib_baselib.ext.commContext
import com.guadou.lib_baselib.ext.gotoActivity
import com.guadou.lib_baselib.utils.CommUtils
import com.guadou.lib_baselib.utils.log.YYLogUtils
import com.guadou.lib_baselib.view.gloading.GLoadingTitleStatus
import com.guadou.lib_baselib.view.gloading.Gloading
import com.guadou.lib_baselib.view.gloading.GloadingPlaceHolderlAdapter
import com.hongyegroup.cpt_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.databinding.ActivityParttimeJobDetailBinding
import com.hongyegroup.cpt_parttime.databinding.IncludePartTimeJobDetailActivityBinding
import com.hongyegroup.cpt_parttime.mvvm.PartTimeJobDetailViewModel
import com.hongyegroup.cpt_parttime.ui.fragment.*
import com.youth.banner.indicator.CircleIndicator
import dagger.hilt.android.AndroidEntryPoint

@SuppressLint("NotifyDataSetChanged")
@AndroidEntryPoint
class PartTimeJobDetailActivity : YYBaseVDBLoadingActivity<PartTimeJobDetailViewModel, ActivityParttimeJobDetailBinding>() {

    private var mRootBinding: IncludePartTimeJobDetailActivityBinding? = null
    private val mClickProxy by lazy { ClickProxy() }
    private val titleList = mutableListOf<String>()  //TabLayot的Title
    private var mCurPagePosition = 0
    private val isFragmentShowedStatus = true

    private var mPartJobDetailFragment: PartJobDetailFragment? = null
    private var mPartJobDetailSlotsFragment: PartJobDetailSlotsFragment? = null
    private var mPartJobDetailProcessFragment: PartJobDetailProcessFragment? = null
    private var mPartJobDetailGroomingFragment: PartJobDetailGroomingFragment? = null
    private var mPartJobDetailPaymentFragment: PartJobDetailPaymentFragment? = null
    private var mPartJobDetailFaqFragment: PartJobDetailFaqFragment? = null

    companion object {
        fun startInstance() {
            commContext().gotoActivity<PartTimeJobDetailActivity>()
        }
    }

    //重新生成GLoading对象-跳动动画
    override fun generateGLoading(): Gloading.Holder {
        return Gloading.from(GloadingPlaceHolderlAdapter(R.layout.layout_placeholder_part_time_detail))
            .wrap(this, GLoadingTitleStatus(true, true, false))
            .withRetry { onGoadingRetry() }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.activity_parttime_job_detail, BR.viewModel, mViewModel)
            .addBindingParams(BR.click, mClickProxy)
    }

    override fun startObserve() {

    }

    override fun init(savedInstanceState: Bundle?) {
        initDataAndRootView()
    }

    //请求工作详情数据-并加载真正的布局
    private fun initDataAndRootView() {
        if (!mBinding.viewStubRoot.isInflate()) {
            val start1 = System.currentTimeMillis()
            mBinding.viewStubRoot.inflateAsync { view ->
                val end1 = System.currentTimeMillis()
                YYLogUtils.w("添加布局耗时：" + (end1 - start1))
                mRootBinding = DataBindingUtil.bind<IncludePartTimeJobDetailActivityBinding>(view)?.apply {
                    click = mClickProxy
                }

                initRV()
                checkView2Showed()
            }
        }

        //并发网络请求
        requestDetailData()
    }

    //这里请求网络数据完成，只展示顶部图片和标题和TabView和ViewPager
    private fun requestDetailData() {
        mViewModel.requestJobDetail().observe(this) {
            checkView2Showed()
        }
    }

    override fun onGoadingRetry() {
        requestDetailData()
    }

    //查询异步加载的布局和异步的远端数据是否已经准备就绪
    private fun checkView2Showed() {
        if (mViewModel.mPartTimeJobDetail != null && mRootBinding != null) {
            //尝试手动赋值BR
            mViewModel.testText.value = "123"
            mRootBinding?.setVariable(BR.viewModel, mViewModel)

            showStateSuccess()

            initPager(hasHow2Report = true, hasGrooming = true)
            popupData2Top()
        }
    }

    private fun popupData2Top() {
        //展示顶部的图片或者Banner
        mRootBinding?.apply {
            ivJobPhotoCover.visibility = View.GONE
            bannerEmployerImgs.visibility = View.VISIBLE
            mViewModel.mBannerImgAdapter.notifyDataSetChanged()


            //展示标题为工作标题
        }
    }

    //初始化Tab和ViewPager
    private fun initPager(hasHow2Report: Boolean, hasGrooming: Boolean) {
        titleList.clear()
        mViewModel.mFragments.clear()

        mPartJobDetailFragment = PartJobDetailFragment()
        mViewModel.mFragments.add(mPartJobDetailFragment!!)
        titleList.add("工作详情")

        mPartJobDetailSlotsFragment = PartJobDetailSlotsFragment()
        mViewModel.mFragments.add(mPartJobDetailSlotsFragment!!)
        titleList.add("更多工作")

        if (hasHow2Report) {
            mPartJobDetailProcessFragment = PartJobDetailProcessFragment()
            mViewModel.mFragments.add(mPartJobDetailProcessFragment!!)
            titleList.add("工作流程")
        }

        if (hasGrooming) {
            mPartJobDetailGroomingFragment = PartJobDetailGroomingFragment()
            mViewModel.mFragments.add(mPartJobDetailGroomingFragment!!)
            titleList.add("着装")
        }

        mPartJobDetailPaymentFragment = PartJobDetailPaymentFragment()
        mViewModel.mFragments.add(mPartJobDetailPaymentFragment!!)
        titleList.add("付款流程")

        mPartJobDetailFaqFragment = PartJobDetailFaqFragment()
        mViewModel.mFragments.add(mPartJobDetailFaqFragment!!)
        titleList.add("常见问题")

        //更新ViewPager
        mRootBinding?.viewPager?.apply {
            adapter?.notifyDataSetChanged()
            offscreenPageLimit = mViewModel.mFragments.size - 1
        }

        //自定义Tab View,自定义下划线
        mRootBinding?.tabLayout?.removeAllTabs()
        for (i in titleList.indices) {
            val tab: TabLayout.Tab? = mRootBinding?.tabLayout?.newTab()
            val view = CommUtils.inflate(R.layout.tab_job_detail_category)
            tab?.customView = view
            val text = view.findViewById<TextView>(R.id.tab_text)
            text.text = titleList[i]
            mRootBinding?.tabLayout?.addTab(tab!!)
        }

        mRootBinding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                mCurPagePosition = position
                mRootBinding?.tabLayout?.setScrollPosition(position, 0f, true)

                if (position == 0) {
                    if (isFragmentShowedStatus) {
                        mRootBinding?.flBottomBtns?.visibility = View.VISIBLE
                    }
//                    if (!CheckUtil.isEmpty(mCurrentJobDetail.getJob().work_status_describe)) {
//                        mTvCancelStatusMessage.setVisibility(View.VISIBLE)
//                    }
                } else {
                    mRootBinding?.flBottomBtns?.visibility = View.GONE
                }

                mRootBinding?.ivTabRight?.visibility = if (position == titleList.size - 1) View.GONE else View.VISIBLE

                //监听滚动，设置是否禁用截屏功能
                setScreenshotEnable(position != 2)
            }
        })

        mRootBinding?.tabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val position = tab.position
                mRootBinding?.viewPager?.setCurrentItem(position, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    //是否禁止截屏
    private fun setScreenshotEnable(enable: Boolean) {
        if (enable) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
        }
    }

    private fun initRV() {
        //设置banner图片的RV
        mRootBinding?.apply {
            bannerEmployerImgs.addBannerLifecycleObserver(this@PartTimeJobDetailActivity)
            bannerEmployerImgs.indicator = CircleIndicator(mActivity)
            bannerEmployerImgs.adapter = mViewModel.mBannerImgAdapter

            viewPager.bindFragment(supportFragmentManager, this@PartTimeJobDetailActivity.lifecycle, mViewModel.mFragments)
        }

    }

    /**
     * DataBinding事件处理
     */
    inner class ClickProxy {

        //点击申请工作
        fun applyJob() {
            toast("点击申请工作")
        }

        //点击分享工作
        fun shareJob() {
            toast("点击分享工作")
        }

        //点击Tab下一个
        fun tabNext() {
            mRootBinding?.viewPager?.setCurrentItem(mCurPagePosition + 1, true)
        }

        //去相册页面
        fun gotoGalleryPage() {
            PartJobAlbumActivity.startInstance()
        }

    }
}