package com.zxhl.main.page.fragment

import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.tencent.imsdk.v2.V2TIMGroupInfoResult
import com.tencent.liteav.basic.UserModelManager
import com.tencent.liteav.trtcvoiceroom.model.VoiceRoomManager
import com.tencent.liteav.trtcvoiceroom.model.VoiceRoomManager.GetGroupInfoCallback
import com.tencent.liteav.trtcvoiceroom.ui.room.VoiceRoomAnchorActivity
import com.tencent.liteav.trtcvoiceroom.ui.room.VoiceRoomAudienceActivity
import com.tencent.trtc.TRTCCloudDef
import com.zxhl.cms.common.base.BaseFragment
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.chat.ChatRoomEntity
import com.zxhl.cms.net.model.uc.UserInfo
import com.zxhl.cms.utils.OnRecycleItemClickListener
import com.zxhl.cms.utils.RecyclerViewScrollListener
import com.zxhl.main.R
import com.zxhl.main.page.adapter.RoomAdapter
import com.zxhl.main.page.contract.RoomContract
import com.zxhl.main.page.presenter.RoomPresenter
import kotlinx.android.synthetic.main.activity_layout_create_room.*
import kotlinx.android.synthetic.main.fragment_layout_one.*

class OneFragment : BaseFragment, RoomContract.View, OnRecycleItemClickListener<ChatRoomEntity> {
    private val title: String
    private var mPresenter: RoomPresenter? = null
    private var mAdapter: RoomAdapter? = null

    constructor(title: String) : super() {
        this.title = title
    }


    override fun layoutID(): Int {
        return R.layout.fragment_layout_one
    }

    override fun init(view: View?) {
        mPresenter = RoomPresenter(this)
        mAdapter = RoomAdapter(mActivity, this)
        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 (p0 == 0) {
                    return gridLayoutManager.spanCount
                } else {
                    if (type == mAdapter?.LOADMORE) {
                        return gridLayoutManager.spanCount
                    } else {
                        return 1
                    }
                }
            }
        }
        id_rl_room_list?.setLayoutManager(gridLayoutManager)
        id_rl_room_list?.adapter = mAdapter
        mPresenter?.getRoomList(true, this.title)
        id_refresh_layout?.setColorSchemeColors(resources.getColor(com.zxhl.cms.R.color.color_aa60ff))
        id_refresh_layout?.setOnRefreshListener {
            mPresenter?.getRoomList(true, this.title)
        }
        id_rl_room_list?.addOnScrollListener(object : RecyclerViewScrollListener() {
            override fun onScrollToBottom() {
                super.onScrollToBottom()
                if (mAdapter?.getLoadMore() == true) {
                    mPresenter?.getRoomList(false, title)
                }
            }
        })
    }

    override fun lazyLoad() {
        super.lazyLoad()

    }

    companion object {
        fun newInstance(string: String): OneFragment {
            return OneFragment(string)
        }
    }

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

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

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

    override fun onItemClick(view: View?, position: Int, data: ChatRoomEntity?) {
        when (view?.id) {
            R.id.id_item -> {
                Log.e("MXL", "点击" + position)
                VoiceRoomManager.getInstance()
                    .getGroupInfo(data?.audioId, object : GetGroupInfoCallback {
                        override fun onSuccess(result: V2TIMGroupInfoResult) {
                            if (isRoomExist(result)) {
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupType ================================="
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.onlineCount " + result.groupInfo.onlineCount
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupID " + result.groupInfo.groupID
                                );
                                Log.d("wxw", "result.groupInfo.owner " + result.groupInfo.owner);
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.memberCount " + result.groupInfo.memberCount
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.createTime " + result.groupInfo.createTime
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupAddOpt " + result.groupInfo.groupAddOpt
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupName " + result.groupInfo.groupName
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupType " + result.groupInfo.groupType
                                );
                                Log.d(
                                    "wxw",
                                    "result.groupInfo.groupType ================================="
                                );
                                val user = SettingPreference.getUserInfoData()
                                if (user == null) {
                                    showToast("未查到用户信息，请重新登录")
                                    return;
                                }
                                //自己创建的房间
                                if (result.groupInfo.owner.equals(user.uid.toString())) {
                                    if (data != null && !data.audioId.equals("")) {
                                        realEnterOwnerRoom(data.audioId!!, user, data)
                                    } else {
                                        ToastUtils.showLong("房间信息有误");
                                    }
                                } else {
                                    //进入其他人创建的房间
                                    if (data != null && !data.audioId.equals("")) {
                                        realEnterRoom(data.audioId.toString(), user, data)
                                    } else {
                                        ToastUtils.showLong("房间信息有误");
                                    }
                                }
                            } else {
                                ToastUtils.showLong("房间不存在了")
                            }
                        }

                        override fun onFailed(code: Int, msg: String) {
                            ToastUtils.showLong(msg)
                        }
                    })
            }
        }
    }

    private fun realEnterRoom(
        roomIdStr: String?, userInfo: UserInfo,
        chatRoomEntity: ChatRoomEntity
    ) {
        val userId = userInfo.uid.toString()
        val roomId: Int
        roomId = try {
            roomIdStr!!.toInt()
        } catch (e: Exception) {
            10000
        }
        Log.d("wxw", "enterRoom userId $userId")
        mPresenter?.inRoom(chatRoomEntity.id.toString())
        VoiceRoomAudienceActivity.enterRoom(
            mActivity,
            chatRoomEntity.id,
            roomId,
            userId,
            TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT
        )
    }

    private fun realEnterOwnerRoom(
        roomIdStr: String,
        userInfo: UserInfo,
        chatRoomEntity: ChatRoomEntity
    ) {
        Log.d(
            "wxw",
            "enterOwnerRoom userId " + userInfo.uid.toString() + " isNeed " + chatRoomEntity.wheatType+ " roomIdStr " + chatRoomEntity.audioId
        )
        VoiceRoomAnchorActivity.createRoom(
            context,
            chatRoomEntity.id,
            roomIdStr.toInt(),
            chatRoomEntity.roomName,
            userInfo.uid.toString(),
            userInfo.nickname,
            chatRoomEntity.notice,
            chatRoomEntity.roomCover,
            TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT,
            chatRoomEntity.wheatType == 0
        )
    }

    private fun isRoomExist(result: V2TIMGroupInfoResult?): Boolean {
        if (result == null) {
            return false
        }
        return result.resultCode == 0
    }
}