package com.gh.common.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.*
import android.view.ViewGroup.MarginLayoutParams
import androidx.core.view.updateLayoutParams
import com.gh.common.pop.EditBindPhoneInfoPop
import com.gh.common.pop.EditBindWechatPop
import com.gh.common.pop.RealNameTipsPop
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.entity.WechatConfigEntity
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.*
import com.gh.gamecenter.entity.ReserveReminderEntity
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.halo.assistant.HaloApp
import com.halo.assistant.fragment.reserve.OnReserveReminderListener

class ReserveSuccessReminderDialog(
    context: Context,
    themeResId: Int,
    private val listener: OnReserveReminderListener
) :
    Dialog(context, themeResId), OnReserveSuccessListener {

    private var reserveReminder = ReserveReminderEntity()

    private val handler = Handler(Looper.getMainLooper())

    private val handlers = arrayListOf<ReminderContentHandler>()

    private lateinit var binding: DialogReserveSuccessWithSmsBinding

    private val realNameQuestionPop by lazy {
        RealNameTipsPop.create(context, listener)
    }

    private var hasAutoPopped = false
    private var isInit = true

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            if (realNameQuestionPop.isShowing) {
                realNameQuestionPop.dismiss()
                return true
            } else if (handlers.any { it.hasPopShowing }) {
                handlers.forEach {
                    it.dismissPop()
                }
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogReserveSuccessWithSmsBinding.inflate(LayoutInflater.from(context))
        setContentView(binding.root)

        binding.ivClose.setOnClickListener {
            dismiss()
        }
        binding.ivQuestion.setOnClickListener {
            realNameQuestionPop.showAtLocation(binding.cbAutoDownload, Gravity.BOTTOM, 0, 4F.dip2px())
        }

    }

    private fun initView() {
        handlers.clear()
        binding.flContentContainer.removeAllViews()

        val configTypes = mutableListOf<Int>()
        // 短信
        if (reserveReminder.hasSmsConfig) {
            if (reserveReminder.smsConfig.notice) {
                configTypes.add(SMS_REMINDER_ENABLE_TYPE)
            } else {
                configTypes.add(SMS_REMINDER_UNABLE_TYPE)
            }
        }

        // 微信
        if (reserveReminder.wechatConfig.isReminderEnable) {
            configTypes.add(WECHAT_REMINDER_ENABLE_TYPE)
        } else {
            configTypes.add(WECHAT_REMINDER_UNABLE_TYPE)
        }

        // 日历
        if (reserveReminder.hasCalendarConfig) {
            if (reserveReminder.calendarConfig.notice) {
                configTypes.add(CALENDAR_REMINDER_ENABLE_TYPE)
            } else {
                configTypes.add(CALENDAR_REMINDER_UNABLE_TYPE)
            }
        }

        if (configTypes.size == 1) {
            // 只有微信提醒
            if (configTypes.first() == WECHAT_REMINDER_ENABLE_TYPE) {
                binding.tvContent.setText(R.string.reverse_success_with_reminder_tips)
                handlers.add(
                    WechatReminderEnableHandler(reserveReminder.wechatConfig, 8.dp, binding.flContentContainer, this)
                )
            } else {
                binding.tvContent.setText(R.string.reverse_success_without_reminder_tips)
                handlers.add(OnlyWechatReminderUnableHandler(16.dp, binding.flContentContainer, this))
            }
        } else {
            binding.tvContent.setText(R.string.reverse_success_with_reminder_tips)
            var isLargerSpacing = true
            fun getPaddingTop(): Int {
                val paddingTop = if (isLargerSpacing) 16.dp else 8.dp
                isLargerSpacing = false
                return paddingTop
            }
            configTypes.sorted().forEach {
                when (it) {
                    SMS_REMINDER_ENABLE_TYPE -> {
                        isLargerSpacing = true
                        SmsReminderEnableHandler(reserveReminder.smsConfig, 8.dp, binding.flContentContainer, this)
                    }

                    SMS_REMINDER_UNABLE_TYPE -> {
                        SmsReminderUnableHandler(getPaddingTop(), binding.flContentContainer, this)
                    }


                    WECHAT_REMINDER_ENABLE_TYPE -> {
                        isLargerSpacing = true
                        WechatReminderEnableHandler(
                            reserveReminder.wechatConfig,
                            8.dp,
                            binding.flContentContainer,
                            this
                        )
                    }


                    WECHAT_REMINDER_UNABLE_TYPE ->
                        WechatReminderUnableHandler(getPaddingTop(), binding.flContentContainer, this)

                    CALENDAR_REMINDER_ENABLE_TYPE -> {
                        isLargerSpacing = true
                        CalendarReminderEnableHandler(8.dp, binding.flContentContainer, this)
                    }

                    CALENDAR_REMINDER_UNABLE_TYPE ->
                        CalendarReminderUnableHandler(getPaddingTop(), binding.flContentContainer, this)

                    else -> null
                }?.let(handlers::add)
            }
        }

        handlers.forEach {
            binding.flContentContainer.addView(it.init())
        }

        if (isInit) {
            isInit = false
            binding.gAutoDownload.goneIf(!reserveReminder.isEnableAutoDownload)
            if (reserveReminder.isEnableAutoDownload) {
                binding.cbAutoDownload.isChecked = reserveReminder.wifiAutoDownload
                checkIfShowRealNamePop()
            }
            binding.cbAutoDownload.setOnCheckedChangeListener { _, isChecked ->
                listener.enableAutoDownload(isChecked)
                checkIfShowRealNamePop()
            }
        }

    }

    private fun checkIfShowRealNamePop() {
        if (hasAutoPopped) {
            return
        }
        hasAutoPopped = true
        handler.postDelayed({
            val idCard = UserManager.getInstance().userInfoEntity?.idCard
            if (idCard != null && idCard.status != 1 && idCard.minor != true) {
                // 账号已实名
                return@postDelayed
            }

            val deviceCertificationInfoString =
                SPUtils.getString(Constants.SP_DEVICE_CERTIFICATION_PREFIX + HaloApp.getInstance().gid)
            if (!TextUtils.isEmpty(deviceCertificationInfoString)) {
                val deviceIdCard = deviceCertificationInfoString.toObject<UserInfoEntity>()?.idCard
                if (deviceIdCard != null && deviceIdCard.status != 1 && deviceIdCard.minor != true) {
                    // 设备已实名
                    return@postDelayed
                }
            }
            realNameQuestionPop.showAtLocation(binding.cbAutoDownload, Gravity.BOTTOM, 0, 0)
        }, 16)
    }

    override fun updateSmsReminder(isEnable: Boolean) {
        listener.updateSmsReminder(isEnable)
    }

    override fun updateWechatReminder() {
        listener.updateWechatReminder()
    }

    override fun changePhoneNumber() {
        listener.changedPhoneNumber()
    }

    override fun verifyPhoneNumber() {
        listener.verifyPhoneNumber()
    }

    override fun changeWechatBinding() {
        listener.changeWechatBinding()
    }

    override fun updateCalendarReminder() {
        listener.updateCalendarReminder()
    }

    override fun onStart() {
        super.onStart()
        window?.let {
            it.setDimAmount(0.4F)
            it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val params = it.attributes
            params.width = DisplayUtils.dip2px(300F)
            it.attributes = params
        }
    }

    fun updateReserveReminder(reserveReminder: ReserveReminderEntity) {
        this.reserveReminder = reserveReminder
        initView()
    }

    override fun dismiss() {
        handler.removeCallbacksAndMessages(null)
        super.dismiss()
    }

    companion object {
        private val Int.dp: Int
            get() = DisplayUtils.dip2px(this.toFloat())

        private const val SMS_REMINDER_ENABLE_TYPE = 1
        private const val WECHAT_REMINDER_ENABLE_TYPE = 2
        private const val CALENDAR_REMINDER_ENABLE_TYPE = 3
        private const val SMS_REMINDER_UNABLE_TYPE = 4
        private const val WECHAT_REMINDER_UNABLE_TYPE = 5
        private const val CALENDAR_REMINDER_UNABLE_TYPE = 6

        fun create(context: Context, listener: OnReserveReminderListener) =
            ReserveSuccessReminderDialog(
                context,
                com.gh.gamecenter.common.R.style.DialogWindowTransparent,
                listener
            ).apply {

            }
    }

    abstract class ReminderContentHandler(
        val topMargin: Int,
        val parent: ViewGroup,
        val listener: OnReserveSuccessListener
    ) {

        open val hasPopShowing: Boolean = false

        fun init(): View {
            val root = createView(LayoutInflater.from(parent.context))
            root.updateLayoutParams<MarginLayoutParams> {
                this.topMargin = this@ReminderContentHandler.topMargin
            }
            initView()
            return root
        }

        protected abstract fun createView(inflater: LayoutInflater): View

        protected abstract fun initView()

        open fun dismissPop() = Unit
    }

    class SmsReminderUnableHandler(topMargin: Int, parent: ViewGroup, listener: OnReserveSuccessListener) :
        ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveSmsReminderUnableBinding

        override fun createView(inflater: LayoutInflater): View {
            return LayoutReserveSmsReminderUnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root
        }

        override fun initView() {
            binding.vSmsAdd.setOnClickListener {
                listener.updateSmsReminder(true)
            }
        }

    }

    class WechatReminderUnableHandler(topMargin: Int, parent: ViewGroup, listener: OnReserveSuccessListener) :
        ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveWechatReminderUnableBinding

        override fun createView(inflater: LayoutInflater): View {
            return LayoutReserveWechatReminderUnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root
        }

        override fun initView() {
            binding.vWechatAdd.setOnClickListener {
                listener.updateWechatReminder()
            }
        }

    }

    class SmsReminderEnableHandler(
        private val smsConfig: ReserveReminderEntity.SmsConfig,
        topMargin: Int,
        parent: ViewGroup, listener:
        OnReserveSuccessListener
    ) :
        ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveSmsReminderEnableBinding

        override val hasPopShowing: Boolean
            get() = editBindPhoneInfoPop.isShowing

        override fun dismissPop() {
            if (hasPopShowing) {
                editBindPhoneInfoPop.dismiss()
            }
        }

        private val editBindPhoneInfoPop by lazy {
            EditBindPhoneInfoPop.create(parent.context, smsConfig.mobileValidated, listener)
        }

        override fun createView(inflater: LayoutInflater) =
            LayoutReserveSmsReminderEnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root

        override fun initView() {
            binding.tvPhone.text = smsConfig.mobile
            binding.vSmsEdit.setOnClickListener {
                editBindPhoneInfoPop.showAsDropDown(
                    binding.ivSmsEdit,
                    (-104).dp,
                    0,
                )
            }
        }
    }

    class WechatReminderEnableHandler(
        private val wechatConfig: WechatConfigEntity,
        topMargin: Int,
        parent: ViewGroup,
        listener: OnReserveSuccessListener
    ) :
        ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveWechatReminderEnableBinding

        private val editWechatPop by lazy {
            EditBindWechatPop.create(parent.context, listener)
        }

        override fun createView(inflater: LayoutInflater) =
            LayoutReserveWechatReminderEnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root

        override fun initView() {
            binding.tvWechat.text = wechatConfig.nickName
            binding.vModifyWechat.setOnClickListener {
                editWechatPop.showAsDropDown(
                    binding.ivModifyWechat,
                    (-104).dp,
                    0
                )
            }
        }

    }

    class OnlyWechatReminderUnableHandler(topMargin: Int, parent: ViewGroup, listener: OnReserveSuccessListener) :
        ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveOnlyWechatUnableBinding

        override fun createView(inflater: LayoutInflater) =
            LayoutReserveOnlyWechatUnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root

        override fun initView() {
            binding.vSubmitBackground.setOnClickListener {
                listener.updateWechatReminder()
            }
        }

    }

    class CalendarReminderUnableHandler(
        topMargin: Int,
        parent: ViewGroup,
        listener: OnReserveSuccessListener
    ) : ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveWechatReminderUnableBinding

        // 复用微信提醒未开启状态布局
        override fun createView(inflater: LayoutInflater) =
            LayoutReserveWechatReminderUnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root

        override fun initView() {
            binding.tvWechatReminderTitle.setText(R.string.calendar_reminders)
            binding.tvWechatReminderDescription.setText(R.string.calendar_reminders_description)
            binding.vWechatAdd.setOnClickListener {
                listener.updateCalendarReminder()
            }
        }

    }

    class CalendarReminderEnableHandler(
        topMargin: Int,
        parent: ViewGroup,
        listener: OnReserveSuccessListener
    ) : ReminderContentHandler(topMargin, parent, listener) {

        private lateinit var binding: LayoutReserveCalendarReminderUnableBinding

        override fun createView(inflater: LayoutInflater) =
            LayoutReserveCalendarReminderUnableBinding.inflate(inflater, parent, false)
                .also {
                    binding = it
                }.root

        override fun initView() {

        }


    }

}

interface OnReserveSuccessListener {

    fun updateSmsReminder(isEnable: Boolean)

    fun updateWechatReminder()

    fun changePhoneNumber()

    fun verifyPhoneNumber()

    fun changeWechatBinding()

    fun updateCalendarReminder()
}