package com.gh.gamecenter.video.videomanager

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.*
import com.gh.common.util.LogUtils
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.VideoVerifyItemBinding
import com.gh.gamecenter.entity.VideoEntity
import com.gh.gamecenter.video.VideoVerifyItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel
import com.gh.gamecenter.video.upload.view.UploadVideoActivity
import java.text.SimpleDateFormat
import java.util.*

class VideoVerifyAdapter(
    context: Context,
    private val mViewModel: VideoVerifyViewModel,
    private val mEntrance: String
) : ListAdapter<VideoEntity>(context) {

    override fun areItemsTheSame(oldItem: VideoEntity?, newItem: VideoEntity?): Boolean {
        return oldItem?.id == newItem?.id
    }

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) {
            return ItemViewType.ITEM_FOOTER
        }
        return ItemViewType.ITEM_BODY
    }

    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)
            }
            else -> {
                view = mLayoutInflater.inflate(R.layout.video_verify_item, parent, false)
                return VideoVerifyItemViewHolder(VideoVerifyItemBinding.bind(view))
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is VideoVerifyItemViewHolder) {
            val topPad = if (position == 0) 8F.dip2px() else 0
            val bottomPad = if (position == itemCount - 2) 8F.dip2px() else 0
            holder.itemView.setPadding(0, topPad, 0, bottomPad)

            val entity = mEntityList[position]
            ImageUtils.display(holder.binding.videoCover, entity.poster)
            holder.binding.videoTitle.text = entity.title

            if (entity.status == "pending") {
                holder.binding.videoStatus.setTextColor(R.color.text_FF700F.toColor())
                if (entity.audit) {
                    holder.binding.videoStatus.text = ("编辑内容审核中")
                } else {
                    holder.binding.videoStatus.text = ("审核中，" + getVerifyTimeDesc(entity.time.upload))
                }
            } else if (entity.status == "pass") {
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
                holder.binding.videoStatus.setTextColor(R.color.text_subtitleDesc.toColor())
                holder.binding.videoStatus.text = dateFormat.format(entity.time.upload * 1000)
            } else {
                VideoVerifyItemViewHolder.setVideoStatus(holder.binding.videoStatus, entity.status)
            }

            holder.itemView.setOnClickListener {
                DirectUtils.directToVideoDetail(
                    mContext,
                    entity.id,
                    VideoDetailContainerViewModel.Location.USER_UPLOADED_VIDEO.value,
                    false,
                    path = "视频投稿-已投稿"
                )
            }
            holder.binding.more.setOnClickListener {
                showMorePopWindow(holder.binding.more, entity) {
                    if (it == "编辑") {
                        PermissionHelper.checkStoragePermissionBeforeAction(mContext,
                            object : EmptyCallback {
                                override fun onCallback() {
                                    val intent = UploadVideoActivity.getIntent(mContext, entity, mEntrance, "视频投稿-已投稿")
                                    if (mContext is Activity) {
                                        (mContext as Activity).startActivityForResult(
                                            intent,
                                            VideoManagerActivity.REQUEST_CODE_VIDEO
                                        )
                                    }
                                    LogUtils.logVideoStreamingUpload("点击编辑按钮", "视频投稿-已投稿", "", "")
                                }
                            })
                    } else {
                        if (entity.status == "pending") {
                            ToastUtils.showToast("视频正在审核中")
                        } else {
                            DialogHelper.showDialog(
                                mContext,
                                "提示",
                                "视频删除后不可恢复，确定删除吗？",
                                "确定删除",
                                "暂不删除",
                                {
                                    mViewModel.deleteVideo(entity.id)
                                    LogUtils.logVideoStreamingUpload(
                                        "点击删除按钮",
                                        "视频投稿-已投稿",
                                        "",
                                        entity.id
                                    )
                                })
                        }
                    }
                }
            }
        } else if (holder is FooterViewHolder) {
            holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    // 别问为什么，具体需要请参考 https://gitlab.ghzs.com/pm/halo-app-issues/-/issues/887#note_57618 (1)
    private fun getVerifyTimeDesc(time: Long): String {
        val calendar = Calendar.getInstance()
        calendar.time = Date(time * 1000)
        val day = calendar.get(Calendar.DAY_OF_WEEK)
        val targetTime = if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
            time * 1000 + 48 * 60 * 60 * 1000
        } else {
            time * 1000 + 24 * 60 * 60 * 1000
        }

        val hourFormat = SimpleDateFormat("HH", Locale.CHINA)
        val hour = hourFormat.format(targetTime)
        if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
            return "预计后天" + hour + "点前审核完成"
        } else {
            return "预计明天" + hour + "点前审核完成"
        }
    }

    private fun showMorePopWindow(view: View, entity: VideoEntity, clickListener: (String) -> Unit) {
        val contentList = if (entity.status == "fail") arrayListOf("删除") else arrayListOf("编辑", "删除")
        val inflater = LayoutInflater.from(view.context)
        val layout = inflater.inflate(R.layout.layout_popup_container, null)
        val popupWindow = BugFixedPopupWindow(
            layout,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        val container = layout.findViewById<LinearLayout>(R.id.container)
        for (text in contentList) {
            val item = inflater.inflate(R.layout.layout_popup_option_item, container, false)
            container.addView(item)

            val hitText = item.findViewById<TextView>(R.id.hint_text)
            hitText.text = text
            if (entity.status == "pending" && text == "删除") {
                hitText.setBackgroundColor(R.color.background.toColor())
                hitText.setTextColor(R.color.text_body.toColor())
            }

            item.setOnClickListener {
                clickListener.invoke(text)
                popupWindow.dismiss()
            }
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true
        popupWindow.showAutoOrientation(view)
    }

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