package com.adealink.weparty.profile.dynamic.fragment.photo

import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.aab.util.getCompatDimensionPixelSize
import com.adealink.frame.aab.util.getCompatString
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.util.naviBarHeight
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.dialogfragment.CommonTextActionDialog
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.diffutil.BaseListDiffUtil
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.module.profile.Profile
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.setting.Setting
import com.adealink.weparty.profile.R
import com.adealink.weparty.profile.databinding.FragmentDynamicPhotoBinding
import com.adealink.weparty.profile.dynamic.adapter.DynamicCommentTitleViewBinder
import com.adealink.weparty.profile.dynamic.adapter.DynamicCommentViewBinder
import com.adealink.weparty.profile.dynamic.data.publishNewCommentLD
import com.adealink.weparty.profile.dynamic.fragment.data.BaseDynamicDetailItem
import com.adealink.weparty.profile.dynamic.fragment.data.DynamicDetailCommentItem
import com.adealink.weparty.profile.dynamic.fragment.data.DynamicDetailCommentTitleItem
import com.adealink.weparty.profile.dynamic.fragment.dialog.DynamicTalkDialog
import com.adealink.weparty.profile.dynamic.fragment.photo.adapter.DynamicPhotoHeaderViewBinder
import com.adealink.weparty.profile.dynamic.fragment.photo.viewmodel.DynamicPhotoViewModel
import com.adealink.weparty.profile.dynamic.viewmodel.DynamicViewModel
import com.adealink.weparty.util.applyImmersive
import com.adealink.weparty.util.formatNumberStr
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.adealink.weparty.R as APP_R

class PhotoDynamicFragment : BaseFragment(R.layout.fragment_dynamic_photo) {

    companion object {
        const val TAG = "PhotoDynamicFragment"
    }

    private val binding by viewBinding(FragmentDynamicPhotoBinding::bind)

    private lateinit var photoDynamicLayoutManger: LinearLayoutManager
    private val photoDynamicAdapter by fastLazy {
        MultiTypeListAdapter<BaseDynamicDetailItem>(
            BaseListDiffUtil()
        )
    }

    private val dynamicViewModel by activityViewModels<DynamicViewModel>()
    private val photoViewModel by activityViewModels<DynamicPhotoViewModel>()

    private lateinit var layoutManager: LinearLayoutManager

    private var showCommentWhenFirstEnter = false
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        showCommentWhenFirstEnter =
            activity?.intent?.getBooleanExtra(Profile.Dynamic.EXTRA_DYNAMIC_SHOW_COMMENT, false)
                ?: false
    }

    override fun initViews() {
        super.initViews()
        activity.applyImmersive { top ->
            binding.topBar.root.setPadding(
                16.dp(), top, 16.dp(), 0
            )
            binding.topBar.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
                height =
                    top + getCompatDimensionPixelSize(APP_R.dimen.common_top_bar_height)
            }
        }
        binding.topBar.ivBack.onClick {
            activity?.finish()
        }
        binding.topBar.btnMore.onClick {
            clickMore()
        }
        binding.bottomBar.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
            bottomMargin = activity.naviBarHeight()
        }
        binding.bottomBar.clTalk.onClick {
            clickTalk()
        }
        binding.bottomBar.clLike.onClick {
            clickLike()
        }
        binding.bottomBar.clComment.onClick {
            clickComment()
        }

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


            override fun onLoadMore(refreshLayout: RefreshLayout) {
                photoViewModel.loadMoreComment()
            }
        })

        photoDynamicAdapter.register(DynamicPhotoHeaderViewBinder())
        photoDynamicAdapter.register(DynamicCommentTitleViewBinder())
        photoDynamicAdapter.register(DynamicCommentViewBinder())
        binding.rvContent.adapter = photoDynamicAdapter
        layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false).also {
            photoDynamicLayoutManger = it
        }
        binding.rvContent.layoutManager = layoutManager
    }

    override fun observeViewModel() {
        super.observeViewModel()
        dynamicViewModel.dynamicDetailLD.observe(viewLifecycleOwner) {
            photoViewModel.loadItemListIfEmpty(it)

            binding.topBar.ivAvatar.setImageUrl(it.avatar)
            binding.topBar.tvUserName.text = it.nickname

            if (it.liked) {
                binding.bottomBar.ivLike.setImageResource(R.drawable.profile_dynamic_liked_ic)
            } else {
                binding.bottomBar.ivLike.setImageResource(R.drawable.profile_dynamic_like_ic)
            }
            if (it.likeCount > 0) {
                binding.bottomBar.tvLike.text = formatNumberStr(it.likeCount)
            } else {
                binding.bottomBar.tvLike.text = getCompatString(R.string.profile_dynamic_like)
            }

            if (it.commentCount > 0) {
                binding.bottomBar.tvComment.text = formatNumberStr(it.commentCount)
            } else {
                binding.bottomBar.tvComment.text = getCompatString(R.string.profile_dynamic_comment)
            }
        }
        publishNewCommentLD.observeWithoutCache(viewLifecycleOwner) {
            if (dynamicViewModel.dynamicDetailLD.value?.id == it.dynamicId) {
                dynamicViewModel.onNewComment()
                photoViewModel.onNewCommentAdd(it.comment)
            }
        }
        photoViewModel.itemListRltLD.observe(viewLifecycleOwner) { rlt ->
            binding.vRefresh.finishRefresh()
            binding.vRefresh.finishLoadMore()
            binding.vRefresh.setEnableLoadMore(photoViewModel.hasMoreData())
            showFailedToast(rlt)
        }

        var firstCommit = true
        photoViewModel.itemListLD.observe(viewLifecycleOwner) {
            photoDynamicAdapter.submitList(it, committed = {
                if (firstCommit) {
                    firstCommit = false
                    if (showCommentWhenFirstEnter) {
                        clickComment()
                    }
                }
            })
        }
    }

    private fun clickMore() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        if (detailData.uid == ProfileModule.getMyUid()) {
            CommonTextActionDialog.Builder()
                .addItem(APP_R.id.id_common_op_delete, APP_R.string.common_delete)
                .showCancel(true)
                .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                    override fun onActionClick(viewId: Int) {
                        when (viewId) {
                            APP_R.id.id_common_op_delete -> {
                                deleteDynamic()
                            }
                        }
                    }
                }).build().show(childFragmentManager)
        } else {
            CommonTextActionDialog.Builder()
                .addItem(APP_R.id.id_common_op_report, APP_R.string.common_report)
                .showCancel(true)
                .actionListener(object : CommonTextActionDialog.CommonTextActionListener {
                    override fun onActionClick(viewId: Int) {
                        when (viewId) {
                            APP_R.id.id_common_op_report -> {
                                clickReport()
                            }
                        }
                    }
                }).build().show(childFragmentManager)
        }
    }

    private fun clickReport() {
        val act = activity ?: return
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        val uid = detailData.uid
        Router.build(act, Setting.Report.PATH)
            .putExtra(Setting.Report.EXTRA_UID, uid)
            .start()
    }

    private fun deleteDynamic() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        fun deleteDynamicInner(dynamicId: String) {
            showLoading()
            dynamicViewModel.delete(dynamicId).observe(viewLifecycleOwner) { rlt ->
                dismissLoading()
                showToast(rlt)
                when (rlt) {
                    is Rlt.Failed -> {
                        //Ntd.
                    }

                    is Rlt.Success<*> -> {
                        activity?.finish()
                    }
                }
            }
        }
        CommonDialog.Builder()
            .title(getCompatString(APP_R.string.common_confirm_delete))
            .setShowDefaultCancel(true)
            .positiveText(getCompatString(APP_R.string.commonui_confirm))
            .onPositive {
                deleteDynamicInner(detailData.id)
            }
            .show(childFragmentManager, "DeleteDynamic")
    }

    private fun clickTalk() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        DynamicTalkDialog().apply {
            setDynamicId(detailData.id)
        }.show(childFragmentManager)
    }

    private fun clickLike() {
        val detailData = dynamicViewModel.dynamicDetailLD.value ?: return
        dynamicViewModel.like(detailData.id).observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    showToast(rlt)
                }

                is Rlt.Success -> {
                    //Ntd.
                }
            }
        }
    }

    private fun clickComment() {
        if (isCommentAtTop()) {
            clickTalk()
            return
        }
        scrollToComment()
    }

    private fun isCommentAtTop(): Boolean {
        val firstItemPosition = layoutManager.findFirstVisibleItemPosition()
        val firstItem = photoDynamicAdapter.getItem(firstItemPosition)
        if (firstItem is DynamicDetailCommentTitleItem || firstItem is DynamicDetailCommentItem) {
            //第一个是评论
            return true
        }

        val canScrollDown = binding.rvContent.canScrollVertically(1)
        if (!canScrollDown) {
            //不能往下滑
            return true
        }

        return false
    }

    private fun scrollToComment() {
        val itemList = photoViewModel.itemListLD.value ?: return
        val commentIndex =
            itemList.indexOfFirst { it is DynamicDetailCommentTitleItem || it is DynamicDetailCommentItem }
        if (commentIndex >= 0) {
            photoDynamicLayoutManger.scrollToPositionWithOffset(commentIndex, 0)
        }
    }

}