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

import android.graphics.Color
import android.text.TextUtils
import com.cheng.blzb.bean.AccountEntity
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentAccountManageBinding
import com.cheng.blzb.event.LoginSuccessEvent
import com.cheng.blzb.manager.DialogEnum
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.dialog.TipDialog
import com.example.base.common.RxBus
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.anko.backgroundColor

class AccountManageFragment : BaseFragment<FragmentAccountManageBinding, AccountManageViewModel>() {
    private val mAdapter by lazy { AccountAdapter() }
    private var mAccount: AccountEntity? = null

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

        binding.rvAccount.adapter = mAdapter
    }

    override fun initData() {
        super.initData()
        mViewModel.accountList()
    }

    override fun initListener() {
        super.initListener()
        mAdapter.setOnItemClickListener { _, _, i ->
            val item = mAdapter.getItem(i)
            if (item.user_id != UserConfigManager.userInfo?.user_id) {
                val f = TipDialog.newInstance("提示", "您确定要切换账户吗？")
                f.setOnSelectListener {
                    if (it == DialogEnum.CLICK_OK) {
                        LoginManager.saveToken("")
                        changeAccount(mAdapter.getItem(i).user_id)

                        EventReportManager.eventReport(EventConstants.SWITCH_ACCOUNT, mAdapter.getItem(i).user_id, "")
                    }
                }
                f.show(childFragmentManager, TipDialog::class.java.simpleName)
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.accountLiveData.observe(this) {
            val list = it.toMutableList()
            for (account in list) {
                if (account.user_id == UserConfigManager.userInfo?.user_id) {
                    mAccount = account
                    list.remove(account)
                    break
                }
            }
            mAdapter.setList(list)
            if (mAccount != null) {
                mAdapter.addData(0, mAccount!!)
            } else if (UserConfigManager.userInfo != null) {
                val userinfo = UserConfigManager.userInfo
                val bind = mutableListOf<String>()
                if (!TextUtils.isEmpty(userinfo!!.unionid)) {
                    bind.add("weixin")
                }
                if (!TextUtils.isEmpty(userinfo.phone)) {
                    bind.add("phone")
                }
                val account = AccountEntity(
                    userinfo.avater,
                    bind,
                    "",
                    userinfo.name,
                    userinfo.phone,
                    userinfo.role.toInt(),
                    userinfo.temp,
                    userinfo.user_id,
                    userinfo.vip_name,
                    userinfo.vip
                )
                mAdapter.addData(0, account)
            }
        }

        mViewModel.loginLiveData.observe(this) {
            EventReportManager.eventReport(EventConstants.LOGIN, "device", it.user_id)
            loginSuccess(it)
        }
    }

    /**
     * 切换账户
     */
    private fun changeAccount(userId: String) {
        val jsonObject = JsonObject()
        jsonObject.addProperty("login_type", "device")

        val jsonDevice = JsonObject()
        jsonDevice.addProperty("user_id", userId)
        jsonObject.add("device", jsonDevice)
        mViewModel.login(jsonObject.toString().toRequestBody())
    }

    private fun loginSuccess(entity: com.cheng.blzb.bean.LoginEntity) {
        mViewModel.showDialog()
        LoginManager.saveToken(entity.token)
        UserConfigManager.saveLastUserinfo(UserConfigManager.userInfo)
        UserConfigManager.userConfig {
            toast("切换成功")
            mViewModel.dismissDialog()
            RxBus.defaultInstance.post(LoginSuccessEvent())
            requireActivity().finish()
        }
    }
}