package com.adealink.weparty.playmate.setting

import androidx.activity.viewModels
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.itemdecoration.VerticalSpaceItemDecoration
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.module.joinus.JoinUs
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.playmate.databinding.ActivityPlaymateSkillSettingBinding
import com.adealink.weparty.playmate.setting.adapter.SkillItemViewBinder
import com.adealink.weparty.playmate.setting.data.SkillSettingItemData
import com.adealink.weparty.playmate.setting.viewmodel.SkillSettingViewModel
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModelFactory
import com.adealink.weparty.util.applyImmersive
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.adealink.weparty.R as APP_R

@RouterUri(path = [Playmate.SkillSetting.PATH], desc = "我的技能-设置")
class PlaymateSkillSettingActivity : BaseActivity() {

    private val binding by viewBinding(ActivityPlaymateSkillSettingBinding::inflate)

    private val skillAdapter by fastLazy { MultiTypeListAdapter<SkillSettingItemData>() }

    private val viewModel by viewModels<SkillSettingViewModel> { PlaymateViewModelFactory() }
    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        setContentView(binding.root)
        applyImmersive { top ->
            binding.topBar.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }
        binding.topBar.getRightView().onClick {
            goOrderSetting()
        }
        binding.btnApplySkill.onClick {
            applySkill()
        }

        binding.vRefresh.setEnableRefresh(true)
        binding.vRefresh.setEnableLoadMore(false)
        binding.vRefresh.setEnableAutoLoadMore(false)
        binding.vRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                viewModel.loadSettingList()
            }


            override fun onLoadMore(refreshLayout: RefreshLayout) {
                //
            }
        })

        skillAdapter.register(
            SkillItemViewBinder(
                goDetail = {
                    goDetail(it)
                },
                onSwitchChanged = { item, open, position ->
                    switch(item, open, position)
                }
            ))
        binding.rvSkill.adapter = skillAdapter
        binding.rvSkill.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        binding.rvSkill.addItemDecoration(
            VerticalSpaceItemDecoration(10.dp(), 0, 12.dp())
        )
    }

    override fun observeViewModel() {
        super.observeViewModel()
        viewModel.settingListRltLD.observeWithoutCache(this) { rlt ->
            binding.vRefresh.finishRefresh()
            binding.vRefresh.finishLoadMore()
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                    binding.rvSkill.gone()
                    binding.vErrorView.show(
                        errorEmptyResId = APP_R.drawable.common_net_error_ic,
                        title = APP_R.string.common_net_error
                    )
                }

                is Rlt.Success -> {

                }
            }
        }
        viewModel.settingListLD.observeWithoutCache(this) {
            skillAdapter.submitList(it)
            if (it.isNullOrEmpty()) {
                binding.rvSkill.gone()
                binding.vErrorView.show(
                    errorEmptyResId = APP_R.drawable.common_list_empty_ic,
                    title = APP_R.string.commonui_list_empty
                )
            } else {
                binding.rvSkill.show()
                binding.vErrorView.gone()
            }
        }
    }

    override fun loadData() {
        super.loadData()
        viewModel.loadSettingList()
    }

    private fun goDetail(item: SkillSettingItemData) {
        Router.build(this, Playmate.Detail.PATH)
            .putExtra(Playmate.Detail.EXTRA_PLAYMATE_ID, item.data.id)
            .start()
    }

    private fun switch(item: SkillSettingItemData, open: Boolean, position: Int) {
        showLoading()
        viewModel.openBusiness(item.data.id, open).observe(this) { rlt ->
            dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showFailedToast(rlt)
                }

                is Rlt.Success -> {
                    item.data.open = open
                    skillAdapter.notifyItemChanged(position)
                }
            }
        }
    }

    private fun goOrderSetting() {
        Router.build(this, Playmate.OrderSetting.PATH).start()

    }

    private fun applySkill() {
        val currentCategoryCodeList = viewModel.settingListLD.value?.map {
            it.data.categoryCode
        } ?: emptyList()
        Router.build(this, JoinUs.ApplySKill.PATH)
            .putExtra(
                JoinUs.ApplySKill.EXTRA_OWN_SKILL_LIST,
                arrayListOf<String>().apply {
                    addAll(currentCategoryCodeList)
                })
            .start()

    }

}