package com.bc_chat.circle

import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.entity.Hudgens
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.MessageHelper
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.circle.activity.CircleMessageActivity
import com.bc_chat.circle.activity.SendPostingActivity
import com.bc_chat.circle.activity.UserCircleDetailsActivity
import com.bc_chat.circle.adapetr.HudgensAdapter
import com.bc_chat.circle.contract.CircleContract
import com.bc_chat.circle.fragment.DynamicFragment
import com.bc_chat.circle.presenter.CirclePresenter
import com.bc_chat.contacts.R
import com.bc_chat.contacts.databinding.FragmentCircleBinding
import com.zhaohaoting.framework.abs.AbsV4Fragment
import com.zhaohaoting.framework.abs.adapter.TabAdapter
import com.zhaohaoting.framework.abs.entity.TabTag
import com.zhaohaoting.framework.utils.ActivityUtils
import com.zhaohaoting.framework.utils.Check
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import org.jetbrains.anko.support.v4.startActivity

/**
 * author：Created by zhaohaoting on 2019/8/27
 * email：526309416@qq.com
 * desc：
 */
@Route(path = RouteConfig.CIRCLE_FRAGMENT)
class CircleFragment : AbsV4Fragment<CirclePresenter>(), Observer<String>, CircleContract.View {

    private val binding by lazy {
        rootDataBinding as FragmentCircleBinding
    }
    private var select: Int? = 0;
    private var isNewmsg: Boolean? = false;
    private var hudgensAdapter: HudgensAdapter? = null

    companion object {
        const val SEND_POSTING = 41
    }

    override fun initPresenter(): CirclePresenter? = CirclePresenter(this)

    override fun getLayoutResId(): Int = R.layout.fragment_circle

    private var tabNames: MutableList<TabTag>? = null
    private var mutableList: MutableList<DynamicFragment>? = null
    private var inflater: LayoutInflater? = null

    override fun initialize() {
        tabNames = getTabNames()
        mutableList = getFragmentList()
        inflater = LayoutInflater.from(activity)
        val tabAdapter = TabAdapter(fragmentManager, mutableList, tabNames)
        binding.viewPager.adapter = tabAdapter
        addCustomTab()
        binding.tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(binding.viewPager))
        binding.viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                binding.tabs.setScrollPosition(position, 0f, true)
                if (position == 1) {
                    val view = binding.tabs.getTabAt(1)?.customView
                    view?.findViewById<TextView>(R.id.un_read).gone()
                    MessageHelper.instance.isFllowTopic = false
                }
            }
        })
        if (isNewmsg!!) showNewMsg()
        if (select != -1) binding.viewPager.setCurrentItem(select ?: 0, true)
        presenter.loadHudgens()
        binding.tvPosting?.setOnClickListener {
            ActivityUtils.newInstance(this).navigation(SendPostingActivity::class.java, SEND_POSTING)
        }
        binding.tvCircleRefresh.setOnClickListener {
            val objectAnimator = ObjectAnimator.ofFloat(it, "rotation", 0.0f, 720f)
            objectAnimator.duration = 1500
            objectAnimator.repeatMode = ObjectAnimator.REVERSE
            objectAnimator.start()
//            it.animate().rotation(720f).rotationX(0.5f).rotation(0.5f).setDuration(1500).start()
            val dynamicFragment = mutableList?.get(binding.viewPager.currentItem)
            dynamicFragment?.refresh(true)
        }
        binding.rvHudgens.setHasFixedSize(true)
        binding.rvHudgens.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        hudgensAdapter = HudgensAdapter(activity)
        binding.rvHudgens.adapter = hudgensAdapter
        hudgensAdapter?.addOnItemClickListener { vh, position ->
            val hudgens = hudgensAdapter?.data!![position]
            ActivityUtils.newInstance(this)
                .putExtra("cuid", hudgens.uid)
                .navigation(UserCircleDetailsActivity::class.java)
        }
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FOLLOW_TOPIC, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.TOPIC_CHILD_COMMENT, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.TOPIC_COMMENT, this)
        binding.messageLayout.setOnClickListener {
            startActivity<CircleMessageActivity>()
            binding.unRead.gone()
        }
    }

    override fun setArguments(args: Bundle?) {
        if (!isStateSaved) {
            super.setArguments(args)
        }
        select = arguments?.getInt("select")
        isNewmsg = arguments?.getBoolean("new_msg", false)
        if (isAdded) {
            if (select != -1) binding.viewPager.setCurrentItem(select ?: 0, true)
            if (isNewmsg!!) showNewMsg()
        }
    }

    override fun freshUI() {
        super.freshUI()
        if (MessageHelper.instance.isNewComment || MessageHelper.instance.isChildNewComment) {
            binding.unRead.visible()
        } else {
            binding.unRead.gone()
        }
    }

    override fun onEvent(key: String?, var1: String?) {
        when (key) {
            Const.ObserverKey.FOLLOW_TOPIC -> {
                MessageHelper.instance.isFllowTopic = true
            }
            Const.ObserverKey.TOPIC_CHILD_COMMENT -> {
                MessageHelper.instance.isChildNewComment = true
            }
            Const.ObserverKey.TOPIC_COMMENT -> {
                MessageHelper.instance.isNewComment = true
            }
        }
        showNewMsg()
    }

    private fun showNewMsg() {
        if (MessageHelper.instance.isFllowTopic) {
            val view = binding.tabs.getTabAt(1)?.customView
            view?.findViewById<TextView>(R.id.un_read).visible()
        }
        if (MessageHelper.instance.isNewComment || MessageHelper.instance.isChildNewComment) {
            binding.unRead.visible()
        } else {
            binding.unRead.gone()
        }
    }

    private fun getTabNames(): MutableList<TabTag> = mutableListOf(TabTag("全部", "1"), TabTag("关注", "2"))

    private fun getFragmentList(): MutableList<DynamicFragment> {
        val mutableListOf: MutableList<DynamicFragment> = mutableListOf()
        tabNames?.map {
            mutableListOf.add(DynamicFragment.newInstance(it.id))
        }
        return mutableListOf
    }

    private fun addCustomTab() {
        tabNames?.map {
            binding.tabs.addTab(binding.tabs.newTab().setCustomView(getTabItemView(it)).setTag(it.id))
        }
    }

    private fun getTabItemView(tag: TabTag?): View {
        val view = inflater?.inflate(R.layout.circle_tab_layout, null, false)
        val tvText = view?.findViewById<TextView>(R.id.tv_text)
        val unRead = view?.findViewById<TextView>(R.id.un_read)
        tvText?.text = tag?.name
        return view!!
    }

    override fun loadHudgensSuccess(data: List<Hudgens>?) {
        if (Check.isEmpty(data)) {
            binding.hudgensLayout.visibility = View.GONE
        } else {
            binding.hudgensLayout.visibility = View.VISIBLE
            hudgensAdapter?.notifyDataChanged(data, true)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == SEND_POSTING) {
            mutableList?.map {
                if (it.isAdded) {
                    it.refresh()
                }
            }
        }
    }
}