package com.ym.chat.activity

import android.text.TextUtils
import android.util.Log
import android.view.View
import com.tencent.imsdk.v2.*
import com.tencent.liteav.basic.AvatarConstant
import com.tencent.liteav.basic.UserModel
import com.tencent.liteav.basic.UserModelManager
import com.tencent.liteav.debug.GenerateTestUserSig
import com.tencent.liteav.trtccalling.model.TUICalling
import com.tencent.liteav.trtccalling.model.impl.TUICallingManager
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.trtc.TRTCCloud
import com.tencent.trtc.TRTCCloudDef
import com.ym.chat.R
import com.ym.chat.utils.TUIUtils
import com.zxhl.cms.common.base.BaseActivity
import kotlinx.android.synthetic.main.activity_video_call_demo.*
import java.util.*

/**
 * @author (wangXuewei)
 * @datetime 2022-03-31 14:05 GMT+8
 * @detail :
 */
class VideoCallDemoActivity : BaseActivity() {
    val TAG = "VideoCallDemoActivity"
    override fun init() {
        id_btn_login.setOnClickListener {
            login();
        }
        id_btn_call.setOnClickListener {
            call();
        }
        TRTCCloud.setLogLevel(TRTCCloudDef.TRTC_LOG_LEVEL_DEBUG)
        navigation()
    }

    override fun onClick(v: View?) {

    }

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

    private fun navigation() {
        val userModelManager: UserModelManager = UserModelManager.getInstance()
        if (TextUtils.isEmpty(userModelManager.userModel.userId)) {
            //Login
            Log.e(TAG, "LoginError")
        } else {
            //Main
            Log.e(TAG, "LoginSuccess id${userModelManager.userModel.userId}")
        }
    }


    private fun login() {
        val userId: String = et_userId.getText().toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(userId)) {
            Log.e(TAG, "userId is Empty")
            return
        }
        val manager = UserModelManager.getInstance()
        val userModel = manager.userModel
        userModel.phone = userId
        userModel.userId = userId
        userModel.userSig = GenerateTestUserSig.genTestUserSig(userId)
        manager.userModel = userModel
        val config = V2TIMSDKConfig()
        config.logLevel = V2TIMSDKConfig.V2TIM_LOG_DEBUG
        TUILogin.init(this, GenerateTestUserSig.SDKAPPID, null, object : V2TIMSDKListener() {
            override fun onKickedOffline() {
                Log.d(TAG, "You have been kicked off the line. Please login again!")
            }

            override fun onUserSigExpired() {
                Log.d(TAG, "Your user signature information has expired")
            }
        })
        TUILogin.login(userModel.userId, userModel.userSig, object : V2TIMCallback {
            override fun onError(code: Int, msg: String) {
                Log.d(TAG, "login fail code: $code msg:$msg")
            }

            override fun onSuccess() {
                Log.d(TAG, "login onSuccess id${userModel.userId}")
                Log.d(TAG, "login onSuccess userSig ${userModel.userSig}")
            }
        })
    }

    private fun getUserInfo() {
        val manager = UserModelManager.getInstance()
        val userModel = manager.userModel
        //先查询用户是否存在
        val userIdList: MutableList<String> = ArrayList()
        userIdList.add(userModel.userId)
        Log.d(TAG, "setUserInfo: userIdList = $userIdList")
        V2TIMManager.getInstance().getUsersInfo(
            userIdList,
            object : V2TIMValueCallback<List<V2TIMUserFullInfo>?> {
                override fun onError(code: Int, msg: String) {
                    Log.e(TAG, "get group info list fail, code:$code msg: $msg")
                }

                override fun onSuccess(resultList: List<V2TIMUserFullInfo>?) {
                    if (resultList == null || resultList.isEmpty()) {
                        return
                    }
                    val result = resultList[0]
                    val userName = result.nickName
                    val userAvatar = result.faceUrl
                    Log.d(TAG, "onSuccess: userName = $userName , userAvatar = $userAvatar")
                    //如果用户名和头像为空,则跳转设置界面进行设置
                    if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(userAvatar)) {
                        val avatarArr = AvatarConstant.USER_AVATAR_ARRAY
                        val index = Random().nextInt(avatarArr.size)
                        var mAvatarUrl = avatarArr[index]
                        setProfile("Test1", mAvatarUrl)
                    } else {
                        userModel.userAvatar = userAvatar
                        userModel.userName = userName
                        manager.userModel = userModel
                        //如果用户信息不为空,则直接进入主界面
                        Log.d(TAG, "onSuccess: userName = $userName , userAvatar = $userAvatar")
                    }
                }
            })
    }


    private fun setProfile(userName: String, mAvatarUrl: String) {
        if (TextUtils.isEmpty(userName)) {
            Log.e(TAG, "userName is Empty")
            return
        }
        val v2TIMUserFullInfo = V2TIMUserFullInfo()
        v2TIMUserFullInfo.faceUrl = mAvatarUrl
        v2TIMUserFullInfo.setNickname(userName)
        V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, object : V2TIMCallback {
            override fun onError(code: Int, desc: String) {
                Log.e(TAG, "set profile failed errorCode : $code errorMsg : $desc")
                //头像和昵称设置失败,也可以进入到主界面(头像和昵称都用默认值),不影响功能
            }

            override fun onSuccess() {
                Log.i(TAG, "set profile success.")
                //成功后保存用户数据
                val userModel = UserModelManager.getInstance().userModel
                userModel.userName = userName
                userModel.userAvatar = mAvatarUrl
                UserModelManager.getInstance().userModel = userModel
            }
        })
    }

    fun call() {
        TRTCCloud.setLogLevel(TRTCCloudDef.TRTC_LOG_LEVEL_DEBUG)
        val userIDs = arrayOfNulls<String>(1)
        userIDs[0] = "0000"
        TUICallingManager.sharedInstance().call(userIDs, TUICalling.Type.VIDEO)
    }


}