package com.gh.gamecenter.qa.dialog

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.widget.TextViewCompat
import com.gh.common.util.NewLogUtils
import com.gh.gamecenter.common.base.fragment.BaseDraggableDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.entity.NormalShareEntity
import com.gh.gamecenter.common.eventbus.EBShare
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.DialogGameDetailMoreBinding
import com.gh.gamecenter.entity.MenuItemEntity
import org.greenrobot.eventbus.EventBus

class MoreFunctionPanelDialog : BaseDraggableDialogFragment() {

    private lateinit var binding: DialogGameDetailMoreBinding
    private var mMenuItems: ArrayList<MenuItemEntity> = arrayListOf()
    private var mTitle: String = ""
    private var mParentTag: String = ""
    private var mStatus: String = ""
    private var titleStyle: Int = MORE_DIALOG_TITLE_STYLE_CENTER_BOLD
    private var mShareEntity: NormalShareEntity? = null
    private var mShareUtils: ShareUtils? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireArguments().run {
            mMenuItems = getParcelableArrayList(KEY_MENU_ITEMS) ?: arrayListOf()
            mTitle = getString(KEY_TITLE) ?: ""
            mStatus = getString(KEY_STATUS) ?: ""
            mShareEntity = getParcelable(KEY_SHARE)
            mParentTag = getString(EntranceConsts.KEY_PARENT_TAG) ?: ""
            titleStyle = getInt(KEY_TITLE_STYLE)
        }
        mShareUtils = getShareUtils()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DialogGameDetailMoreBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.gameNameTv.text = mTitle
        binding.gameIconView.visibility = View.GONE
        binding.feedbackTv.visibility = View.GONE
        binding.copyrightTv.visibility = View.GONE

        when (titleStyle) {
            MORE_DIALOG_TITLE_STYLE_CENTER_BOLD -> {
                TextViewCompat.setTextAppearance(binding.gameNameTv, com.gh.gamecenter.common.R.style.TextBody2B)
                binding.gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                binding.gameNameTv.gravity = Gravity.CENTER
            }

            MORE_DIALOG_TITLE_STYLE_LEFT_BOLD -> {
                TextViewCompat.setTextAppearance(binding.gameNameTv, com.gh.gamecenter.common.R.style.TextBody2B)
                binding.gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()))
                binding.gameNameTv.gravity = Gravity.START
            }

            MORE_DIALOG_TITLE_STYLE_CENTER_NORMAL -> {
                TextViewCompat.setTextAppearance(binding.gameNameTv, com.gh.gamecenter.common.R.style.TextBody2)
                binding.gameNameTv.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(requireContext()))
                binding.gameNameTv.gravity = Gravity.CENTER
            }
        }

        binding.shareWechatTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.wechatShare()
                    NewLogUtils.logShareTypeClick("微信好友")
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.sharePyquanTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.wechatMomentsShare()
                    NewLogUtils.logShareTypeClick("朋友圈")
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.shareQqTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.qqShare()
                    NewLogUtils.logShareTypeClick("QQ好友")
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.shareQqzoneTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.qZoneShare()
                    NewLogUtils.logShareTypeClick("QQ空间")
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.shareWeiboTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.sinaWeiboShare()
                    NewLogUtils.logShareTypeClick("新浪微博")
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.shareSmsTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.shortMessageShare()
                    NewLogUtils.logShareTypeClick("短信")
                    EventBus.getDefault().post(EBShare(ShareUtils.shareEntrance, "短信"))
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.copyLinkTv.setOnClickListener {
            debounceActionWithInterval(it.id, 2000) {
                if (checkStatusIsPass()) {
                    mShareUtils?.copyLink(mShareUtils?.shareUrl ?: "")
                    NewLogUtils.logShareTypeClick("复制链接")
                    EventBus.getDefault().post(EBShare(ShareUtils.shareEntrance, "复制链接"))
                    dismissAllowingStateLoss()
                }
            }
        }
        binding.cancelTv.setOnClickListener {
            NewLogUtils.logSharePanelCancelClick()
            dismissAllowingStateLoss()
        }
        addActionItem()
    }

    private fun checkStatusIsPass(): Boolean {
        return when (mStatus) {
            "pending" -> {
                toast("内容审核中，不支持分享")
                false
            }

            "fail" -> {
                toast("内容审核不通过，不支持分享")
                false
            }

            else -> true
        }
    }

    private fun addActionItem() {
        mMenuItems.forEachIndexed { index, menuItemEntity ->
            val itemView = createItemView(menuItemEntity).apply {
                if (index == mMenuItems.lastIndex) {
                    (layoutParams as MarginLayoutParams).apply {
                        rightMargin = 16F.dip2px()
                    }
                }
            }
            itemView.setOnClickListener {
                debounceActionWithInterval(it.id, 2000) {
                    if (menuItemEntity.isEnable) {
                        val intent = Intent().apply {
                            putExtra(EntranceConsts.KEY_DATA, menuItemEntity)
                        }
                        if (parentFragment != null) {
                            parentFragment?.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent)
                        } else {
                            activity?.supportFragmentManager?.findFragmentByTag(mParentTag)
                                ?.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent)
                        }
                        dismissAllowingStateLoss()
                    }
                }
            }
            binding.actionContainer.addView(itemView)
        }
    }

    private fun createItemView(itemEntity: MenuItemEntity): View {
        val params = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        params.leftMargin = 16F.dip2px()
        return TextView(requireContext()).apply {
            textSize = 11F
            text = itemEntity.text
            setTextColor(
                ContextCompat.getColor(
                    requireContext(),
                    if (itemEntity.isEnable) com.gh.gamecenter.common.R.color.text_secondary else com.gh.gamecenter.common.R.color.text_tertiary
                )
            )
            includeFontPadding = false
            gravity = Gravity.CENTER
            layoutParams = params
            compoundDrawablePadding = 8F.dip2px()
            setDrawableTop(itemEntity.normalIcon)
        }
    }

    private fun getShareUtils(): ShareUtils {
        val shareUtils = ShareUtils.getInstance(requireContext())
        mShareEntity?.run {
            shareUtils.shareParamsDetail(
                requireActivity(),
                shareUrl,
                shareIcon,
                shareTitle,
                shareSummary,
                shareEntrance,
                id,
                mShareEntity?.additionalParams
            )
        }
        return shareUtils
    }

    override fun getRootView(): View = binding.root
    override fun getDragCloseView(): View = binding.dragClose

    companion object {
        const val KEY_MENU_ITEMS = "menu_items"
        const val KEY_TITLE = "title"
        const val KEY_SHARE = "share"
        const val KEY_STATUS = "status"
        const val KEY_TITLE_STYLE = "title_style"
        const val REQUEST_CODE = 1101

        const val MORE_DIALOG_TITLE_STYLE_CENTER_BOLD = 0    // 居中-加粗
        const val MORE_DIALOG_TITLE_STYLE_LEFT_BOLD = 1      // 左对齐-加粗
        const val MORE_DIALOG_TITLE_STYLE_CENTER_NORMAL = 2  // 居中

        @JvmStatic
        fun showMoreDialog(
            activity: AppCompatActivity,
            menuItems: ArrayList<MenuItemEntity>,
            title: String,
            share: NormalShareEntity,
            status: String,
            parentTag: String,
            titleStyle: Int = MORE_DIALOG_TITLE_STYLE_CENTER_BOLD
        ) {
            MoreFunctionPanelDialog().apply {
                arguments = Bundle().apply {
                    putParcelableArrayList(KEY_MENU_ITEMS, menuItems)
                    putString(KEY_TITLE, title)
                    putParcelable(KEY_SHARE, share)
                    putString(KEY_STATUS, status)
                    putString(EntranceConsts.KEY_PARENT_TAG, parentTag)
                    putInt(KEY_TITLE_STYLE, titleStyle)
                }
            }.show(
                activity.supportFragmentManager,
                MoreFunctionPanelDialog::class.java.name
            )
        }

        fun getMoreDialog(
            menuItems: ArrayList<MenuItemEntity>,
            title: String,
            share: NormalShareEntity,
            status: String,
            parentTag: String
        ): MoreFunctionPanelDialog {
            return MoreFunctionPanelDialog().apply {
                arguments = Bundle().apply {
                    putParcelableArrayList(KEY_MENU_ITEMS, menuItems)
                    putString(KEY_TITLE, title)
                    putParcelable(KEY_SHARE, share)
                    putString(KEY_STATUS, status)
                    putString(EntranceConsts.KEY_PARENT_TAG, parentTag)
                }
            }
        }
    }
}