package com.gh.gamecenter.feedback.view.suggest

import android.text.Html
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.callback.OnListClickListener
import com.gh.gamecenter.common.entity.SuggestType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.choosepic.ChoosePicAdapter
import com.gh.gamecenter.feature.selector.ChooseType
import com.gh.gamecenter.feature.selector.LocalMediaActivity
import com.gh.gamecenter.feedback.R
import com.gh.gamecenter.feedback.databinding.FragmentSuggestCopyrightBinding
import com.gh.gamecenter.feedback.entity.ContactType
import com.gh.gamecenter.feedback.utils.NewFlatLogUtils

/***
 * 意见反馈-版权申诉
 */
class SuggestCopyrightFragment : SuggestAppFragment() {
    private lateinit var mBinding: FragmentSuggestCopyrightBinding
    private var mCredentialsPicAdapter: ChoosePicAdapter? = null
    private var mAppScreenshotsAdapter: ChoosePicAdapter? = null

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View =
        FragmentSuggestCopyrightBinding.inflate(layoutInflater, null, false).apply { mBinding = this }.root

    override fun getSuggestType(): String = SuggestType.COPYRIGHT.type

    override fun initView() {
        mBinding.run {
            identityTv.text = Html.fromHtml(getString(R.string.suggestion_copyright_identity))
            credentials.titleTv.text = Html.fromHtml(getString(R.string.suggestion_copyright_credentials))
            credentials.editText.hint = "请填写身份证号或护照号"
            uploadCredentialsPic.titleTv.text = Html.fromHtml(getString(R.string.suggestion_copyright_credentials_pic))
            appName.titleTv.text = Html.fromHtml(getString(R.string.suggestion_copyright_app_name))
            appName.editText.hint = "请输入应用名"
            appScreenshots.titleTv.text = Html.fromHtml(getString(R.string.suggestion_copyright_app_screenshots))
            problemDes.titleTv.text = Html.fromHtml(getString(R.string.suggestion_problem_des))
            contact.titleTv.text = Html.fromHtml(getString(R.string.suggestion_contact))

            suggestIdentityRg.setOnCheckedChangeListener { _, checkedId ->
                if (checkedId == R.id.suggestPersonalRb) {
                    mViewModel.copyrightIdentity = SuggestViewModel.COPYRIGHT_IDENTITY_PERSON
                    credentials.editText.hint = "请填写身份证号或护照号"
                    uploadCredentialsPic.titleTv.text =
                        Html.fromHtml(getString(R.string.suggestion_copyright_credentials_pic))
                } else if (checkedId == R.id.suggestCompanyRb) {
                    mViewModel.copyrightIdentity = SuggestViewModel.COPYRIGHT_IDENTITY_COMPANY
                    credentials.editText.hint = "请填写公司营业执照或组织代码等"
                    uploadCredentialsPic.titleTv.text =
                        Html.fromHtml(getString(R.string.suggestion_copyright_company_pic))
                }
            }

            uploadCredentialsPic.run {
                picRv.layoutManager = object : LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }
                }
                mCredentialsPicAdapter = ChoosePicAdapter(requireContext(), object : OnListClickListener {
                    override fun <T : Any?> onListClick(view: View?, position: Int, data: T) {
                        PermissionHelper.checkStoragePermissionBeforeAction(requireContext()) {
                            val intent = LocalMediaActivity.getIntent(
                                requireContext(),
                                ChooseType.IMAGE,
                                1,
                                "意见反馈-${getSuggestType()}"
                            )
                            startActivityForResult(intent, MEDIA_STORE_CREDENTIALS_REQUEST)
                        }
                    }
                })
                picRv.adapter = mCredentialsPicAdapter
            }

            appScreenshots.run {
                tipsTv.visibility = View.VISIBLE
                divider.visibility = View.GONE
                picRv.layoutManager = object : LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }
                }
                mAppScreenshotsAdapter = ChoosePicAdapter(requireContext(), object : OnListClickListener {
                    override fun <T : Any?> onListClick(view: View?, position: Int, data: T) {
                        PermissionHelper.checkStoragePermissionBeforeAction(requireContext()) {
                            val intent = LocalMediaActivity.getIntent(
                                requireContext(),
                                ChooseType.IMAGE,
                                1,
                                "意见反馈-版权申诉"
                            )
                            startActivityForResult(intent, MEDIA_STORE_SCREENSHOT_REQUEST)
                        }
                    }
                })
                picRv.adapter = mAppScreenshotsAdapter
                picRv.layoutParams = (picRv.layoutParams as ConstraintLayout.LayoutParams).apply {
                    bottomMargin = 0
                }
            }

            problemDes.run {
                divider.visibility = View.VISIBLE
                editText.doOnTextChanged { text, _, _, _ ->
                    val count = text?.count { !it.isWhitespace() } ?: 0
                    problemDes.countTv.text = "${count}/300"
                }
            }

            contact.contactTv.setOnClickListener {
                showContactOptionPopup(it) { name ->
                    mViewModel.contactType = ContactType.getContactTypeByName(name)
                    contact.contactTv.text = name
                }
            }

            suggestPostBtn.setOnClickListener {
                val isCredentialsNotEmpty = credentials.editText.text.isNotEmpty()
                val isCredentialsPicNotEmpty = !mCredentialsPicAdapter?.fileList.isNullOrEmpty()
                val isAppNameNotEmpty = appName.editText.text.isNotEmpty()
                val isAppScreenshotNotEmpty = !mAppScreenshotsAdapter?.fileList.isNullOrEmpty()
                val isProblemDesNotEmpty = problemDes.editText.text.trim().isNotEmpty()
                val isContactNotEmpty = contact.contactEt.text.isNotEmpty()

                if (!isCredentialsNotEmpty) {
                    toast("请填写版权方证件")
                    return@setOnClickListener
                }

                if (!isCredentialsPicNotEmpty) {
                    val credentialsTitle =
                        if (mViewModel.copyrightIdentity == SuggestViewModel.COPYRIGHT_IDENTITY_PERSON) "证件正反面照片" else "公司或组织证件照片"
                    toast("请上传$credentialsTitle")
                    return@setOnClickListener
                }

                if (!isAppNameNotEmpty) {
                    toast("请填写侵权的应用")
                    return@setOnClickListener
                }

                if (!isAppScreenshotNotEmpty) {
                    toast("请上传侵权应用截图")
                    return@setOnClickListener
                }

                if (!isProblemDesNotEmpty) {
                    toast("请填写问题描述")
                    return@setOnClickListener
                }

                if (!isContactNotEmpty) {
                    toast("请填写联系方式")
                    return@setOnClickListener
                }

                ifLogin("意见反馈-${getSuggestType()}") {
                    NewFlatLogUtils.logFeedbackCommit(getSuggestType(), "", "")

                    val credentialsFileList = mCredentialsPicAdapter?.fileList
                    val screenshotsFileList = mAppScreenshotsAdapter?.fileList
                    if (!credentialsFileList.isNullOrEmpty() && !screenshotsFileList.isNullOrEmpty()) {
                        mViewModel.uploadPicAndPostCopyrightSuggestion(
                            credentialsFileList,
                            screenshotsFileList,
                            mPostDialog,
                            contact.contactEt.text.toString().trim(),
                            problemDes.editText.text.toString().trim(),
                            appName.editText.text.toString().trim(),
                            credentials.editText.text.toString().trim()
                        )
                    }
                }
            }
        }
    }

    override fun addFileList(requestCode: Int, path: String) {
        if (requestCode == MEDIA_STORE_CREDENTIALS_REQUEST) {
            mCredentialsPicAdapter?.addFileList(path)
        } else if (requestCode == MEDIA_STORE_SCREENSHOT_REQUEST) {
            mAppScreenshotsAdapter?.addFileList(path)
        }
    }

    override fun handleBackPressed(): Boolean {
        mBinding.run {
            if (problemDes.editText.text.isNotEmpty() ||
                !mCredentialsPicAdapter?.fileList.isNullOrEmpty() ||
                !mAppScreenshotsAdapter?.fileList.isNullOrEmpty() ||
                contact.contactEt.text.isNotEmpty() ||
                credentials.editText.text.isNotEmpty() ||
                appName.editText.text.isNotEmpty()
            ) {
                DialogHelper.showDialog(
                    requireContext(), "提示",
                    "确定放弃反馈吗？", "继续反馈", "放弃", cancelClickCallback = {
                        mIsBackConfirm = true
                        requireActivity().onBackPressed()
                    }, extraConfig = DialogHelper.Config(centerContent = true, centerTitle = true)
                )
                return true
            } else {
                return false
            }
        }
    }

    override fun onDarkModeChanged() {
        mBinding.suggestPersonalRb.background =
            if (mBinding.suggestPersonalRb.isChecked) com.gh.gamecenter.common.R.drawable.button_round_theme_alpha_10.toDrawable(requireContext()) else com.gh.gamecenter.feature.R.drawable.button_round_gray_light.toDrawable(
                requireContext()
            )
        mBinding.suggestPersonalRb.setTextColor(
            if (mBinding.suggestPersonalRb.isChecked) com.gh.gamecenter.common.R.color.text_theme.toColor(
                requireContext()
            ) else com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext())
        )
        mBinding.suggestCompanyRb.background =
            if (mBinding.suggestCompanyRb.isChecked) com.gh.gamecenter.common.R.drawable.button_round_theme_alpha_10.toDrawable(requireContext()) else com.gh.gamecenter.feature.R.drawable.button_round_gray_light.toDrawable(
                requireContext()
            )
        mBinding.suggestCompanyRb.setTextColor(
            if (mBinding.suggestCompanyRb.isChecked) com.gh.gamecenter.common.R.color.text_theme.toColor(
                requireContext()
            ) else com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext())
        )
    }
}