package com.gh.gamecenter.energy.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.fragment.BaseDraggableDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.energy.databinding.DialogInviteCodeBinding
import com.gh.gamecenter.energy.eventbus.EBTask
import com.gh.gamecenter.energy.retrofit.RetrofitManager
import com.gh.gamecenter.energy.utils.EnergyTaskHelper
import com.gh.gamecenter.login.user.UserManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import retrofit2.HttpException

class InviteCodeDialog : BaseDraggableDialogFragment() {

    private lateinit var mBinding: DialogInviteCodeBinding
    private var mIsBind: Boolean = false
    private var mIsHorizontal: Boolean = false
    private var mFrom: String = ""
    private var mPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireArguments().run {
            mIsBind = getBoolean(KEY_IS_BIND)
            mIsHorizontal = getBoolean(KEY_IS_HORIZONTAL)
            mFrom = getString(KEY_FROM) ?: ""
            mPosition = getInt(KEY_POSITION)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return DialogInviteCodeBinding.inflate(inflater, container, false).apply { mBinding = this }.root
    }

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

        mBinding.run {
            if (mIsBind) {
                bindPhoneContainer.visibility = View.GONE
                inviteCodeContainer.visibility = View.VISIBLE
            } else {
                bindPhoneContainer.visibility = View.VISIBLE
                inviteCodeContainer.visibility = View.GONE
            }

            bindCloseIv.setOnClickListener {
                dismissAllowingStateLoss()
            }

            bindBtn.setOnClickListener {
                ARouter.getInstance().build(RouteConsts.activity.bindPhoneActivity)
                    .withBoolean(EntranceConsts.KEY_FROM_LOGIN, false)
                    .withBoolean(EntranceConsts.KEY_CHANGE_PHONE, false)
                    .navigation()
                dismissAllowingStateLoss()
            }

            inviteCloseIv.setOnClickListener {
                dismissAllowingStateLoss()
            }

            confirmBtn.setOnClickListener {
                val code = inviteEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                val newCallback = {
                    dismissAllowingStateLoss()
                    EventBus.getDefault().post(EBTask(mIsHorizontal, mPosition))
                }
                checkInviteCode(code, mFrom, newCallback)
            }
        }
    }

    @SuppressLint("CheckResult")
    fun checkInviteCode(code: String, from: String, callback: () -> Unit) {
        val params = JSONObject()
        params.put("code", code)
        params.put("type", "new")
        params.put("from", from)

        val body = RequestBody.create(MediaType.parse("application/json"), params.toString())
        RetrofitManager.getInstance()
            .api.checkInviteCode(UserManager.getInstance().userId, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<ResponseBody>() {
                override fun onSuccess(data: ResponseBody) {
                    EnergyTaskHelper.postInviteCodeTask(code, from, callback)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    if (exception is HttpException) {
                        try {
                            val responseBody = exception.response().errorBody()
                            val string = responseBody!!.string()
                            val content = JSONObject(string)
                            when (content.optInt("code")) {
                                403091 -> ToastUtils.showToast("你已经是老用户了")

                                else -> ToastUtils.showToast("填写邀请码错误")
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            ToastUtils.showToast("填写邀请码错误")
                        }
                    }
                }
            })
    }

    override fun getRootView(): View = mBinding.root
    override fun getDragCloseView(): View = if (mIsBind) mBinding.inviteCloseIv else mBinding.bindCloseIv

    companion object {
        const val KEY_IS_BIND = "is_bind"
        const val KEY_FROM = "from"
        const val KEY_IS_HORIZONTAL = "horizontal"
        const val KEY_POSITION = "position"

        @JvmStatic
        fun showInviteCodeDialog(
            activity: AppCompatActivity,
            isBind: Boolean,
            from: String,
            isHorizontal: Boolean,
            position: Int
        ) {
            InviteCodeDialog().apply {
                arguments = Bundle().apply {
                    putBoolean(KEY_IS_BIND, isBind)
                    putBoolean(KEY_IS_HORIZONTAL, isHorizontal)
                    putString(KEY_FROM, from)
                    putInt(KEY_POSITION, position)
                }
            }.show(activity.supportFragmentManager, InviteCodeDialog::class.java.name)
        }
    }
}