package com.cheng.blzb.ui.fragment.mine.account

import android.graphics.Color
import android.text.TextUtils
import com.example.base.common.RxBus
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.example.base.utils.Utils
import com.google.gson.JsonObject
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentBindAccountBinding
import com.cheng.blzb.event.HomeRefreshEvent
import com.cheng.blzb.event.MineRefreshEvent
import com.cheng.blzb.event.WxLoginEvent
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.dialog.BindPhoneDialog
import com.cheng.blzb.ui.dialog.TipDialog
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.anko.backgroundColor

class BindAccountFragment : BaseFragment<FragmentBindAccountBinding, BindAccountViewModel>() {
    private var userInfo: com.cheng.blzb.bean.UserEntity? = null
    private lateinit var api: IWXAPI

    private var isVisible = false

    private var isWxRequesting = false

    override fun initView() {
        super.initView()
        mTitleBar?.backgroundColor = Color.WHITE
    }

    override fun initData() {
        super.initData()
        mViewModel.userInfo()
        api = WXAPIFactory.createWXAPI(requireContext(), Constants.WechatAppId)
    }

    override fun onStart() {
        super.onStart()
        isVisible = true
    }

    override fun onStop() {
        super.onStop()
        isVisible = false
    }

    override fun initListener() {
        super.initListener()
        binding.btnBindWx.onClick {
            if (TextUtils.isEmpty(userInfo?.unionid)) {
                wxAuth()
            } else {
                val f = TipDialog.newInstance("解除微信绑定", "解绑后将无法使用该微信号登录此账号，请谨慎操作！")
                f.setOnSelectListener {
                    if (it == DialogEnum.CLICK_OK) {
                        if (!TextUtils.isEmpty(userInfo?.phone)) {
                            unbindWx()
                        } else {
                            val f1 = TipDialog.newInstance(
                                "预警提示",
                                "您若继续解除绑定，您的账号将没有绑定账号，软件在使用过程中可能会造成账号丢失！是否继续解除绑定！"
                            )
                            f1.setOnSelectListener { e ->
                                if (e == DialogEnum.CLICK_OK) {
                                    unbindWx()
                                }
                            }
                            f1.show(childFragmentManager, TipDialog::class.java.simpleName)
                        }
                    }
                }
                f.show(childFragmentManager, TipDialog::class.java.simpleName)
            }
        }
        binding.btnBindPhone.onClick {
            if (TextUtils.isEmpty(userInfo?.phone)) {
                val f = BindPhoneDialog.newInstance()
                f.setOnSendCodeClickListener { phone ->
                    mViewModel.sendCode(phone) {
                        f.setTimestamp(it.timestamp)
                    }
                }
                f.setOnBackListener { phone, code, timestamp ->
                    bindPhone(phone, code, timestamp)
                }
                f.show(childFragmentManager, BindPhoneDialog::class.java.simpleName)
            } else {
                val f = TipDialog.newInstance("解除手机绑定", "解绑后将无法使用该手机号登录此账号，请谨慎操作！")
                f.setOnSelectListener {
                    if (it == DialogEnum.CLICK_OK) {
                        if (!TextUtils.isEmpty(userInfo?.unionid)) {
                            unbindPhone()
                        } else {
                            val f1 = TipDialog.newInstance(
                                "预警提示",
                                "您若继续解除绑定，您的账号将没有绑定账号，软件在使用过程中可能会造成账号丢失！是否继续解除绑定！"
                            )
                            f1.setOnSelectListener { e ->
                                if (e == DialogEnum.CLICK_OK) {
                                    unbindPhone()
                                }
                            }
                            f1.show(childFragmentManager, TipDialog::class.java.simpleName)
                        }
                    }
                }
                f.show(childFragmentManager, TipDialog::class.java.simpleName)
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            userInfo = it
            setUserInfo()
        }
        mViewModel.bindPhoneLiveData.observe(this) {
            toast("绑定成功")
            refreshData()
            EventReportManager.eventReport(EventConstants.ACCOUNT_BIND, it, "")
        }
        mViewModel.unbindPhoneLiveData.observe(this) {
            toast("解绑成功")
            refreshData()
            EventReportManager.eventReport(EventConstants.ACCOUNT_UNBIND, it, "")
        }
        val wxLoginEvent = RxBus.defaultInstance.toObservable(WxLoginEvent::class.java).subscribe {
            isWxRequesting = false
            if (!TextUtils.isEmpty(it.code) && isVisible && it.state.endsWith("bind")) bindWx(it.code)
        }
        addDisposable(wxLoginEvent)
    }

    private fun refreshData() {
        UserConfigManager.userConfig {
            mViewModel.userInfo()
            RxBus.defaultInstance.post(HomeRefreshEvent())
            RxBus.defaultInstance.post(MineRefreshEvent())
        }
    }

    private fun setUserInfo() {
        if (TextUtils.isEmpty(userInfo?.unionid)) {
            binding.btnBindWx.text = "立即绑定"
        } else {
            binding.btnBindWx.text = "解除绑定"
        }
        if (TextUtils.isEmpty(userInfo?.phone)) {
            binding.btnBindPhone.text = "立即绑定"
        } else {
            binding.btnBindPhone.text = "解除绑定"
        }
    }

    private fun bindWx(code: String) {
        val jsonWx = JsonObject()
        jsonWx.addProperty("code", code)
        jsonWx.addProperty("code_type", "")

        val jsonObject = JsonObject()
        jsonObject.add("weixin", jsonWx)
        jsonObject.addProperty("login_type", "weixin")
        jsonObject.addProperty("bind", true)
        mViewModel.bind(jsonObject.toString().toRequestBody(), "weixin")
    }

    private fun bindPhone(phone: String, code: String, timestamp: String) {
        val jsonPhone = JsonObject()
        jsonPhone.addProperty("timestamp", timestamp)
        jsonPhone.addProperty("phone", phone)
        jsonPhone.addProperty("code", code)

        val jsonObject = JsonObject()
        jsonObject.add("phone", jsonPhone)
        jsonObject.addProperty("login_type", "phone")
        jsonObject.addProperty("bind", true)
        mViewModel.bind(jsonObject.toString().toRequestBody(), "phone")
    }

    private fun unbindWx() {
        val jsonObject = JsonObject()
        jsonObject.addProperty("login_type", "weixin")
        jsonObject.addProperty("unbind", true)
        mViewModel.unbind(jsonObject.toString().toRequestBody(), "weixin")
    }

    private fun unbindPhone() {
        val jsonObject = JsonObject()
        jsonObject.addProperty("login_type", "phone")
        jsonObject.addProperty("unbind", true)
        mViewModel.unbind(jsonObject.toString().toRequestBody(), "phone")
    }

    private fun wxAuth() {
        if (isWxRequesting) return
        if (!api.isWXAppInstalled) {
            toast("未安装微信客户端，请先下载安装微信客户端")
            return
        }
        isWxRequesting = true
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo" // 只能填 snsapi_userinfo
        req.state = Utils.getApp().packageName + Math.random() * 1000 + "_bind"
        api.sendReq(req)
    }
}