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

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import coil.load
import coil.transform.CircleCropTransformation
import com.cheng.blzb.R
import com.cheng.blzb.bean.UserEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentMineBinding
import com.cheng.blzb.event.CompanyAuthEvent
import com.cheng.blzb.event.MineRefreshEvent
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.LoginManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.LoginActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.ShareDialog
import com.cheng.blzb.ui.fragment.bid.publish.my.MyPublishFragment
import com.cheng.blzb.ui.fragment.mine.auth.CompanyAuthFragment
import com.cheng.blzb.ui.fragment.mine.favorite.FavoriteFragment
import com.cheng.blzb.ui.fragment.mine.feedback.FeedbackFragment
import com.cheng.blzb.ui.fragment.mine.history.HistoryFragment
import com.cheng.blzb.ui.fragment.mine.message.MessageFragment
import com.cheng.blzb.ui.fragment.mine.order.OrderFragment
import com.cheng.blzb.ui.fragment.mine.seat.SeatManageFragment
import com.cheng.blzb.ui.fragment.mine.settings.SettingsFragment
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.ui.fragment.push.subscribe.SubscribeFragment
import com.example.base.common.RxBus
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.ClipboardUtils

/**
 * 我的
 */
class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>() {
    private var userInfo: UserEntity? = null

    private var isInit = true

    private var isEnterprise = false

    override fun initView() {
        super.initView()
        binding.tvVipName.typeface = Constants.ysbth
        binding.tvPushCount.typeface = Constants.dDIN_PRO_M
        binding.tvFavoriteCount.typeface = Constants.dDIN_PRO_M
        binding.tvHistoryCount.typeface = Constants.dDIN_PRO_M
        binding.tvOrderCount.typeface = Constants.dDIN_PRO_M
    }

    override fun onResume() {
        super.onResume()
        mViewModel.userInfo(isInit)
        mViewModel.getCompanyInfo()
        mViewModel.getSubscriptionList()
        mViewModel.getFavoriteList()
        mViewModel.getHistoryList()
        mViewModel.getOrderList("")
        if (isInit) isInit = false
    }

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

    override fun initListener() {
        super.initListener()
        binding.btnLogin.onClick {
            LoginActivity.start(requireActivity(), Pair("from", 1))
            EventReportManager.eventReport(EventConstants.JUMP_TO_LOGIN, "center", "")
        }

        binding.tvUserId.onClick {
            if (!TextUtils.isEmpty(userInfo?.user_id)) {
                ClipboardUtils.copyText(userInfo?.user_id)
                toast("复制成功")
                EventReportManager.eventReport(EventConstants.COPY_USER_ID, "", "")
            }
        }

        binding.ivVipBg.onClick {
            PublicActivity.start(requireContext(), VipFragment::class.java, Pair("origin", "center"))
            EventReportManager.eventReport(EventConstants.JUMP_TO_MEMBER_RECHARGE, "center", "")
        }

        binding.ivSetting.onClick {
            PublicActivity.start(requireContext(), SettingsFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_SYSTEM_SETTING, "", "")
        }

        binding.ivMessage.onClick {
            PublicActivity.start(requireContext(), MessageFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_MESSAGE, "", "")
        }

        binding.layoutPush.onClick {
            PublicActivity.start(requireContext(), SubscribeFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_SUBSCRIBE, "center", "")
        }

        binding.layoutFavorite.onClick {
            PublicActivity.start(requireContext(), FavoriteFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_FAVORITE, "", "")
        }

        binding.layoutHistory.onClick {
            PublicActivity.start(requireContext(), HistoryFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_HISTORY, "", "")
        }

        binding.layoutOrder.onClick {
            PublicActivity.start(requireContext(), OrderFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_ORDER, "", "")
        }

        binding.tvMyPublish.onClick {
            PublicActivity.start(requireContext(), MyPublishFragment::class.java, Pair("type", 1))
            EventReportManager.eventReport(EventConstants.JUMP_TO_MY_PUBLISH, "", "")
        }

        binding.tvAuth.onClick {
            PublicActivity.start(requireContext(), CompanyAuthFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_AUTH, "", "")
        }

        binding.tvSeatManage.onClick {
            PublicActivity.start(requireContext(), SeatManageFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_SEAT_MANAGE, "", "")
        }

        binding.tvService.onClick {
            mViewModel.wxService()
            EventReportManager.eventReport(EventConstants.JUMP_TO_SERVICE, "", "")
        }

        binding.tvShare.onClick {
            if (UserConfigManager.getShareEntity() != null) {
                ShareDialog().show(childFragmentManager, "")
            }
        }

        binding.tvFeedback.onClick {
            PublicActivity.start(requireContext(), FeedbackFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_FEEDBACK, "", "")
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            userInfo = it
            UserConfigManager.userInfoLiveData.postValue(it)
            setUserInfo()
        }

        mViewModel.companyLiveData.observe(this) {
            if (it != null) {
                when (it.status) {
                    "2" -> {
                        binding.tvAuthStatus.text = "认证成功"
                        binding.tvAuthStatus.setTextColor(getColor(R.color.color_3bbf0f))
                        binding.tvAuthStatus.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_auth_success_dot, 0, 0, 0)
                        binding.tvAuthStatus.visible()
                    }
                    "3" -> {
                        binding.tvAuthStatus.text = "认证失败"
                        binding.tvAuthStatus.setTextColor(getColor(R.color.color_ff592b))
                        binding.tvAuthStatus.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_auth_fail_dot, 0, 0, 0)
                        binding.tvAuthStatus.visible()
                    }
                    else -> binding.tvAuthStatus.gone()
                }
            } else {
                binding.tvAuthStatus.text = "未认证"
                binding.tvAuthStatus.setTextColor(getColor(R.color.color_ff592b))
                binding.tvAuthStatus.setCompoundDrawablesWithIntrinsicBounds(R.drawable.shape_auth_fail_dot, 0, 0, 0)
                binding.tvAuthStatus.visible()
            }
        }

        mViewModel.subscribeLiveData.observe(this) {
            binding.tvPushCount.text = "${it.size}"
        }

        mViewModel.favoriteLiveData.observe(this) {
            binding.tvFavoriteCount.text = "${it.size}"
        }

        mViewModel.historyLiveData.observe(this) {
            binding.tvHistoryCount.text = "${it.size}"
        }

        mViewModel.orderLiveData.observe(this) {
            binding.tvOrderCount.text = "${it.size}"
        }

        val authEvent = RxBus.defaultInstance.toObservable(CompanyAuthEvent::class.java).subscribe {
            mViewModel.getCompanyInfo()
        }
        addDisposable(authEvent)

        val mineRefreshEvent = RxBus.defaultInstance.toObservable(MineRefreshEvent::class.java).subscribe {
            mViewModel.userInfo()
        }
        addDisposable(mineRefreshEvent)
    }

    @SuppressLint("SetTextI18n")
    private fun setUserInfo() {
        if (userInfo == null) return
        binding.ivAvatar.load(userInfo?.avater) {
            transformations(CircleCropTransformation())
            placeholder(R.mipmap.ic_default_avatar)
            error(R.mipmap.ic_default_avatar)
        }

        if (userInfo?.vip == "1") {
            isEnterprise = false

            binding.tvVipName.text = "开通会员"
            binding.tvExpireTime.text = "开通会员，查看海量商机"

            binding.tvVipName.setTextColor(getColor(R.color.color_fbcd8c))
            binding.tvExpireTime.setTextColor(getColor(R.color.color_bcac8e))
            binding.tvExpireTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_mine_arrow1, 0)
            binding.ivVipBg.setImageResource(R.mipmap.ic_mine_vip_bg1)

            val vipBgLp = binding.ivVipBg.layoutParams as ConstraintLayout.LayoutParams
            vipBgLp.dimensionRatio = "h,1029:342"
            binding.ivVipBg.layoutParams = vipBgLp
        } else if (userInfo?.vip == "2") {
            isEnterprise = false

            binding.tvVipName.text = "普通会员"
            binding.tvExpireTime.text = "${userInfo!!.vip_expire} 会员到期"

            binding.tvVipName.setTextColor(getColor(R.color.color_fbcd8c))
            binding.tvExpireTime.setTextColor(getColor(R.color.color_bcac8e))
            binding.tvExpireTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_mine_arrow1, 0)
            binding.ivVipBg.setImageResource(R.mipmap.ic_mine_vip_bg1)

            val vipBgLp = binding.ivVipBg.layoutParams as ConstraintLayout.LayoutParams
            vipBgLp.dimensionRatio = "h,1029:342"
            binding.ivVipBg.layoutParams = vipBgLp
        } else if (userInfo?.vip == "3") {
            isEnterprise = false

            binding.tvVipName.text = "终生会员"
            binding.tvExpireTime.text = "享受永久会员专属权益"

            binding.tvVipName.setTextColor(getColor(R.color.color_fbcd8c))
            binding.tvExpireTime.setTextColor(getColor(R.color.color_bcac8e))
            binding.tvExpireTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_mine_arrow1, 0)
            binding.ivVipBg.setImageResource(R.mipmap.ic_mine_vip_bg1)

            val vipBgLp = binding.ivVipBg.layoutParams as ConstraintLayout.LayoutParams
            vipBgLp.dimensionRatio = "h,1029:342"
            binding.ivVipBg.layoutParams = vipBgLp
        } else if (userInfo?.vip == "12") {
            isEnterprise = true

            binding.tvVipName.text = "普通企业"
            binding.tvExpireTime.text = "${userInfo!!.vip_expire} 会员到期"

            binding.tvVipName.setTextColor(getColor(R.color.color_c5ffe1))
            binding.tvExpireTime.setTextColor(getColor(R.color.color_a6c8ba))
            binding.tvExpireTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_mine_arrow2, 0)
            binding.ivVipBg.setImageResource(R.mipmap.ic_mine_vip_bg2)

            val vipBgLp = binding.ivVipBg.layoutParams as ConstraintLayout.LayoutParams
            vipBgLp.dimensionRatio = "h,1029:309"
            binding.ivVipBg.layoutParams = vipBgLp
        } else if (userInfo?.vip == "11") {
            isEnterprise = true

            binding.tvVipName.text = "终生企业"
            binding.tvExpireTime.text = "享受永久会员专属权益"

            binding.tvVipName.setTextColor(getColor(R.color.color_c5ffe1))
            binding.tvExpireTime.setTextColor(getColor(R.color.color_a6c8ba))
            binding.tvExpireTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_mine_arrow2, 0)
            binding.ivVipBg.setBackgroundResource(R.mipmap.ic_mine_vip_bg2)

            val vipBgLp = binding.ivVipBg.layoutParams as ConstraintLayout.LayoutParams
            vipBgLp.dimensionRatio = "h,1029:309"
            binding.ivVipBg.layoutParams = vipBgLp
        }
        binding.tvUsername.text = userInfo?.name
        binding.tvUserId.text = "ID:${userInfo?.user_id}"
        binding.btnLogin.visibility = if (LoginManager.isLogin()) View.GONE else View.VISIBLE
        binding.tvSeatManage.visibility = if (isEnterprise || userInfo!!.is_show_crop_add) View.VISIBLE else View.GONE
        binding.tvShare.visibility = if (UserConfigManager.getShareEntity() != null) View.VISIBLE else View.GONE
    }
}