package com.zswc.creativity.fragment

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import cn.bingoogolapple.bgabanner.BGABanner
import coil.load
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.zswc.creativity.R
import com.zswc.creativity.adapter.FragAdapter
import com.zswc.creativity.base.MBFragment
import com.zswc.creativity.databinding.FragmentHomeFirstBinding
import com.zswc.creativity.model.HomeBanner
import com.zswc.creativity.vmodel.HomeFirstVModel
import com.tencent.mmkv.MMKV
import com.zswc.creativity.config.ConfigRx
import java.util.ArrayList

/**
 * 首页
 *Created by shihuiyun
 *on 2020/9/11
 */
class HomeFirstFragment : MBFragment<HomeFirstVModel, FragmentHomeFirstBinding>() {

    var fragments = emptyArray<Fragment>()
    private var adapter: FragAdapter? = null
    var type = 1//1精选 2预约


    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        vm.toGetBanner()
        //获取登录状态
        var token= MMKV.defaultMMKV().decodeString("token", "")
        if(token.equals("")){
            vm.isLogin.value=false
        }else{
            //登录之后访问的接口
            vm.getUserInfo()
            vm.getMessageList()
        }

        vm.bannerList.observe(this) {

            if (it.isNotEmpty()) {
                initBanner(it)
            }
            //
           binding.refreshLayout.isRefreshing=false
        }

     //   initViewPage()

        initFragments()
        switchContent(0)//默认第一个

    }


    private fun initFragments() {
        val oneFragment = RecommendFragment()
       val twoFragment = RecommendFragment()

        fragments = arrayOf(
                oneFragment,
                twoFragment
        )
    }

    private fun switchContent(index: Int) {

        val childFragmentManager: FragmentManager = childFragmentManager
        val transaction = childFragmentManager.beginTransaction()
        var fragment = childFragmentManager.findFragmentByTag("tab_$index")
        if (fragment == null) {//还未加载

            fragment = fragments[index]
            if (fragment != null) {
                transaction.add(R.id.home_container, fragment, "tab_$index")
            }
        } else {
            transaction.show(fragment)
        }
        for (i in fragments.indices) {
            fragment = childFragmentManager.findFragmentByTag("tab_$i")
            if (fragment == null || index == i) {
                continue
            }
            transaction.hide(fragment)
        }
        transaction.commitAllowingStateLoss()
    }

    override fun listeners() {
        super.listeners()
        binding.tvMyChose.setOnClickListener(View.OnClickListener { view: View? ->
            switchContent(0)
            binding.tvMyChose.setTextColor(Color.parseColor("#222222"))
            binding.tvMyAppointment.setTextColor(Color.parseColor("#888888"))

        })
        binding.tvMyAppointment.setOnClickListener(View.OnClickListener { view: View? ->
            switchContent(1)
            binding.tvMyChose.setTextColor(Color.parseColor("#888888"))
            binding.tvMyAppointment.setTextColor(Color.parseColor("#222222"))
        })

    }

//
//    fun initViewPage() {
//
//        val oneFragment = RecommendFragment()
//        val twoFragment = RecommendFragment()
//
//        fragments = arrayOf(
//                oneFragment,
//                twoFragment
//        )
//        adapter = FragAdapter(childFragmentManager, fragments.toMutableList())
//        binding.viewPager.offscreenPageLimit = 2
//        binding.viewPager.adapter = adapter
//        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
//            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
//            override fun onPageSelected(position: Int) {
//                choseType(position)
//            }
//
//            override fun onPageScrollStateChanged(state: Int) {}
//        })
//
//        binding.tvMyChose.setOnClickListener(View.OnClickListener { view: View? -> binding.viewPager.currentItem = 0 })
//        binding.tvMyAppointment.setOnClickListener(View.OnClickListener { view: View? -> binding.viewPager.currentItem = 1 })
//
//
//    }
//
//    private fun choseType(position: Int) {
//        when (position) {
//            0 -> {
//                type = 1
//                binding.tvMyChose.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
//                binding.tvMyAppointment.typeface = Typeface.DEFAULT
//
//
//            }
//            1 -> {
//                type = 2
//                binding.tvMyChose.typeface = Typeface.DEFAULT
//                binding.tvMyAppointment.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
//
//            }
//            else -> {
//            }
//        }
//    }


    fun initBanner(bean: List<HomeBanner>) {

        var list = ArrayList<String>()

        for (item in bean) {
            list.add(item.cover)
        }

        if (list.size > 1) {
            binding.banner.setAutoPlayAble(true)
        } else {
            binding.banner.setAutoPlayAble(false)
        }
        binding.banner.setAdapter(BGABanner.Adapter<CardView, String?> { banner, itemView, model, position -> //图片布局
            val simpleDraweeView = itemView.findViewById<ImageView>(R.id.sdv_item_fresco_content)
            simpleDraweeView.load(model)

        })
        binding.banner.setData(R.layout.item_fresco, list, null)
        binding.banner.setAutoPlayInterval(6000)
        binding.banner.setDelegate { banner, itemView, model, position ->

            //todo： var ad = beanlist[position]

        }

    }


    override fun vmClass(): Class<HomeFirstVModel> {
        return HomeFirstVModel::class.java
    }

    override fun binding(inflater: LayoutInflater, container: ViewGroup?): FragmentHomeFirstBinding {
        return FragmentHomeFirstBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return null
    }

    override val isRxbus: Boolean
        get() = true

    @Subscribe(tags = [Tag(ConfigRx.REFRESH_USER)])
    fun setRefreshUser(type: String) {
        vm.getUserInfo()
    }
//    @Subscribe(tags = [Tag(ConfigRx.STOP_REFRSH)])
//    fun setRefreshUser(flag: Boolean) {
//        binding.refreshLayout.isEnabled=flag
//    }
}
