package com.gh.gamecenter.video.poster

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.gh.gamecenter.CropImageActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity_TabLayout
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.ActivityPosterEditBinding
import com.gh.gamecenter.entity.VideoEntity
import com.gh.gamecenter.video.poster.photo.PhotoAlbumsAdapter
import com.gh.gamecenter.video.poster.photo.PhotoAlbumsSpanner
import com.gh.gamecenter.video.poster.photo.PhotoPosterFragment
import com.gh.gamecenter.video.poster.video.VideoPosterFragment
import com.gh.gamecenter.video.upload.view.UploadVideoActivity
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.Album
import com.zhihu.matisse.internal.entity.SelectionSpec
import com.zhihu.matisse.internal.model.AlbumCollection
import java.io.File

class PosterEditActivity : BaseActivity_TabLayout(), AdapterView.OnItemSelectedListener,
    AlbumCollection.AlbumCallbacks {

    private lateinit var mBinding: ActivityPosterEditBinding

    private val mAlbumCollection = AlbumCollection()

    private lateinit var mAlbumsSpinner: PhotoAlbumsSpanner
    private lateinit var mAlbumsAdapter: PhotoAlbumsAdapter

    private lateinit var mPhotoPosterFragment: PhotoPosterFragment
    private lateinit var mVideoPosterFragment: VideoPosterFragment

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (UploadVideoActivity.REQUEST_CODE_IMAGE_CROP == requestCode && resultCode == Activity.RESULT_OK) {
            setResult(Activity.RESULT_OK, data)
            finish()
        }
    }

    override fun provideTabView(position: Int, tabTitle: String?): View {
        val tabCustomView = BaseFragment_TabLayout.createDefaultTabCustomView(this, tabTitle)
        tabCustomView.findViewById<TextView>(R.id.tab_title)
            .setTextColor(resources.getColorStateList(R.color.poster_text_tabbar_style))
        return tabCustomView
    }

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        val videoPath = intent.getStringExtra(EntranceConsts.KEY_PATH_VIDEO)
        val videoEntity = intent.getParcelableExtra<VideoEntity>(VideoEntity::class.java.simpleName)
        mPhotoPosterFragment = PhotoPosterFragment()
        mVideoPosterFragment = VideoPosterFragment.newInstance(videoPath, videoEntity)
        fragments.add(mVideoPosterFragment)
        fragments.add(mPhotoPosterFragment)
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add("视频截图")
        tabTitleList.add("相册选择")
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_poster_edit
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Matisse.from(this).choose(MimeType.ofImage()).showSingleMediaType(true)

        setNavigationTitle("编辑封面")

        initView()
        initAlbumsSpinner()
    }

    private fun initView() {
        mBinding = ActivityPosterEditBinding.bind(mContentView)

        mBinding.activityViewPager.setScrollable(false)
        mBinding.activityViewPager.addOnPageChangeListener {
            if (VIDEO_POSTER_INDEX == it) {
                setNavigationTitle("编辑封面")
                mTitleTv.removeDrawable()
            } else {
                setPhotoNavigationTitle(false)
            }
        }
        mBinding.confirm.setOnClickListener {
            val selectImagePath = getSelectImagePath()
            if (selectImagePath != null) {
                if (mBinding.activityViewPager.currentItem == 0) {
                    val data = Intent()
                    data.putExtra(CropImageActivity.RESULT_CLIP_PATH, selectImagePath)
                    setResult(Activity.RESULT_OK, data)
                    finish()
                } else {
                    val intent = CropImageActivity.getIntent(this, selectImagePath, 9 / 16F, mEntrance)
                    startActivityForResult(intent, UploadVideoActivity.REQUEST_CODE_IMAGE_CROP)
                }
            } else {
                toast("请选择图片")
            }
        }
        mTitleTv.setOnClickListener {
            setPhotoNavigationTitle(true)
            mAlbumsSpinner.show(mBinding.activityViewPager.height)
        }

        DisplayUtils.transparentStatusBar(this)
        mBaseHandler.postDelayed({
            mBinding.activityTabIndicator.generatePath(
                mBinding.activityViewPager.currentItem,
                0F
            )
        }, 10)
    }

    private fun initAlbumsSpinner() {
        mAlbumsAdapter = PhotoAlbumsAdapter(this)
        mAlbumsSpinner = PhotoAlbumsSpanner(this)

        mAlbumsSpinner.setPopupAnchorView(findViewById(R.id.normal_toolbar))
        mAlbumsSpinner.setAdapter(mAlbumsAdapter)
        mAlbumsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                mAlbumCollection.setStateCurrentSelection(position)
                mAlbumsAdapter.cursor.moveToPosition(position)
                val album = Album.valueOf(mAlbumsAdapter.cursor)
                if (album.isAll && SelectionSpec.getInstance().capture) {
                    album.addCaptureCount()
                }
                if (mPhotoPosterFragment.isAdded) {
                    mPhotoPosterFragment.loadPhotos(album)
                }
            }
        }

        mAlbumsSpinner.setDismissListener(PopupWindow.OnDismissListener {
            setPhotoNavigationTitle(false)
        })

        mAlbumCollection.onCreate(this, this)
        mAlbumCollection.loadAlbums()
    }


    private fun setPhotoNavigationTitle(up: Boolean) {
        if (mBinding.activityViewPager.currentItem == VIDEO_POSTER_INDEX) return
        mTitleTv.setDrawableEnd(if (up) R.drawable.poster_select_up else R.drawable.poster_select_down)
        mTitleTv.compoundDrawablePadding = 2F.dip2px()
        mTitleTv.text = "全部图片"
    }

    private fun getSelectImagePath(): String? {
        if (mBinding.activityViewPager.currentItem == VIDEO_POSTER_INDEX) {
            val clipPath = cacheDir.absolutePath + File.separator + System.currentTimeMillis() + ".jpg"
            mVideoPosterFragment.savePicture(clipPath)
            return clipPath
        } else {
            return mPhotoPosterFragment.getSelectImagePath()
        }
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
    }

    override fun onAlbumLoad(cursor: Cursor?) {
        mAlbumsAdapter.swapCursor(cursor)
        mBaseHandler.post {
            cursor?.moveToPosition(mAlbumCollection.currentSelection)
            val album = Album.valueOf(cursor)
            if (album.isAll && SelectionSpec.getInstance().capture) {
                album.addCaptureCount()
            }
            if (::mPhotoPosterFragment.isInitialized && mPhotoPosterFragment.isAdded) {
                mPhotoPosterFragment.loadPhotos(album)
            }
        }
    }

    override fun onAlbumReset() {
    }

    override fun provideNavigationIcon(): Int {
        return R.drawable.ic_toolbar_back_white
    }

    override fun handleBackPressed(): Boolean {
        DialogHelper.showDialog(this, "提示", "确定放弃编辑封面吗？", "确定", "暂不", { finish() })

        return true
    }

    companion object {
        private const val VIDEO_POSTER_INDEX = 0
        private const val PHOTO_POSTER_INDEX = 1

        fun getIntentByPath(context: Context, videoPath: String): Intent {
            val intent = Intent(context, PosterEditActivity::class.java)
            intent.putExtra(EntranceConsts.KEY_PATH_VIDEO, videoPath)
            return intent
        }

        fun getIntentByVideo(context: Context, videoEntity: VideoEntity): Intent {
            val intent = Intent(context, PosterEditActivity::class.java)
            intent.putExtra(VideoEntity::class.java.simpleName, videoEntity)
            return intent
        }
    }
}