package com.cheng.blzb.ui.fragment.push.subscribe.source

import android.text.TextUtils
import android.view.View
import com.cheng.blzb.R
import com.cheng.blzb.bean.SourceEntity
import com.cheng.blzb.databinding.FragmentSourceSearchBinding
import com.cheng.blzb.event.SourceDataEvent
import com.cheng.blzb.impl.TextWatcherImpl
import com.example.base.common.RxBus
import com.example.base.decoration.DividerItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.SpanUtils
import com.example.base.widget.EmptyView
import com.example.base.widget.PageStatus
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class SourceSearchFragment: BaseFragment<FragmentSourceSearchBinding, SourceSearchViewModel>() {
    private val selectedAdapter by lazy { SelectedSourceAdapter() }
    private val recommendAdapter by lazy { RecommendSourceAdapter() }
    private val resultAdapter by lazy { SearchSourceAdapter() }

    private val resultEmptyView by lazy { EmptyView(requireContext()) }

    private val textWatcher = object : TextWatcherImpl() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            super.onTextChanged(s, start, before, count)
            binding.ivClearText.visibility = if (TextUtils.isEmpty(s)) View.GONE else View.VISIBLE

            resultAdapter.setKeyword(s.toString())
            if (!TextUtils.isEmpty(s?.trim())) {
                mViewModel.search(s.toString())
                binding.layoutResult.visible()
            } else {
                binding.layoutResult.gone()
            }
        }
    }

    override fun initView() {
        super.initView()
        val layoutManager = FlexboxLayoutManager(requireContext())
        layoutManager.flexDirection = FlexDirection.ROW
        layoutManager.flexWrap = FlexWrap.WRAP
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvSelected.layoutManager = layoutManager
        binding.rvSelected.adapter = selectedAdapter

        binding.rvRecommend.adapter = recommendAdapter
        binding.rvRecommend.addItemDecoration(DividerItemDecoration(DensityUtils.dp2px(14f), DensityUtils.dp2px(14f), color = getColor(R.color.color_eeeeee)))

        binding.rvResult.adapter = resultAdapter
        resultEmptyView.setNoDataLogo(R.mipmap.ic_empty_data)
        resultEmptyView.setNoDataText("暂无数据")
        resultAdapter.setEmptyView(resultEmptyView)
    }

    override fun initData() {
        super.initData()
        mViewModel.getHotSources()

        val listStr = arguments?.getString("list")
        if (!TextUtils.isEmpty(listStr)) {
            selectedAdapter.setList(Gson().fromJson(listStr, object : TypeToken<List<SourceEntity>>() {}.type))
            if (selectedAdapter.data.isNotEmpty()) {
                SpanUtils.with(binding.tvSelectedCount)
                    .append("(")
                    .append("${selectedAdapter.data.size}")
                    .setForegroundColor(getColor(R.color.color_ff493c))
                    .append("/5)")
                    .create()
                binding.layoutSelected.visible()
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.etSearch.addTextChangedListener(textWatcher)

        binding.ivClearText.onClick {
            binding.etSearch.setText("")
        }

        binding.layoutResult.onClick {
            binding.layoutResult.gone()
        }

        recommendAdapter.setOnItemClickListener { _, _, i ->
            val item = recommendAdapter.getItem(i)
            if (selectedAdapter.data.size == 5) {
                toast("最多添加5个数据源")
                return@setOnItemClickListener
            }
            if (selectedAdapter.data.find { it.id == item.id } != null){
                toast("数据源已存在")
                return@setOnItemClickListener
            }
            selectedAdapter.addData(item)
            SpanUtils.with(binding.tvSelectedCount)
                .append("(")
                .append("${selectedAdapter.data.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()
            binding.layoutSelected.visible()
        }

        resultAdapter.setOnItemClickListener { _, _, i ->
            val item = resultAdapter.getItem(i)
            if (selectedAdapter.data.size == 5) {
                toast("最多添加5个数据源")
                return@setOnItemClickListener
            }
            if (selectedAdapter.data.find { it.id == item.id } != null){
                toast("数据源已存在")
                return@setOnItemClickListener
            }
            selectedAdapter.addData(item)
            SpanUtils.with(binding.tvSelectedCount)
                .append("(")
                .append("${selectedAdapter.data.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()
            binding.layoutSelected.visible()
            binding.layoutResult.gone()
        }

        selectedAdapter.setOnItemChildClickListener { _, view, i ->
            when(view.id) {
                R.id.iv_delete -> {
                    selectedAdapter.removeAt(i)
                    SpanUtils.with(binding.tvSelectedCount)
                        .append("(")
                        .append("${selectedAdapter.data.size}")
                        .setForegroundColor(getColor(R.color.color_ff493c))
                        .append("/5)")
                        .create()
                    if (selectedAdapter.data.isEmpty()) {
                        binding.layoutSelected.gone()
                    }
                }
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.hotLiveData.observe(this) {
            recommendAdapter.setList(it)
        }

        mViewModel.searchLiveData.observe(this) {
            resultAdapter.setList(it)
            if (it.isNotEmpty()) {
                resultEmptyView.setStatus(PageStatus.GONG)
            } else {
                resultEmptyView.setStatus(PageStatus.NO_DATA)
            }
        }
    }

    override fun onDestroyView() {
        binding.etSearch.removeTextChangedListener(textWatcher)
        super.onDestroyView()
    }

    override fun onDestroy() {
        RxBus.defaultInstance.post(SourceDataEvent(selectedAdapter.data))
        super.onDestroy()
    }
}