package com.gh.gamecenter.qa.video.publish

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaMetadataRetriever
import android.media.ThumbnailUtils
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import com.gh.base.BaseRichEditorActivity
import com.gh.common.util.ErrorHelper
import com.gh.common.util.NewLogUtils
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.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.entity.LocalVideoEntity
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.common.mvvm.Status
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.FragmentVideoPublishBinding
import com.gh.gamecenter.entity.ActivityLabelEntity
import com.gh.gamecenter.entity.ForumDetailEntity
import com.gh.gamecenter.entity.VideoDraftEntity
import com.gh.gamecenter.entity.VideoEntity
import com.gh.gamecenter.feature.entity.ForumVideoEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.selector.ChooseType
import com.gh.gamecenter.feature.selector.LocalMediaActivity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.qa.BbsType
import com.gh.gamecenter.qa.dialog.ChooseActivityDialogFragment
import com.gh.gamecenter.qa.dialog.ChooseForumActivity
import com.gh.gamecenter.qa.dialog.ChooseSectionDialogFragment
import com.gh.gamecenter.qa.dialog.InputUrlDialogFragment
import com.gh.gamecenter.qa.editor.GameActivity
import com.gh.gamecenter.video.upload.OnUploadListener
import com.gh.gamecenter.video.upload.UploadManager
import com.gh.gamecenter.video.upload.view.VideoFileEntity
import com.gh.gamecenter.video.videomanager.VideoDraftActivity
import com.lightgame.utils.Util_System_Keyboard
import com.therouter.TheRouter
import java.io.File

class VideoPublishFragment : ToolbarFragment(), KeyboardHeightObserver {

    private lateinit var mBinding: FragmentVideoPublishBinding
    private lateinit var mViewModel: VideoPublishViewModel
    private var mVideoFileEntity: VideoFileEntity? = null
    private lateinit var mMenuDraft: MenuItem
    private lateinit var mMenuPost: MenuItem
    private var mUpdatedPosterPath = ""
    private var mProcessingDialog: WaitingDialogFragment? = null
    private var mIsKeyBoardShow = false
    private var mKeyboardHeightProvider: KeyboardHeightProvider? = null
    private var mIsForumSelectionDisabled = false // 是否停用选择论坛/游戏
    private var mIsCommunityActivity = false //是否是活动页跳转过来的
    private var mIsChoiceCommunity = false //活动页跳转过来是否传递了论坛数据

    override fun getLayoutId(): Int = 0

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setNavigationTitle("发视频")
        initMenu(R.menu.menu_answer_post)
        mMenuDraft = getItemMenu(R.id.menu_draft)
        mMenuPost = getItemMenu(R.id.menu_answer_post)
        mViewModel = viewModelProvider()
        mViewModel.videoDraft = arguments?.getParcelable(VideoDraftEntity::class.java.simpleName)
        mViewModel.videoPatch = arguments?.getParcelable(ForumVideoEntity::class.java.simpleName)
        mViewModel.communityEntity = arguments?.getParcelable(CommunityEntity::class.java.simpleName)
        mViewModel.gameEntity = arguments?.getParcelable(GameEntity::class.java.simpleName)
        mViewModel.selectActivityLabelEntity = arguments?.getParcelable(ActivityLabelEntity::class.java.simpleName)
        mViewModel.type = arguments?.getString(BbsType::class.java.simpleName) ?: ""
        mIsForumSelectionDisabled = arguments?.getBoolean(IS_FORUM_SELECTION_DISABLED) ?: false
        mIsCommunityActivity = arguments?.getBoolean(IS_FROM_COMMUNITY_ACTIVITY) ?: false
        mIsChoiceCommunity = mIsCommunityActivity && mViewModel.communityEntity != null
        mKeyboardHeightProvider = KeyboardHeightProvider(requireActivity())
        mBinding.title.post { mKeyboardHeightProvider?.start() }
        initData()
        observeData()
        checkPostButtonEnable()

        mBinding.title.filters = arrayOf(TextHelper.getFilter(50, "标题最多50个字"))
        mBinding.title.doOnTextChanged { text, start, _, _ ->
            if (text?.contains("\n") == true) {
                mBinding.title.setText(text.toString().replace("\n", ""))
                mBinding.title.setSelection(start)
                return@doOnTextChanged
            }
            if (PatternUtils.isHasSpace(text.toString())) {
                mBinding.title.setText(PatternUtils.replaceSpace(text.toString()))
                mBinding.title.setSelection(start)
                return@doOnTextChanged
            }
            checkPostButtonEnable()
        }
        mBinding.videoDes.doOnTextChanged { _, _, _, _ ->
            checkPostButtonEnable()
        }

        mBinding.uploadButton.setOnClickListener {
            checkStoragePermissionBeforeAction {
                startActivityForResult(
                    LocalMediaActivity.getIntent(
                        requireContext(),
                        ChooseType.VIDEO,
                        1,
                        "发视频帖"
                    ), BaseRichEditorActivity.INSERT_MEDIA_VIDEO_CODE
                )
                NewLogUtils.logChooseMedia("view_media", "视频帖", "视频")
            }
        }
        mBinding.videoPosterPatchHint.setOnClickListener { startMediaStore() }
        mBinding.forumContainer.setOnClickListener {
            if (mIsCommunityActivity && mIsChoiceCommunity && mViewModel.type == BbsType.GAME_BBS.value) {
                ToastUtils.showToast("当前活动不支持修改论坛噢~")
                return@setOnClickListener
            }
            showSelectGameDialog()
        }
        mBinding.chooseActivityContainer.setOnClickListener {
            if (mViewModel.communityEntity == null || mViewModel.communityEntity?.id?.isEmpty() == true) {
                toast("请先选择论坛")
                showSelectGameDialog()
                return@setOnClickListener
            }
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(requireActivity())
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay({
                ChooseActivityDialogFragment.show(
                    requireActivity() as AppCompatActivity,
                    ChooseActivityDialogFragment.ActivityLabelLocation.BBS_VIDEO,
                    mViewModel.communityEntity?.id ?: "",
                    mViewModel.selectActivityLabelEntity?.id,
                    tag ?: ""
                )
            }, delayTime)
        }
        mBinding.deleteVideoIv.setOnClickListener {
            DialogHelper.showDialog(requireContext(), "提示", "确定删除吗？", "确定", "取消", {
                mVideoFileEntity = null
                resetUI()
            })
        }
        mBinding.originalTv.setOnClickListener {
            if (mBinding.originalTv.isChecked) {
                mBinding.originalTv.isChecked = false
            } else {
                switchVideoSource(true)
            }
        }
        mBinding.reprintTv.setOnClickListener {
            if (mBinding.reprintTv.isChecked) {
                mBinding.reprintTv.isChecked = false
                mBinding.reprintUrlTv.visibility = View.GONE
            } else {
                switchVideoSource(false)
            }
        }
        mBinding.reprintUrlTv.setOnClickListener {
            InputUrlDialogFragment.show(
                requireActivity() as AppCompatActivity,
                mBinding.reprintUrlTv.text.toString(),
                tag ?: ""
            )
        }
        mBinding.sectionName.setOnClickListener {
            val delayTime = if (mIsKeyBoardShow) {
                Util_System_Keyboard.hideSoftKeyboard(requireActivity())
                200L
            } else 0L
            AppExecutor.uiExecutor.executeWithDelay({
                ChooseSectionDialogFragment.show(
                    requireActivity() as AppCompatActivity,
                    mViewModel.communityEntity?.id ?: "",
                    mViewModel.selectSection?.id ?: "",
                    mViewModel.isModerator,
                    tag ?: ""
                )
            }, delayTime)
        }
        mBinding.clearIv.setOnClickListener {
            setSectionUI(true)
            mViewModel.selectSection = null
        }

        val bbsType = if (mViewModel.communityEntity?.type == "official_bbs") "综合论坛" else "游戏论坛"
        SensorsBridge.trackEvent(
            "ViewPostArticle",
            "source_entrance",
            mEntrance,
            "article_type",
            "视频贴",
            "bbs_type",
            bbsType,
            "bbs_id",
            mViewModel.communityEntity?.id ?: ""
        )
    }

    private fun showSelectGameDialog() {
        if (mViewModel.type == BbsType.OFFICIAL_BBS.value && mViewModel.communityEntity != null) {
            startActivityForResult(
                GameActivity.getIntent(
                    requireContext(),
                    GameActivity.SELECT_GAME_TITLE
                ), REQUEST_GAME_CODE
            )
        } else {
            ChooseForumActivity.startChooseForumActivity(requireActivity(), "社区")
            NewLogUtils.logChooseForumPanelEnter("发视频帖")
        }
    }

    private fun getCallBack(): (url: String) -> Unit {
        return {
            mBinding.reprintUrlTv.text = it
        }
    }

    private fun getChooseSelectCallback(): (entity: ActivityLabelEntity?) -> Unit {
        return {
            mViewModel.selectActivityLabelEntity = it
            mBinding.activityTv.text = it?.name ?: "添加话题标签"
            mBinding.activityTv.setTextColor(
                if (it != null) com.gh.gamecenter.common.R.color.text_FA8500.toColor(requireContext()) else com.gh.gamecenter.common.R.color.text_primary.toColor(
                    requireContext()
                )
            )
        }
    }

    private fun initData() {
        val videoPatch = mViewModel.videoPatch
        val videoDraft = mViewModel.videoDraft
        when {
            videoPatch != null -> {
                setNavigationTitle("编辑视频")
                setVideoPatch(videoPatch)
            }

            videoDraft != null -> {
                setNavigationTitle("发视频")
                setVideoDraft()
            }

            else -> {
                setNavigationTitle("发视频")
                if (mViewModel.communityEntity != null) {
                    setForumName()
                    resetSection()
                    if (mIsForumSelectionDisabled && mViewModel.type == BbsType.GAME_BBS.value) {
                        mBinding.forumContainer.isEnabled = false
                    }
                }
                if (mViewModel.selectActivityLabelEntity != null) {
                    mBinding.activityTv.text = mViewModel.selectActivityLabelEntity?.name ?: ""
                    mBinding.activityTv.setTextColor(
                        if (mViewModel.selectActivityLabelEntity != null) com.gh.gamecenter.common.R.color.text_FA8500.toColor(
                            requireContext()
                        ) else com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext())
                    )
                }

                if (requireContext().checkCallingOrSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED
                ) {
                    startActivityForResult(
                        LocalMediaActivity.getIntent(
                            requireContext(),
                            ChooseType.VIDEO,
                            1,
                            "发视频帖"
                        ), BaseRichEditorActivity.INSERT_MEDIA_VIDEO_CODE
                    )
                }
            }
        }
    }

    private fun observeData() {
        mViewModel.processDialog.observeNonNull(this) {
            if (it.isShow) {
                if (mProcessingDialog?.dialog?.isShowing == true) {
                    mProcessingDialog?.uploadWaitingHint(it.msg)
                } else {
                    mProcessingDialog = WaitingDialogFragment.newInstance(it.msg, false)
                    mProcessingDialog?.show(childFragmentManager, null)
                }
            } else {
                mProcessingDialog?.dismiss()
            }
        }
        mViewModel.postDraftLiveData.observeNonNull(this) {
            if (it.status == Status.SUCCESS) {
                toast("保存成功")
                requireActivity().finish()
            } else if (it.status == Status.ERROR) {
                ErrorHelper.handleError(
                    requireContext(),
                    it.exception?.response()?.errorBody()?.string()
                )
            }
        }
        mViewModel.postLiveData.observeNonNull(this) {
            if (it.status == Status.SUCCESS) {
                toast("提交成功，审核通过即可生效")
                val data = it.data
                val intent = Intent()
                data?.title = mBinding.title.text.toString()
                data?.des = mBinding.videoDes.text.toString()
                intent.putExtra(ForumVideoEntity::class.java.simpleName, data)
                requireActivity().setResult(Activity.RESULT_OK, intent)
                requireActivity().finish()
                AppExecutor.uiExecutor.executeWithDelay(Runnable {
                    NotificationHelper.showNotificationHintDialog(NotificationUgc.VIDEO)
                }, 1000)
                UploadManager.deleteUploadData(mVideoFileEntity?.path)
            } else if (it.status == Status.ERROR) {
                ErrorHelper.handleError(
                    requireContext(),
                    it.exception?.response()?.errorBody()?.string(),
                    false,
                    "发帖子（视频）",
                    "社区实名",
                    "视频贴"
                ) {
                    if (::mMenuPost.isInitialized) {
                        onMenuItemClick(mMenuPost)
                    }
                }
            }
        }
        mViewModel.sectionListLiveData.observeNonNull(this) {
            mBinding.arrowIv.goneIf(it.isEmpty())
            mBinding.sectionContainer.goneIf(it.isEmpty())
        }
    }

    private fun switchVideoSource(isOriginal: Boolean) {
        mBinding.originalTv.isChecked = isOriginal
        mBinding.reprintTv.isChecked = !isOriginal
        mBinding.reprintUrlTv.goneIf(isOriginal)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null || resultCode != Activity.RESULT_OK) return
        if (requestCode == BaseRichEditorActivity.INSERT_MEDIA_VIDEO_CODE) {
            val localVideoList =
                data.getParcelableArrayListExtra<LocalVideoEntity>(LocalVideoEntity::class.java.name)
                    ?: arrayListOf()
            if (localVideoList.isNotEmpty()) {
                initUpload(localVideoList[0].filePath, localVideoList[0].poster)
            }
        } else if (requestCode == REQUEST_CODE_IMAGE_CROP) {
            val imagePath = data.getStringExtra(CropImageActivity.RESULT_CLIP_PATH)
            mBinding.videoPoster.setImageURI("file://$imagePath")
            mUpdatedPosterPath = imagePath ?: ""
        } else if (requestCode == ChooseForumActivity.CHOOSE_FORUM_REQUEST) {
            val community = data.getParcelableExtra<CommunityEntity>(EntranceConsts.KEY_COMMUNITY_DATA)
            mViewModel.communityEntity = community
            mViewModel.type = community?.type ?: ""
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mViewModel.gameEntity = null
            }
            setForumName()
            resetSection()
        } else if (requestCode == REQUEST_GAME_CODE) {
            val game = data.getParcelableExtra<GameEntity>(GameEntity::class.java.simpleName)
            if (game != null) {
                mViewModel.gameEntity = game
                setForumName()
            }
        } else if (requestCode == REQUEST_CHOOSE_DRAFT) {
            val draftEntity =
                data.getParcelableExtra<VideoDraftEntity>(VideoDraftEntity::class.java.simpleName)
            if (draftEntity != null) {
                mViewModel.videoDraft = draftEntity
                setVideoDraft()
            }
        } else if (requestCode == ChooseActivityDialogFragment.REQUEST_CODE) {
            getChooseSelectCallback().invoke(data.getParcelableExtra(EntranceConsts.KEY_DATA))
        } else if (requestCode == InputUrlDialogFragment.REQUEST_CODE) {
            getCallBack().invoke(data.getStringExtra(EntranceConsts.KEY_DATA) ?: "")
        } else if (requestCode == ChooseSectionDialogFragment.REQUEST_CODE) {
            data.getParcelableExtra<ForumDetailEntity.Section>(EntranceConsts.KEY_DATA)?.let {
                mBinding.sectionName.text = it.name
                mViewModel.selectSection = it
                setSectionUI(false)
            }
        }
    }

    private fun setVideoPatch(videoPatch: ForumVideoEntity) {
        mMenuDraft.isVisible = false
        mViewModel.type = videoPatch.type
        mViewModel.gameEntity = videoPatch.game
        mViewModel.communityEntity = videoPatch.bbs
        mViewModel.communityEntity?.icon = mViewModel.gameEntity?.icon
        mViewModel.communityEntity?.iconSubscript = mViewModel.gameEntity?.iconSubscript
        mBinding.forumContainer.isEnabled = false
        mBinding.sectionName.isEnabled = false
        mBinding.clearIv.isEnabled = false
        mBinding.deleteVideoIv.visibility = View.GONE
        mBinding.title.setText(videoPatch.title)
        mBinding.videoDes.setText(videoPatch.des)
        mBinding.activityTv.text = videoPatch.tagActivityName
        mBinding.chooseActivityContainer.isEnabled = false
        ImageUtils.display(mBinding.videoPoster, videoPatch.poster)
        mBinding.originalTv.isEnabled = false
        mBinding.reprintTv.isEnabled = false
        if (videoPatch.original == "yes") {
            switchVideoSource(true)
        } else if (videoPatch.original == "no") {
            switchVideoSource(false)
            mBinding.reprintUrlTv.text = videoPatch.source
            mBinding.reprintUrlTv.isEnabled = false
        }
        if (mVideoFileEntity == null) {
            mVideoFileEntity = VideoFileEntity(
                "",
                videoPatch.url,
                videoPatch.poster,
                videoPatch.length,
                videoPatch.length,
                videoPatch.format
            )
        }
        handleUploadSuccess(videoPatch.url)
        mBinding.deleteVideoIv.visibility = View.GONE
        setForumName()
        resetSection()
    }

    private fun setVideoDraft() {
        mViewModel.videoDraft?.let {
            if (it.bbsId.isNotEmpty() && it.game != null) {
                mViewModel.communityEntity = CommunityEntity(
                    it.bbsId, it.game?.name ?: "", icon = it.game?.icon, iconSubscript = it.game?.iconSubscript
                )
                mViewModel.gameEntity = it.game
            }
            mViewModel.gameEntity = it.game
            mViewModel.type = it.type
            mBinding.title.setText(it.title)
            mBinding.videoDes.setText(it.des)
            if (it.tagActivityId.isNotEmpty() && it.tagActivityName.isNotEmpty()) {
                mBinding.activityTv.text = it.tagActivityName
                mBinding.activityTv.setTextColor(com.gh.gamecenter.common.R.color.text_FA8500.toColor())
                mViewModel.selectActivityLabelEntity =
                    ActivityLabelEntity(it.tagActivityId, it.tagActivityName)
            }
            if (it.url.isNotEmpty()) {
                ImageUtils.display(mBinding.videoPoster, it.poster)
                handleUploadSuccess(it.url)
            }
            if (it.original == "yes") {
                switchVideoSource(true)
            } else if (it.original == "no") {
                switchVideoSource(false)
                mBinding.reprintUrlTv.text = it.source
            }
            initUpload(it.localPath, it.poster)
            setForumName()
            resetSection()
        }
    }

    private fun initUpload(videoPath: String?, poster: String) {
        if (videoPath == null || !File(videoPath).exists()) {
            handleFileNotFound()
            return
        }
        if (poster.isNotEmpty()) {
            ImageUtils.display(mBinding.videoPoster, poster)
        } else {
            val thumbnail = ThumbnailUtils.createVideoThumbnail(
                videoPath,
                MediaStore.Images.Thumbnails.MINI_KIND
            )
            mBinding.videoPoster.setImageBitmap(thumbnail)
        }

        mBinding.uploadButton.visibility = View.GONE
        mBinding.videoPosterMask.visibility = View.GONE
        mBinding.pauseButton.setOnClickListener {
            when {
                UploadManager.isUploading(videoPath) -> {
                    mBinding.uploadStatus.text = "上传已暂停"
                    mBinding.uploadInfoContainer.visibility = View.VISIBLE
                    mBinding.uploadSpeed.visibility = View.GONE
                    mBinding.pauseButton.setImageResource(R.drawable.upload_resume)
                    mBinding.pauseButton.visibility = View.VISIBLE
                    UploadManager.cancelTask(videoPath)
                }

                File(videoPath).exists() -> {
                    mBinding.uploadStatus.text = "视频上传中..."
                    mBinding.uploadInfoContainer.visibility = View.VISIBLE
                    mBinding.pauseButton.setImageResource(R.drawable.upload_pause)
                    mBinding.pauseButton.visibility = View.VISIBLE
                    createUploadTask(videoPath)
                }

                else -> {
                    handleFileNotFound()
                    toast("上传失败，视频文件不存在")
                }
            }
        }
        val videoFile = File(videoPath)
        val retriever = MediaMetadataRetriever()
        val fileUri = Uri.fromFile(videoFile)
        retriever.setDataSource(requireContext(), fileUri)
        val time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) ?: "0"
        val timeInSecond = java.lang.Long.parseLong(time) / 1000
        retriever.release()

        var format = ""
        tryWithDefaultCatch {
            val mimeType = FileUtils.getFileMimeType(requireContext(), videoPath)
            if (mimeType != null) {
                val split = mimeType.split("/")
                format = if (split.count() >= 2) {
                    split[1]
                } else {
                    mimeType
                }
            }
        }

        mVideoFileEntity = VideoFileEntity(videoPath, null, poster, timeInSecond, videoFile.length(), format)
        createUploadTask(videoPath)
    }

    private fun createUploadTask(videoPath: String) {
        mBinding.uploadStatus.text = "视频上传中..."
        UploadManager.createUploadTask(videoPath, object : OnUploadListener {
            override fun onProgressChanged(
                uploadFilePath: String,
                currentSize: Long,
                totalSize: Long,
                speed: Long
            ) {
                mBaseHandler.post {
                    mBinding.uploadInfoContainer.visibility = View.VISIBLE
                    mBinding.uploadStatus.text = "视频上传中..."
                    mBinding.uploadSpeed.visibility = View.VISIBLE
                    mBinding.pauseButton.visibility = View.VISIBLE
                    mBinding.uploadSpeed.text = "${SpeedUtils.getSpeed(speed)}预计还需${
                        SpeedUtils.getRemainTime(
                            totalSize,
                            currentSize,
                            speed
                        )
                    }"
                    mBinding.uploadProgress.update(((360 * currentSize) / totalSize).toInt(), "")
                }
            }

            override fun onUploadSuccess(uploadFilePath: String, url: String) {
                runOnUiThread {
                    handleUploadSuccess(url)
                }
            }

            override fun onUploadFailure(uploadFilePath: String, errorMsg: String) {
                runOnUiThread {
                    if (!File(uploadFilePath).exists()) {
                        handleFileNotFound()
                        toast("上传失败，视频文件不存在")
                    } else {
                        mBinding.uploadStatus.text = "网络错误，中断上传 $errorMsg"
                        mBinding.pauseButton.setImageResource(R.drawable.upload_resume)
                        mBinding.pauseButton.visibility = View.VISIBLE
                        toast("网络错误，请检查网络正常后再重试 $errorMsg")
                    }
                    mBinding.uploadSpeed.visibility = View.GONE
                }
            }
        })
    }

    private fun handleFileNotFound() {
        mBinding.uploadButton.visibility = View.VISIBLE
        mBinding.uploadInfoContainer.visibility = View.GONE
        mBinding.videoPosterMask.visibility = View.VISIBLE
    }

    private fun handleUploadSuccess(url: String) {
        mBinding.uploadButton.visibility = View.GONE
        mBinding.uploadInfoContainer.visibility = View.GONE
        mBinding.videoPosterMask.visibility = View.GONE
        mBinding.videoPosterPatchHint.visibility = View.VISIBLE
        mBinding.deleteVideoIv.visibility = View.VISIBLE
        mBinding.uploadProgress.update(360, "")
        mVideoFileEntity?.url = url
        checkPostButtonEnable()
    }

    private fun resetUI() {
        mBinding.deleteVideoIv.visibility = View.GONE
        mBinding.uploadButton.visibility = View.VISIBLE
        mBinding.videoPosterMask.visibility = View.VISIBLE
        mBinding.uploadInfoContainer.visibility = View.GONE
        mBinding.videoPosterPatchHint.visibility = View.GONE
        checkPostButtonEnable()
    }

    private fun setForumName() {
        if (mViewModel.communityEntity != null) {
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mBinding.chooseForumTv.text = mViewModel.communityEntity?.name
                mBinding.forumIconView.displayGameIcon(
                    mViewModel.communityEntity?.icon,
                    mViewModel.communityEntity?.iconSubscript
                )
                setForumUI()
            } else if (mViewModel.type == BbsType.OFFICIAL_BBS.value) {
                if (mViewModel.gameEntity == null) {
                    mBinding.chooseForumTv.text = "选择游戏"
                    mBinding.forumIconView.visibility = View.GONE
                } else {
                    mBinding.chooseForumTv.text = mViewModel.gameEntity?.name
                    mBinding.forumIconView.displayGameIcon(
                        mViewModel.gameEntity?.icon,
                        mViewModel.gameEntity?.iconSubscript
                    )
                    setForumUI()
                }
            }
        } else {
            if (mViewModel.type == BbsType.GAME_BBS.value) {
                mBinding.chooseForumTv.text = "选择论坛"
            } else if (mViewModel.type == BbsType.OFFICIAL_BBS.value) {
                mBinding.chooseForumTv.text = "选择游戏"
            }
        }
        checkPostButtonEnable()
    }

    private fun setForumUI() {
        mBinding.forumIconView.visibility = View.VISIBLE
        mBinding.forumContainer.background =
            com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(requireContext())
        mBinding.chooseForumTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext()))
    }

    private fun setSectionUI(isEmpty: Boolean) {
        mBinding.run {
            sectionContainer.background =
                if (isEmpty) R.drawable.button_round_primary_light.toDrawable(requireContext()) else com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(
                    requireContext()
                )
            sectionName.setTextColor(
                if (isEmpty) com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()) else com.gh.gamecenter.common.R.color.text_secondary.toColor(
                    requireContext()
                )
            )
            clearIv.goneIf(isEmpty)
            if (isEmpty) sectionName.text = "选择子版块"
        }
    }

    private fun resetSection() {
        mBinding.clearIv.performClick()
        mViewModel.communityEntity?.id?.let {
            mViewModel.getForumSections(it)
            mViewModel.getModeratorsInfo(it)
        }
    }

    private fun checkPostButtonEnable() {
        mMenuPost.actionView?.postDelayed({
            val isEnabled = checkData()
            mMenuPost.actionView?.alpha = if (isEnabled) 1f else 0.6f
        }, 100)
    }

    private fun checkData(): Boolean {
        val title = mBinding.title.text.toString()
        val des = mBinding.videoDes.text.toString()
        if (mVideoFileEntity?.url.isNullOrEmpty()) return false
        if (mViewModel.videoPatch == null && mViewModel.communityEntity == null) return false
        if (title.isEmpty()) return false
        if (mViewModel.videoPatch != null && mViewModel.videoPatch?.title == title && mViewModel.videoPatch?.des == des) return false
        return true
    }

    override fun onMenuItemClick(menuItem: MenuItem?) {
        super.onMenuItemClick(menuItem)
        when (menuItem?.itemId) {
            R.id.menu_answer_post -> {
                debounceActionWithInterval(R.id.menu_answer_post, 3000L) {
                    logButtonClick("click_video_post_button")

                    val bbsType = if (mViewModel.communityEntity?.type == "official_bbs") "综合论坛" else "游戏论坛"
                    SensorsBridge.trackEvent(
                        "ArticlePostClick",
                        "bbs_id",
                        mViewModel.communityEntity?.id ?: "",
                        "bbs_type",
                        bbsType,
                        "activity_tag",
                        mViewModel.selectActivityLabelEntity?.name ?: "",
                        "article_type",
                        "视频贴"
                    )

                    verifyData(false)
                }
            }

            R.id.menu_draft -> {
                NewLogUtils.logVideoDraftClick()
                startActivityForResult(
                    VideoDraftActivity.getIntent(requireContext()),
                    REQUEST_CHOOSE_DRAFT
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(this)
    }

    override fun onPause() {
        super.onPause()
        mKeyboardHeightProvider?.setKeyboardHeightObserver(null)
    }

    override fun onKeyboardHeightChanged(height: Int, orientation: Int) {
        mIsKeyBoardShow = height > 0
    }

    private fun startMediaStore() {
        try {
            PermissionHelper.checkStoragePermissionBeforeAction(requireContext()) {
                val postcard = TheRouter.build(RouteConsts.activity.videoCoverEditActivity)
                when {
                    mVideoFileEntity?.url?.isNotEmpty() == true -> {
                        val videoEntity = VideoEntity(
                            length = mVideoFileEntity?.length ?: 0, url = mVideoFileEntity?.url ?: ""
                        )
                        postcard.withParcelable(EntranceConsts.KEY_VIDEO_ENTITY, videoEntity)
                    }

                    mVideoFileEntity?.path?.isNotEmpty() == true -> {
                        postcard.withString(EntranceConsts.KEY_PATH_VIDEO, mVideoFileEntity?.url ?: "")
                    }

                    else -> {
                        throwExceptionInDebug("video not found")
                    }
                }
                postcard.navigation(requireActivity(), REQUEST_CODE_IMAGE_CROP)
            }
        } catch (e: Exception) {
            toast(R.string.media_image_hint)
            e.printStackTrace()
        }
    }

    override fun onBackPressed(): Boolean {
        logButtonClick("click_video_cancel")
        if (TextUtils.isEmpty(UserManager.getInstance().token)) return false

        if (mViewModel.videoPatch == null && mViewModel.videoDraft == null) {
            if (mBinding.title.text.isNotEmpty() || mBinding.videoDes.text.isNotEmpty()) {
                SensorsBridge.trackEvent("ArticleCancelDialogShow")
                DialogHelper.showDialog(
                    requireContext(),
                    "提示",
                    "是否保存内容再退出？",
                    cancelText = "不保存",
                    confirmText = "保存并退出",
                    cancelClickCallback = {
                        SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "不保存")
                        requireActivity().finish()
                    },
                    confirmClickCallback = {
                        SensorsBridge.trackEvent("ArticleCancelDialogClick", "button_name", "保存并退出")
                        verifyData(true)
                    },
                    extraConfig = DialogHelper.Config(
                        showCloseIcon = true,
                        centerContent = true,
                        centerTitle = true
                    )
                )
                return true
            }
        }

        if (mViewModel.videoPatch != null && mViewModel.videoDraft == null) {
            return if (mViewModel.videoPatch?.title != mBinding.title.text.toString() ||
                mViewModel.videoPatch?.des != mBinding.videoDes.text.toString()
            ) {
                showBackDialog()
                true
            } else false

        }

        return checkDraft()
    }

    private fun logButtonClick(event: String) {
        val bbsType =
            if (mViewModel.type.isNotEmpty()) if (mViewModel.type == "game_bbs") "游戏论坛" else "综合论坛" else ""
        val originalType = if (mBinding.originalTv.isChecked && !mBinding.reprintTv.isChecked) {
            "原创"
        } else if (!mBinding.originalTv.isChecked && mBinding.reprintTv.isChecked) {
            "转载"
        } else {
            "未勾选"
        }
        NewLogUtils.logPublishVideoClick(
            event, mViewModel.communityEntity?.id
                ?: "", bbsType, mViewModel.selectActivityLabelEntity?.name
                ?: "", mBinding.videoDes.text.toString().count(), originalType
        )
    }

    private fun checkDraft(): Boolean {
        if (mViewModel.videoDraft != null && (mViewModel.videoDraft?.title != mBinding.title.text.toString()
                    || mViewModel.videoDraft?.des != mBinding.videoDes.text.toString())
        ) {
            showBackDialog()
            return true
        }
        return false
    }

    private fun showBackDialog() {
        DialogHelper.showDialog(
            requireContext(),
            "提示",
            "是否保存修改内容用于下次编辑？",
            cancelText = "不保存",
            confirmText = "保存并退出",
            cancelClickCallback = { requireActivity().finish() },
            confirmClickCallback = { verifyData(true) },
            extraConfig = DialogHelper.Config(
                showCloseIcon = true,
                centerTitle = true,
                centerContent = true
            )
        )
    }

    private fun verifyData(isDraft: Boolean) {
        if (mViewModel.videoPatch == null) {
            if (!isDraft && mVideoFileEntity != null &&
                !File(mVideoFileEntity?.path ?: "").exists()
            ) {
                toast("提交失败，视频文件不存在")
                handleFileNotFound()
                return
            }

            if (!isDraft && mVideoFileEntity?.url == null) {
                toast("视频尚未上传完成")
                return
            }

            if (!isDraft && (mViewModel.communityEntity == null || mViewModel.communityEntity?.id?.isEmpty() == true)) {
                showSelectGameDialog()
                return
            }
        }
        val title = mBinding.title.text.trim()
        if (!isDraft && title.isEmpty()) {
            toast("请填写标题")
            return
        }

        if (!isDraft && mViewModel.videoPatch == null && mViewModel.selectActivityLabelEntity?.original == true && !mBinding.originalTv.isChecked) {
            toast("本次话题内容要求原创")
            return
        }

        if (!isDraft && mViewModel.videoPatch == null && mBinding.reprintTv.isChecked && mBinding.reprintUrlTv.text.isEmpty()) {
            toast("请填写转载来源")
            return
        }

        val des = mBinding.videoDes.text.trim()
        if (mViewModel.videoPatch != null && mViewModel.videoPatch?.title == title && mViewModel.videoPatch?.des == des) return

        val videoData = if (mViewModel.videoPatch != null) {
            mViewModel.videoPatch!!.title = title.toString()
            mViewModel.videoPatch!!.des = des.toString()
            mViewModel.videoPatch!!
        } else {
            ForumVideoEntity(
                id = mViewModel.videoDraft?.id ?: "",
                title = title.toString(),
                des = des.toString(),
                url = mVideoFileEntity?.url ?: "",
                size = mVideoFileEntity?.size ?: 0,
                format = mVideoFileEntity?.format ?: "",
                length = mVideoFileEntity?.length ?: 0,
                poster = mViewModel.videoDraft?.poster ?: "",
                bbsId = mViewModel.communityEntity?.id ?: "",
                type = mViewModel.type,
                gameId = mViewModel.gameEntity?.id ?: mViewModel.communityEntity?.game?.id ?: "",
                original = if (mBinding.originalTv.isChecked) "yes" else if (mBinding.reprintTv.isChecked) "no" else "",
                source = if (mBinding.reprintTv.isChecked) mBinding.reprintUrlTv.text.toString() else "",
                tagActivityId = mViewModel.selectActivityLabelEntity?.id ?: "",
                tagActivityName = mViewModel.selectActivityLabelEntity?.name ?: ""
            )
        }
        if (mUpdatedPosterPath.isEmpty() && videoData.poster.isNotEmpty()) {
            mViewModel.postContent(isDraft, videoData, mVideoFileEntity?.path)
        } else {
            //未选择视频直接保存草稿
            if (isDraft && mVideoFileEntity == null) {
                mViewModel.postContent(isDraft, videoData, mVideoFileEntity?.path)
                return
            }
            mViewModel.postVideoPosterAndContent(
                isDraft,
                videoData,
                mUpdatedPosterPath,
                mVideoFileEntity?.path
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val path = mVideoFileEntity?.path
        if (path != null && UploadManager.isUploading(path)) {
            UploadManager.cancelTask(path)
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        setSectionUI(mViewModel.selectSection == null)
        mBinding.activityTv.setTextColor(
            if (mViewModel.selectActivityLabelEntity != null) {
                com.gh.gamecenter.common.R.color.text_FA8500.toColor(requireContext())
            } else {
                com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext())
            }
        )
        mBinding.forumContainer.background =
            if (mViewModel.communityEntity == null) R.drawable.button_round_primary_light.toDrawable(requireContext()) else com.gh.gamecenter.common.R.drawable.bg_shape_f5_radius_999.toDrawable(
                requireContext()
            )
        mBinding.chooseForumTv.setTextColor(
            if (mViewModel.communityEntity == null) com.gh.gamecenter.common.R.color.text_theme.toColor(
                requireContext()
            ) else com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext())
        )
    }

    companion object {
        const val REQUEST_CODE_IMAGE_CROP = 101
        const val REQUEST_GAME_CODE = 102
        const val REQUEST_CHOOSE_DRAFT = 103

        const val IS_FORUM_SELECTION_DISABLED = "is_forum_selection_disable"
        const val IS_FROM_COMMUNITY_ACTIVITY = "is_form_community_activity"
    }

}