package com.zxhl.main.page.fragment

import android.media.MediaPlayer
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.down.UpdateVersionManager
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.HomeListEntity
import com.zxhl.cms.net.model.chat.ChatMessageChargeOrNotEntity
import com.zxhl.cms.net.model.chat.ChatStausEvent
import com.zxhl.cms.net.model.chat.DistanceEntity
import com.zxhl.cms.net.model.chat.RecommendEntity
import com.zxhl.cms.utils.*
import com.zxhl.cms.utils.ChatMessageChargeUtils.getChatMessageChargeOrNot
import com.zxhl.cms.utils.UserDataUtils.updateUserInfo
import com.zxhl.cms.widget.ChatDialogUtils
import com.zxhl.cms.widget.ChatDialogUtils.ChatDialogCallBack
import com.zxhl.cms.widget.ChatDialogUtils.ChatDialogCallBackParams
import com.zxhl.cms.widget.MemberDialogUtils
import com.zxhl.cms.widget.RecyclerViewSpacesItemDecoration
import com.zxhl.main.R
import com.zxhl.main.page.adapter.UserAdapter
import com.zxhl.main.page.contract.HomeContract
import com.zxhl.main.page.presenter.HomePresenter
import com.zxhl.main.page.view.AccostDialog
import com.zxhl.main.page.view.DialogUtils
import com.zxhl.main.page.view.SignDialog
import kotlinx.android.synthetic.main.fragment_popular.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * Created by gaoleichao on 2021/10/25
 */
class PopularFragment : BaseFragment(), HomeContract.View, OnRecycleItemClickListener<HomeListEntity>,
    UpdateCallback ,AdCallback<String>{
    private var mPresenter: HomePresenter? = null
    private var mAdapter: UserAdapter? = null
    private var mMediaPlayer: MediaPlayer? = null
    override fun layoutID(): Int {

        return R.layout.fragment_popular
    }

    override fun lazyLoad() {
        super.lazyLoad()
        if (isInitial && isVisible) {
            updateUserInfo(AdCallback { code, result ->

            })
        }

    }

    override fun init(view: View?) {
        EventBus.getDefault().register(this)
//        id_img_banner?.setOnClickListener {
//            JumpUtils.BannerDetailJump()
//        }
        mMediaPlayer = MediaPlayer()
        val updateVersionManager = this?.let { it1 -> UpdateVersionManager(mActivity, this) }
        updateVersionManager?.checkUpdate(true)
        mPresenter = HomePresenter(this)
        mAdapter = UserAdapter(mActivity, this)
        mAdapter?.setHasStableIds(true)
        val gridLayoutManager: GridLayoutManager = object : GridLayoutManager(mActivity, 2) {
            override fun canScrollVertically(): Boolean {
                return true
            }
        }
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(p0: Int): Int {
                val type = mAdapter?.getItemViewType(p0)
                if(type==mAdapter?.LOADMORE){
                    return gridLayoutManager.spanCount
                }else{
                    return 1
                }

            }

        }
        //  val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        //  layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        id_home_rl?.setLayoutManager(gridLayoutManager)
        val stringIntegerHashMap: HashMap<String, Int> = HashMap()
//        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.TOP_DECORATION] =
//            Utils.dip2px(5) //top间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION] =
            Utils.dip2px(5) //底部间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.LEFT_DECORATION] =
            Utils.dip2px(5)//左间距
        stringIntegerHashMap[RecyclerViewSpacesItemDecoration.RIGHT_DECORATION] =
            Utils.dip2px(5) //右间距
        id_home_rl?.addItemDecoration(
            RecyclerViewSpacesItemDecoration(
                stringIntegerHashMap
            )
//            StaggeredDividerItemDecoration(
//                context,
//                Utils.dip2px(5).toFloat(),
//                2
//            )
        )
        id_home_rl?.adapter = mAdapter
        (id_home_rl?.itemAnimator as SimpleItemAnimator).setSupportsChangeAnimations(false)
        id_home_rl?.itemAnimator?.changeDuration = 0
        id_home_rl?.itemAnimator = null
        id_home_rl?.addOnScrollListener(object : RecyclerViewScrollListener() {
            override fun onScrollToBottom() {
                super.onScrollToBottom()
//                if ((mAdapter?.list?.size ?: 0) > 0) {
//                    mPresenter?.getHomeList(false)
//                }
                if (mAdapter?.getLoadMore() == true) {
                    ifChareOrNot(false)
                }
            }
        })
        id_refresh_layout?.setColorSchemeColors(resources.getColor(com.zxhl.cms.R.color.color_aa60ff))
        id_refresh_layout?.setOnRefreshListener {
            //helper=null
            ifChareOrNot(true)
//
        }
        ifChareOrNot(true)
//        helper = OnItemEnterOrExitVisibleHelper()
//        helper?.setRecyclerScrollListener(id_home_rl)
//        helper?.setOnScrollStatusListener(this)
    }

    private var content = "开启会员解锁首页无限查看用户权限"
    private var tipcontent = "星币解锁本次"
    private var free: Int = 0
    fun ifChareOrNot(refsh: Boolean) {
        getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_HOME_PULL,
            "",
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        free = 0
                        mPresenter?.getHomeList(refsh, free,"popular")
                    } else {
                        id_refresh_layout?.isRefreshing = false
                        free = 1

                        ChatDialogUtils.showMemberChargeTip(
                            mActivity,
                            result,
                            content,
                            tipcontent,
                            object : ChatDialogCallBackParams {
                                override fun confirm(type: Int) {
                                    //兑换
                                    if (type == 0) {
                                        if (SettingPreference.getUserInfoData() != null
                                            && SettingPreference.getUserInfoData().starBalance < result.charge
                                        ) {
                                            ChatDialogUtils.showMemberTrip(
                                                mActivity,
                                                object : ChatDialogCallBack {
                                                    override fun confirm() {
                                                        JumpUtils.starCoinpayJump()
                                                    }

                                                    override fun cancel() {}
                                                })
                                        } else {
                                            ifChareOrNot(true)
                                        }

                                    } else {
                                        JumpUtils.payJump()
                                    }
                                }

                                override fun cancel() {}
                            })
                        return
                    }
                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })
    }

    private var isPause = false

    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onResume() {
        super.onResume()
        if (isPause && !TextUtils.isEmpty(SettingPreference.getLikeUserId())) {
            if (mAdapter != null) {
                mAdapter?.updateUserLikeStatus(SettingPreference.getLikeUserId())
            }
        }
        if (isPause && isVisible) {
           // Log.e("MXL", "查询个人信息")
            updateUserInfo(AdCallback { code, result ->
                //    UpdateUserInfo()
            })

        }
        isPause = false
    }

    override fun setHomeData(isRefresh: Boolean, reslut: List<HomeListEntity>?) {
        id_refresh_layout?.isRefreshing = false
        if (isRefresh) {
            if (mAdapter != null) {
                mAdapter?.clear()
            }
        }
        val start = mAdapter?.getItemCount() ?: 0
        mAdapter?.appendToList(reslut)
        if (isRefresh) {
            mAdapter?.notifyDataSetChanged()
        } else {
            val end = mAdapter?.getItemCount() ?: 0
            mAdapter?.notifyItemRangeChanged(start, end)
        }
    }

    override fun setLoadMore(isBoolean: Boolean) {
        mAdapter?.setLoadMore(isBoolean)
    }

    override fun getHomeDataFail() {
        id_refresh_layout?.isRefreshing = false
    }

    var chatEntity:HomeListEntity?=null
    override fun onItemClick(view: View?, position: Int, data: HomeListEntity?) {
        when (view?.id) {
            R.id.id_tv_chat_status -> {
                chatEntity=data
                JumpUtils.startC2CChatActivity(chatEntity?.chatStatus!!,data?.uid, data?.nickname)
            }
            R.id.id_rl_play_audio -> {
                EventUtils.onEvent("HomeAudioPlay",data?.uid.toString())
                //    mAdapter?.setHasStableIds(true)
                mAdapter?.updateOtherPlayStatus(false)
                if (recordPotision != position) {
                    recordPotision = position
                    playSound(data?.voice, position)
                } else {
                    recordPotision = -1
                    if (mMediaPlayer!!.isPlaying) {
                        mMediaPlayer!!.stop()
                        return
                    }
                }

            }

            R.id.id_img_home_like -> {
                likePositon = position
                like(data?.uid.toString())
                EventUtils.onEvent("HomeSuperLike",data?.uid.toString())
                // mPresenter?.likeUser(data?.id)
            }
            R.id.id_tv_chakan_juli -> {
                distancePosition = position
                EventUtils.onEvent("HomeDistanceCheck",data?.uid.toString())
                viewDistance(data?.uid.toString(), position)
            }
            R.id.id_rl_item -> {
                EventUtils.onEvent("HomeUserClick",data?.uid.toString())
                JumpUserDetails(data?.uid.toString())
            }

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(chatStausEvent: ChatStausEvent){
        chatEntity?.chatStatus=chatStausEvent.chatstatus?.toInt()
        mAdapter?.notifyDataSetChanged()
    }

    var detailFree=0
    //跳转详情
    fun JumpUserDetails(userId: String){
        getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_LOOK_USER_HOME,
            userId,
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        detailFree = 0
                        JumpUtils.UserDetailJump(userId, detailFree.toString())
                    } else {
                        detailFree = 1
                        ChatDialogUtils.showMemberChargeTip(
                            mActivity,
                            result,
                            "开启会员解锁无限查看用户权限",
                            "星币解锁当前用户查看",
                            object : ChatDialogCallBackParams {
                                override fun confirm(type: Int) {
                                    //兑换
                                    if (type == 0) {
                                        if (SettingPreference.getUserInfoData() != null
                                            && SettingPreference.getUserInfoData().starBalance < result.charge
                                        ) {
                                            ChatDialogUtils.showMemberTrip(
                                                mActivity,
                                                object : ChatDialogCallBack {
                                                    override fun confirm() {
                                                        JumpUtils.starCoinpayJump()
                                                    }

                                                    override fun cancel() {}
                                                })
                                        } else {
                                            JumpUtils.UserDetailJump(userId, detailFree.toString())
                                        }

                                    } else {
                                        JumpUtils.payJump()
                                    }
                                }

                                override fun cancel() {}
                            })
                        return
                    }
                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })
    }
    var distancePosition: Int = -1
    var distanceFree: Int = 0

    //查看距离
    fun viewDistance(userId: String, position: Int) {

        getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_LOOK_DISTANCE,
            userId,
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        distanceFree = 0
                        mPresenter?.getDistance(distanceFree, userId)
                    } else {
                        distanceFree = 1
                        ChatDialogUtils.showMemberChargeTip(
                            mActivity,
                            result,
                            "开启会员解锁无限查看距离权限",
                            "星币解锁当前用户距离",
                            object : ChatDialogCallBackParams {
                                override fun confirm(type: Int) {
                                    //兑换
                                    if (type == 0) {
                                        if (SettingPreference.getUserInfoData() != null
                                            && SettingPreference.getUserInfoData().starBalance < result.charge
                                        ) {
                                            ChatDialogUtils.showMemberTrip(
                                                mActivity,
                                                object : ChatDialogCallBack {
                                                    override fun confirm() {
                                                        JumpUtils.starCoinpayJump()
                                                    }

                                                    override fun cancel() {}
                                                })
                                        } else {
                                            mPresenter?.getDistance(distanceFree, userId)
                                        }

                                    } else {
                                        JumpUtils.payJump()
                                    }
                                }

                                override fun cancel() {}
                            })
                        return
                    }
                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })

    }

    override fun distanceSuc(reslut: DistanceEntity?) {
        mAdapter?.getDistanceSuc(distancePosition, reslut?.distance.toString())
    }

    override fun distanceFail() {
        //showToast("获取距离失败")
    }

    private var likePositon: Int = -1
    private var likeFree: String = "0"

    //超级喜欢
    fun like(userId: String) {
        getChatMessageChargeOrNot(
            "" + ChatMessageChargeUtils.MESSAGE_SUPER_LOVE,
            userId,
            object : ChatCallback<ChatMessageChargeOrNotEntity> {
                override fun onResult(result: ChatMessageChargeOrNotEntity?) {
                    if (result?.charge!! <= 0) {
                        likeFree = "0"
                        mPresenter?.likeUser(userId, likeFree)
                    } else {
                        id_refresh_layout?.isRefreshing = false
                        likeFree = "1"
                        if (SettingPreference.getUserInfoData() != null && SettingPreference.getUserInfoData().memberType == 1) {
                            MemberDialogUtils.showMemberChargeTip(
                                mActivity,
                                result,
                                "今日赠送超级喜欢已经用完",
                                "星币解锁本次超级喜欢",
                                object : ChatDialogCallBackParams {
                                    override fun confirm(type: Int) {
                                        //兑换
                                        if (type == 0) {
                                            if (SettingPreference.getUserInfoData() != null
                                                && SettingPreference.getUserInfoData().starBalance < result.charge
                                            ) {
                                                ChatDialogUtils.showMemberTrip(
                                                    mActivity,
                                                    object : ChatDialogCallBack {
                                                        override fun confirm() {
                                                            JumpUtils.starCoinpayJump()
                                                        }

                                                        override fun cancel() {}
                                                    })
                                            } else {
                                                mPresenter?.likeUser(userId, likeFree)
                                            }

                                        } else {
                                            JumpUtils.payJump()
                                        }
                                    }

                                    override fun cancel() {}
                                })
                            return
                        } else {
                            if (SettingPreference.getUserInfoData() != null
                                && SettingPreference.getUserInfoData().starBalance >= result.charge
                            ) {
                                mPresenter?.likeUser(userId, likeFree)
                            } else {
                                ChatDialogUtils.showMemberChargeTip(
                                    mActivity,
                                    result,
                                    "开启会员每日都会赠送超级喜欢哦",
                                    "星币解锁本次超级喜欢",
                                    object : ChatDialogCallBackParams {
                                        override fun confirm(type: Int) {
                                            //兑换
                                            if (type == 0) {
                                                if (SettingPreference.getUserInfoData() != null
                                                    && SettingPreference.getUserInfoData().starBalance < result.charge
                                                ) {
                                                    ChatDialogUtils.showMemberTrip(
                                                        mActivity,
                                                        object : ChatDialogCallBack {
                                                            override fun confirm() {
                                                                JumpUtils.starCoinpayJump()
                                                            }

                                                            override fun cancel() {}
                                                        })
                                                } else {
                                                    mPresenter?.likeUser(userId, likeFree)
                                                }

                                            } else {
                                                JumpUtils.payJump()
                                            }
                                        }

                                        override fun cancel() {}
                                    })
                            }


                            return
                        }
                    }

                }


                override fun onError(code: String?, errorMsg: String?) {
                    if (TextUtils.isEmpty(errorMsg)) {
                        return
                    }
                    Utils.showToast(context, errorMsg)
                }
            })
    }

    var recordPotision: Int = -1
    fun playSound(voice: String?, p: Int) {
        try {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.stop()
            }
            mMediaPlayer?.reset()
            mMediaPlayer?.isLooping = false
            mMediaPlayer?.setDataSource(mActivity, Uri.parse(voice))
            mMediaPlayer?.prepareAsync()
            mMediaPlayer?.setOnPreparedListener {
                mAdapter?.updateCurrentPlayStatus(true, p)
                mMediaPlayer?.start()


            }
            mMediaPlayer?.setOnCompletionListener {
                // mMediaPlayer?.start()
                mAdapter?.updateCurrentPlayStatus(false, p)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mMediaPlayer != null) {
            mMediaPlayer?.stop()
            mMediaPlayer?.release()
        }
        EventBus.getDefault().unregister(this)
    }

    //判断更新的回调
    override fun CheckUpate(boolean: Boolean) {
        Log.e("MXL", "判断完更新")
        updateUserInfo(this)
    }

    //领取新人奖励成功
    override fun newUserReceiveSuc() {
        requestSignReceive()
    }

    //领取新人奖励失败
    override fun newUserReceivefail() {
        requestSignReceive()
    }

    //超级喜欢成功
    override fun likeSuc() {
        mAdapter?.likeSuccess(likePositon, true)
    }

    //一键搭讪弹窗
    override fun setRecommend(reslut: RecommendEntity?) {
        if (reslut?.popup == 1) {
            AccostDialog.showAccostDialog(mActivity, reslut?.list)
        }
    }


    //去签到
    fun requestSignReceive() {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        if (user.signInPopup == 1) {
            SignDialog.showSignDialog(mActivity, View.OnClickListener {
                mPresenter?.getRecommend()
            })
        }
    }

    override fun onResult(code: Int, result: String?) {
        val user = SettingPreference.getUserInfoData()
        if (user == null) {
            return
        }
        Log.e("MXL",""+user.newUser)
//        if (TextUtils.equals("${user.newUser}", "1")) {
//            DialogUtils.showFirstGuide(mActivity, View.OnClickListener {
//                mPresenter?.getNewUserReceive()
//            })
//        } else if (user.signInPopup == 1) {
//            requestSignReceive()
//        } else {
//            mPresenter?.getRecommend()
//        }
    }

    companion object {

        fun newInstance() = PopularFragment()
    }
}