package com.gh.gamecenter.energy.view

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.provider.ILinkDirectUtilsProvider
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.provider.IFloatingBackViewManagerProvider
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.energy.R
import com.gh.gamecenter.energy.databinding.DailyTaskItemBinding
import com.gh.gamecenter.energy.databinding.NoviceTasksItemBinding
import com.gh.gamecenter.energy.databinding.TaskBottomItemBinding
import com.gh.gamecenter.energy.databinding.TaskTitleItemBinding
import com.gh.gamecenter.energy.utils.DialogUtils
import com.gh.gamecenter.energy.utils.IntegralLogHelper
import com.gh.gamecenter.login.user.UserManager

class TaskAdapter(context: Context) : ListAdapter<TaskItemData>(context) {

    private val mEntrance = "光能中心-任务列表"
    var horizontalTaskAdapter: HorizontalTaskAdapter? = null

    override fun getItemCount(): Int {
        return if (mEntityList.isNullOrEmpty()) 0 else mEntityList.size
    }

    override fun getItemViewType(position: Int): Int {
        val item = mEntityList[position]
        return when {
            item.noviceTasks != null -> TYPE_NOVICE

            item.title != null -> TYPE_TITLE

            item.dailyTask != null -> TYPE_DAILY

            else -> TYPE_BOTTOM
        }
    }

    override fun areItemsTheSame(oldItem: TaskItemData?, newItem: TaskItemData?): Boolean {
        return when {
            oldItem?.noviceTasks != null && newItem?.noviceTasks != null -> {
                var oldIds = ""
                var newIds = ""
                oldItem.noviceTasks?.forEach { oldIds += it.taskId }
                newItem.noviceTasks?.forEach { newIds += it.taskId }
                oldIds == newIds
            }

            oldItem?.title != null && newItem?.title != null -> true

            oldItem?.dailyTask != null && newItem?.dailyTask != null -> {
                (oldItem.dailyTask?.id == newItem.dailyTask?.id && oldItem.dailyTask?.status == newItem.dailyTask?.status)
            }

            oldItem?.bottom != null && newItem?.bottom != null -> true

            else -> super.areItemsTheSame(oldItem, newItem)
        }
    }

    override fun areContentsTheSame(oldItem: TaskItemData?, newItem: TaskItemData?): Boolean {
        return when {
            oldItem?.noviceTasks != null && newItem?.noviceTasks != null -> {
                var oldIds = ""
                var newIds = ""
                oldItem.noviceTasks?.forEach { oldIds += it.taskId }
                newItem.noviceTasks?.forEach { newIds += it.taskId }
                oldIds == newIds
            }

            oldItem?.title != null && newItem?.title != null -> true

            oldItem?.dailyTask != null && newItem?.dailyTask != null -> {
                (oldItem.dailyTask?.id == newItem.dailyTask?.id && oldItem.dailyTask?.status == newItem.dailyTask?.status)
            }

            oldItem?.bottom != null && newItem?.bottom != null -> true

            else -> super.areContentsTheSame(oldItem, newItem)
        }
    }

    override fun loadChange(status: LoadStatus?) {
        if (status == LoadStatus.INIT) {
            mIsNetworkError = false
            mIsOver = false
            mIsLoading = true
            return
        } else {
            super.loadChange(status)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            ItemViewType.ITEM_FOOTER -> {
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
                FooterViewHolder(view)
            }

            TYPE_NOVICE -> NoviceTasksViewHolder(parent.toBinding())

            TYPE_TITLE -> TaskTitleViewHolder(parent.toBinding())

            TYPE_BOTTOM -> TaskBottomViewHolder(parent.toBinding())

            else -> DailyTaskViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is NoviceTasksViewHolder -> {
                val list = mEntityList[position].noviceTasks!!
                holder.binding.taskContainer.run {
                    layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
                    horizontalTaskAdapter = HorizontalTaskAdapter(context, "光能中心", list)
                    adapter = horizontalTaskAdapter
                }
            }

            is TaskTitleViewHolder -> {
                holder.binding.run {
                    val titleStr = mEntityList[position].title!!
                    topPic.setImageResource(if (titleStr == "日常任务") R.drawable.pic_daily_task_title else R.drawable.pic_fix_task_title)
                }
            }

            is DailyTaskViewHolder -> {
                val task = mEntityList[position].dailyTask ?: return
                holder.binding.run {
                    container.background = R.drawable.background_shape_white_radius_5.toDrawable(mContext)
                    taskName.setTextColor(R.color.text_title.toColor(mContext))
                    progress.setTextColor(R.color.text_subtitle.toColor(mContext))
                    taskBtn.setTextColor(R.color.text_white.toColor(mContext))
                    ImageUtils.display(taskIcon, task.icon)
                    taskName.text = task.name
                    progress.goneIf(task.isFixed)
                    progress.text = "${task.progress}/${task.quota}"

//                    if (task.isFixed) progress.text = ""

                    if (task.status == "finished") {
                        taskBtn.text = "已完成"
                        taskBtn.setBackgroundResource(R.drawable.bg_energy_task_btn_finished)
                    } else {
                        taskBtn.text = "+${task.energy}光能"
                        taskBtn.setBackgroundResource(R.drawable.bg_energy_task_btn_normal)
                    }

                    taskNotice.setOnClickListener {
                        DialogUtils.showEnergyTaskNoticeDialog(mContext, task.name, task.descr)
                    }

                    root.setOnClickListener {
                        task.run {
                            IntegralLogHelper.logTask(
                                "click_mission",
                                "光能中心",
                                taskId,
                                name,
                                if (isFixed) "常驻任务" else "日常任务"
                            )
                        }

                        mContext.ifLogin(mEntrance) {
                            when (task.status) {
                                "normal" -> {
                                    if (task.action == "enter_invite_code") {
                                        InviteCodeDialog.showInviteCodeDialog(
                                            mContext as AppCompatActivity,
                                            UserManager.getInstance().userInfoEntity?.loginMobile?.isNotEmpty()
                                                ?: false,
                                            "task_list",
                                            false,
                                            position
                                        )
                                    } else {
                                        val floatingBackViewManager = ARouter.getInstance()
                                            .build(RouteConsts.provider.floatingBackViewManager)
                                            .navigation() as? IFloatingBackViewManagerProvider
                                        floatingBackViewManager?.enableBackViewForTaskType()
                                        val directUtils =
                                            ARouter.getInstance().build(RouteConsts.provider.linkDirectUtils)
                                                .navigation() as? ILinkDirectUtilsProvider
                                        directUtils?.directToLinkPage(mContext, task.link, mEntrance, "")
                                    }
                                }

                                "limiting" -> ToastUtils.toast(R.string.limiting_tip.toResString())

//                                "finished" -> {}
                            }
                        }
                    }
                }
            }

            is TaskBottomViewHolder -> {
                holder.binding.run {
                    val isLastBottom = mEntityList[position].bottom!!
                    holder.itemView.layoutParams =
                        (holder.itemView.layoutParams as ViewGroup.MarginLayoutParams).apply {
                            val marginBottom = if (isLastBottom) 40F.dip2px() else 0
                            setMargins(16F.dip2px(), 0, 16F.dip2px(), marginBottom)
                        }
                }
            }
        }
    }

    inner class NoviceTasksViewHolder(val binding: NoviceTasksItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
    inner class TaskTitleViewHolder(val binding: TaskTitleItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
    inner class DailyTaskViewHolder(val binding: DailyTaskItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
    inner class TaskBottomViewHolder(val binding: TaskBottomItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)

    companion object {
        private const val TYPE_NOVICE = 900

        private const val TYPE_TITLE = 901

        private const val TYPE_DAILY = 902

        private const val TYPE_BOTTOM = 903
    }
}