package com.gh.gamecenter.qa.editor

import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.common.view.GridSpacingItemDecoration
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.databinding.FragmentLocalMediaBinding
import com.gh.gamecenter.entity.LocalVideoEntity
import com.zhihu.matisse.internal.entity.Album
import com.zhihu.matisse.internal.entity.Item
import com.zhihu.matisse.internal.model.AlbumMediaCollection
import com.zhihu.matisse.internal.model.SelectedItemCollection
import com.zhihu.matisse.internal.ui.BasePreviewActivity
import com.zhihu.matisse.internal.ui.SelectedPreviewActivity
import com.zhihu.matisse.internal.utils.PathUtils
import com.zhihu.matisse.ui.MatisseActivity

class LocalMediaFragment : BaseFragment<Any>(), AlbumMediaCollection.AlbumMediaCallbacks {
    private lateinit var mBinding: FragmentLocalMediaBinding
    private lateinit var mAdapter: LocalMediaAdapter
    private var mAlbumMediaCollection: AlbumMediaCollection? = null
    private var mChooseType = ""

    override fun getLayoutId(): Int = 0

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mChooseType = arguments?.getString(EntranceConsts.KEY_TYPE) ?: ""
//        mBinding.reuseNoneData.reuseNoneDataTv.text = "暂无数据~"
        mBinding.listRv.layoutManager = GridLayoutManager(requireContext(), 3)
        mBinding.listRv.addItemDecoration(GridSpacingItemDecoration(3, 4F.dip2px(), false))
        val maxChooseCount = arguments?.getInt(EntranceConsts.KEY_CHOOSE_MAX_COUNT, 1)
        mAdapter = LocalMediaAdapter(
            requireContext(), mChooseType, maxChooseCount
                ?: 1, mEntrance
        ) {
            mBinding.previewTv.isEnabled = it.isNotEmpty()
            mBinding.confirmTv.isEnabled = it.isNotEmpty()
            if (it.isEmpty()) {
                mBinding.previewTv.setTextColor(R.color.text_body.toColor(requireContext()))
                mBinding.confirmTv.alpha = 0.6f
            } else {
                mBinding.previewTv.setTextColor(R.color.text_subtitle.toColor(requireContext()))
                mBinding.confirmTv.alpha = 1f
            }
            mBinding.numTv.text = "(${it.size}/${mAdapter.maxChooseSize})"
        }
        mBinding.numTv.text = "(0/${mAdapter.maxChooseSize})"
        mBinding.listRv.adapter = mAdapter
        mBinding.listRefresh.isEnabled = false

        val publishContentType = if (mEntrance == "发帖子") "帖子" else if (mEntrance == "发提问帖") "提问帖" else "视频帖"
        val publishMediaType = if (mChooseType == LocalMediaActivity.ChooseType.IMAGE.value) "图片" else "视频"
        mBinding.previewTv.setOnClickListener {
            if (mChooseType == LocalMediaActivity.ChooseType.VIDEO.value) {
                val intent = PreviewVideoActivity.getIntent(requireContext(), mAdapter.getSelectedMediaList())
                requireActivity().startActivityForResult(intent, PREVIEW_VIDEO)
                NewLogUtils.logChooseMedia("click_preview", publishContentType, publishMediaType)
            } else {
                val intent = Intent(requireContext(), SelectedPreviewActivity::class.java)
                val bundle = bundleOf(
                    SelectedItemCollection.STATE_SELECTION to mAdapter.getSelectedMediaList(),
                    SelectedItemCollection.STATE_COLLECTION_TYPE to SelectedItemCollection.COLLECTION_IMAGE
                )
                intent.putExtra(BasePreviewActivity.EXTRA_DEFAULT_BUNDLE, bundle)
                startActivityForResult(intent, PREVIEW_IMAGE)
            }

        }
        mBinding.confirmTv.setOnClickListener {
            NewLogUtils.logChooseMedia("click_confirm", publishContentType, publishMediaType)
            val intent = Intent()
            if (mChooseType == LocalMediaActivity.ChooseType.VIDEO.value) {
                val localVideoList = arrayListOf<LocalVideoEntity>()
                mAdapter.getSelectedMediaList().forEach {
                    val path = PathUtils.getPath(requireContext(), it.contentUri)
                    if (path == null) {
                        toast("视频已不存在，请重新选择")
                        return@forEach
                    }
                    val id = MD5Utils.getUrlMD5(path) + System.currentTimeMillis()
                    val format = getFileFormat(it.mimeType)
                    localVideoList.add(
                        LocalVideoEntity(
                            id,
                            path,
                            contentUri = it.contentUri,
                            duration = it.duration,
                            format = format,
                            size = it.size
                        )
                    )
                }
                intent.putExtra(LocalVideoEntity::class.java.name, localVideoList)
            } else {
                val data = mAdapter.getSelectedMediaList().map { it.contentUri }.toList()
                val path = data.map { PathUtils.getPath(requireContext(), it) }.toList()
                intent.putParcelableArrayListExtra(MatisseActivity.EXTRA_RESULT_SELECTION, ArrayList<Uri>(data))
                intent.putStringArrayListExtra(MatisseActivity.EXTRA_RESULT_SELECTION_PATH, ArrayList<String>(path))
            }
            requireActivity().setResult(Activity.RESULT_OK, intent)
            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 onAlbumMediaReset() {
        mAdapter.swapCursor(null)
    }

    override fun onAlbumMediaLoad(cursor: Cursor?) {
        mAdapter.swapCursor(cursor)
        mBinding.reuseNoneData.reuseNoneData.visibility = View.GONE
        mBinding.reuseLlLoading.root.visibility = View.GONE
        mBinding.reuseNoConnection.root.visibility = View.GONE
        mBinding.listRefresh.isRefreshing = false
    }

    fun loadVideos(album: Album) {
        mAlbumMediaCollection?.onDestroy()

        mAlbumMediaCollection = AlbumMediaCollection()
        mAlbumMediaCollection?.onCreate(requireActivity(), this@LocalMediaFragment)

        mAlbumMediaCollection?.load(album)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) return
        if (requestCode == PREVIEW_IMAGE) {
            val bundleExtra = data.getBundleExtra(BasePreviewActivity.EXTRA_RESULT_BUNDLE)
            val resultApply = data.getBooleanExtra(BasePreviewActivity.EXTRA_RESULT_APPLY, false)
            val items = bundleExtra?.getParcelableArrayList<Item>(SelectedItemCollection.STATE_SELECTION)
            if (resultApply && !items.isNullOrEmpty()) {
                mAdapter.getSelectedMediaList().clear()
                mAdapter.getSelectedMediaList().addAll(items)
                mAdapter.notifyDataSetChanged()
                mBinding.numTv.text = "(${items.size}/${mAdapter.maxChooseSize})"
            }

        } else if (requestCode == PREVIEW_VIDEO) {
            requireActivity().setResult(Activity.RESULT_OK, data)
            requireActivity().finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mAlbumMediaCollection?.onDestroy()
    }

    companion object {
        const val PREVIEW_VIDEO = 100
        const val PREVIEW_IMAGE = 101
    }

}