package com.gh.gamecenter.qa.editor

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.view.SimpleDraweeView
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.CropImageActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentPreviewVideoBinding
import com.gh.gamecenter.databinding.ItemVideoSelectorBinding
import com.gh.gamecenter.entity.LocalVideoEntity
import com.gh.gamecenter.video.poster.PosterEditActivity
import com.gh.gamecenter.video.upload.view.UploadVideoActivity
import com.lightgame.adapter.BaseRecyclerAdapter
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.zhihu.matisse.internal.entity.Item
import com.zhihu.matisse.internal.utils.PathUtils

class PreviewVideoFragment : BaseFragment<Any>() {
    private lateinit var mBinding: FragmentPreviewVideoBinding
    private var mVideoItems: ArrayList<Item> = arrayListOf()
    private var mProcessingDialog: WaitingDialogFragment? = null
    private lateinit var mVideoSelectorAdapter: VideoSelectorAdapter
    private val mLocalVideoList = arrayListOf<LocalVideoEntity>()
    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View {
        mBinding = FragmentPreviewVideoBinding.inflate(LayoutInflater.from(requireContext()), null, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mVideoItems = arguments?.getParcelableArrayList<Item>(EntranceConsts.KEY_VIDEO_LIST)
            ?: arrayListOf()
        if (mVideoItems.isNotEmpty()) {
            mVideoItems.forEach {
                val path = PathUtils.getPath(requireContext(), it.contentUri)
                val id = MD5Utils.getUrlMD5(path) + System.currentTimeMillis()
                val format = getFileFormat(it.mimeType)
                val localVideoEntity = LocalVideoEntity(
                    id = id,
                    filePath = path,
                    contentUri = it.contentUri,
                    duration = it.duration,
                    format = format,
                    size = it.size
                )
                mLocalVideoList.add(localVideoEntity)
            }
            initVideo(mLocalVideoList[0])
        }
        mBinding.numTv.text = "(1/${mVideoItems.size})"
        mVideoSelectorAdapter = VideoSelectorAdapter(requireContext(), mLocalVideoList) { entity, position ->
            mBinding.videoView.release()
            mBinding.numTv.text = "(${position + 1}/${mVideoItems.size})"
            initVideo(entity)
        }
        mBinding.videoSelectorRv.adapter = mVideoSelectorAdapter
        mBinding.videoSelectorRv.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        mBinding.videoSelectorRv.addItemDecoration(
            GridSpacingItemColorDecoration(
                requireContext(),
                4,
                0,
                R.color.transparent
            )
        )
        mBinding.confirmTv.setOnClickListener {
            val intent = Intent()
            intent.putExtra(LocalVideoEntity::class.java.name, mLocalVideoList)
            requireActivity().setResult(Activity.RESULT_OK, intent)
            requireActivity().finish()
        }

        mBinding.changeCoverTv.setOnClickListener {
            val item = mVideoItems[mVideoSelectorAdapter.selectPosition]
            val intent =
                PosterEditActivity.getIntentByPath(requireContext(), PathUtils.getPath(requireContext(), item.uri))
            startActivityForResult(intent, UploadVideoActivity.REQUEST_CODE_IMAGE_CROP)
        }
        mBinding.backBtn.setOnClickListener { requireActivity().finish() }
    }

    private fun getFileFormat(mimeType: String?): String {
        var format = ""
        tryWithDefaultCatch {
            if (mimeType != null) {
                val split = mimeType.split("/")
                format = if (split.count() >= 2) {
                    split[1]
                } else {
                    mimeType
                }
            }
        }
        return format
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == UploadVideoActivity.REQUEST_CODE_IMAGE_CROP) {
            val imagePath = data.getStringExtra(CropImageActivity.RESULT_CLIP_PATH) ?: ""
            if (imagePath.isNotEmpty()) {
                uploadImage(imagePath)
            }
        }
    }

    private fun uploadImage(imagePath: String) {
        mProcessingDialog = WaitingDialogFragment.newInstance("图片上传中...", false)
        mProcessingDialog?.show(requireActivity().supportFragmentManager, WaitingDialogFragment::class.java.name)
        UploadImageUtils.uploadImage(
            UploadImageUtils.UploadType.poster,
            imagePath,
            object : UploadImageUtils.OnUploadImageListener {
                override fun onSuccess(imageUrl: String) {
                    mProcessingDialog?.dismiss()
                    mLocalVideoList[mVideoSelectorAdapter.selectPosition].poster = imageUrl
                    mBinding.videoView.updateThumb(imageUrl)
                }

                override fun onError(e: Throwable?) {
                    mProcessingDialog?.dismiss()
                    ToastUtils.showToast("上传失败")
                }

                override fun onProgress(total: Long, progress: Long) {}
            })
    }

    private fun initVideo(entity: LocalVideoEntity) {
        GSYVideoOptionBuilder()
            .setIsTouchWiget(false)
            .setUrl(entity.filePath)
            .setRotateViewAuto(false)
            .setCacheWithPlay(false)
            .setRotateWithSystem(false)
            .setReleaseWhenLossAudio(true)
            .setLooping(false)
            .setShowFullAnimation(false)
            .build(mBinding.videoView)
        if (entity.poster.isNotEmpty()) {
            mBinding.videoView.updateThumb(entity.poster)
        } else {
            mBinding.videoView.updateThumb("file:///${PathUtils.getPath(requireContext(), entity.contentUri)}")
        }
    }

    class VideoSelectorAdapter(
        context: Context,
        val localVideoList: ArrayList<LocalVideoEntity>,
        val callback: (LocalVideoEntity, Int) -> Unit
    ) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {
        var selectPosition: Int = 0
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return VideoSelectorViewHolder(
                ItemVideoSelectorBinding.inflate(
                    LayoutInflater.from(mContext),
                    parent,
                    false
                )
            )
        }

        override fun getItemCount(): Int = localVideoList.size

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is VideoSelectorViewHolder) {
                val item = localVideoList[position]
                holder.binding.previewBorder.goneIf(selectPosition != position)
                setPreviewBorder(holder.binding.preview, selectPosition == position)
                ImageUtils.display(holder.binding.preview, "file:///${PathUtils.getPath(mContext, item.contentUri)}")
                holder.binding.root.setOnClickListener {
                    selectPosition = position
                    callback.invoke(localVideoList[selectPosition], selectPosition)
                    notifyDataSetChanged()
                }
            }
        }

        private fun setPreviewBorder(view: SimpleDraweeView, isSelected: Boolean) {
            val params = RoundingParams()
            params.setBorder(
                if (isSelected) R.color.black.toColor() else R.color.transparent.toColor(),
                if (isSelected) 1f.dip2px().toFloat() else 0f
            )
            params.setCornersRadius(4f.dip2px().toFloat())
            val build = GenericDraweeHierarchyBuilder.newInstance(mContext.resources)
                .setRoundingParams(params)
                .build()
            view.hierarchy = build
        }
    }

    class VideoSelectorViewHolder(val binding: ItemVideoSelectorBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onResume()
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }
}