package com.gh.gamecenter.personalhome.background

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.CropImageActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.common.view.GridSpacingItemColorDecoration
import com.gh.gamecenter.databinding.PersonalityBackgroundFragmentBinding
import com.gh.gamecenter.login.user.UserViewModel
import com.gh.gamecenter.qa.editor.LocalMediaActivity
import com.halo.assistant.HaloApp
import com.zhihu.matisse.Matisse

class PersonalityBackgroundFragment : ToolbarFragment() {
    private var mAdapter: PersonalityBackgroundAdapter? = null
    private lateinit var mViewModel: PersonalityBackgroundViewModel
    private lateinit var mUserViewModel: UserViewModel
    private lateinit var mBinding: PersonalityBackgroundFragmentBinding
    private var mLoadingDialog: WaitingDialogFragment? = null

    override fun getLayoutId(): Int = R.layout.personality_background_fragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = PersonalityBackgroundFragmentBinding.bind(mCachedView)
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance().application))
        mViewModel = viewModelProvider()
        mUserViewModel.editObsUserinfo.observe(this, Observer {
            mAdapter?.notifyDataSetChanged()
        })
        mViewModel.backgroundImagesLiveData.observe(this, Observer {
            mAdapter?.setListData(it)
        })
        mViewModel.loadingLiveData.observe(this, Observer {
            if (it) {
                mLoadingDialog = WaitingDialogFragment.newInstance("下载图片中...")
                mLoadingDialog?.show(childFragmentManager, null)
            } else {
                mLoadingDialog?.dismiss()
            }
        })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.recommendRv.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            mAdapter = PersonalityBackgroundAdapter(requireContext(), mViewModel)
            addItemDecoration(getItemDecoration())
            adapter = mAdapter
        }
        mBinding.uploadBackgroundLl.setOnClickListener {
            selectPic(requireActivity())
        }

    }

    private fun getItemDecoration(): RecyclerView.ItemDecoration {
        return GridSpacingItemColorDecoration(requireContext(), 8, 20, R.color.background_white)
    }

    private fun selectPic(activity: Activity) {
        PermissionHelper.checkStoragePermissionBeforeAction(activity) {
            startActivityForResult(
                LocalMediaActivity.getIntent(
                    requireContext(),
                    LocalMediaActivity.ChooseType.IMAGE,
                    1,
                    "个性背景"
                ), MEDIA_STORE_REQUEST
            )
        }
    }

    @SuppressLint("Recycle")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == MEDIA_STORE_REQUEST && resultCode == Activity.RESULT_OK) {
            val selectedPaths = Matisse.obtainPathResult(data)
            if (!selectedPaths.isNullOrEmpty()) {
                val intent = BackgroundClipActivity.getIntent(requireContext(), selectedPaths[0], mEntrance)
                startActivityForResult(intent, REQUEST_CODE_IMAGE_CROP)
            }
        } else if (requestCode == REQUEST_CODE_IMAGE_CROP && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val imagePath = data.getStringExtra(CropImageActivity.RESULT_CLIP_PATH)
                val intent = BackgroundPreviewActivity.getIntent(
                    requireContext(), imagePath
                        ?: "", null
                )
                requireActivity().startActivityForResult(intent, CHANGE_BACKGROUND_SUCCESS)
            }
        } else if (requestCode == CHANGE_BACKGROUND_SUCCESS && resultCode == Activity.RESULT_OK) {
            requireActivity().finish()
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding.recommendRv.run {
            if (itemDecorationCount > 0) {
                removeItemDecorationAt(0)
                addItemDecoration(getItemDecoration())
            }
        }
    }

    companion object {
        const val REQUEST_CODE_IMAGE_CROP = 100
        const val MEDIA_STORE_REQUEST = 101
        const val CHANGE_BACKGROUND_SUCCESS = 102
    }
}