package com.ydl.component.rtc

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ToastUtils
import com.tencent.imsdk.v2.*
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.calling.basic.UserModel
import com.tencent.qcloud.tuicore.calling.basic.UserModelManager
import com.ydl.component.R
import com.ydl.component.rtc.bean.UserSigResponse
import com.ydl.component.rtc.http.MDTHttpImpl.Companion.getInstance
import com.ydl.ydlcommon.modular.ModularServiceManager.provide
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.api.service.IUserService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class MDTLoginActivity : AppCompatActivity() {
    private var mEditUserId: EditText? = null
    private var mButtonLogin: Button? = null
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initStatusBar()
        initView()
    }

    private fun initView() {
        mEditUserId = findViewById<View>(R.id.et_userId) as EditText
        initButtonLogin()
    }

    private fun initButtonLogin() {
        mButtonLogin = findViewById<View>(R.id.tv_login) as Button
        mButtonLogin!!.setOnClickListener {
            getSigin()
        }
    }

    @SuppressLint("CheckResult")
    private fun getSigin() {
        var user  = provide(
            IUserService::class.java
        ).getUserInfo()

        val uid = user?.uid

        mEditUserId!!.setText(uid)
        val userId = mEditUserId!!.text.toString().trim { it <= ' ' }
        if (TextUtils.isEmpty(userId)) {
            Toast.makeText(this, R.string.user_id_is_empty, Toast.LENGTH_SHORT).show()
            return
        }

        val manager = UserModelManager.getInstance()
        val userModel = manager.userModel
        uid?.let {uid ->
            getInstance().getSecret(UserSigResponse(uid))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    val data = response.data
                    if ("200" == response.code) {
                        userModel.appId = Integer.valueOf(data.appId)
                        userModel.phone = userId
                        userModel.userId = userId
                        userModel.userSig = data.userSig
                        userModel.userAvatar =user?.head
                        userModel.userName =user?.nick_name
                        manager.userModel = userModel
                        login(userModel)
                    } else {
                        ToastUtil.toastShort(response.msg)
                    }
                }, { error ->
                    ToastUtil.toastShort(error.message)
                })
        }


    }

    private fun login(userModel: UserModel) {
        val config = V2TIMSDKConfig()
        config.logLevel = V2TIMSDKConfig.V2TIM_LOG_DEBUG
        TUILogin.init(this, userModel.appId, null, object : V2TIMSDKListener() {
            override fun onKickedOffline() {}
            override fun onUserSigExpired() {}
        })
        TUILogin.login(userModel.userId, userModel.userSig, object : V2TIMCallback {
            override fun onError(code: Int, msg: String) {
                ToastUtils.showLong("登录IM失败，所有功能不可用[%d]%s", code, msg)
                Log.d(TAG, "login fail code: $code msg:$msg")
            }

            override fun onSuccess() {
                Log.d(TAG, "login onSuccess")
                userInfo
            }
        })
    }//如果用户信息不为空,则直接进入主界面//如果用户名和头像为空,则跳转设置界面进行设置

    //先查询用户是否存在
    private val userInfo: Unit
        private get() {
            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 intent = Intent(this@MDTLoginActivity, ProfileActivity::class.java)
                            startActivity(intent)
                            finish()
                        } else {
                            userModel.userAvatar = userAvatar
                            userModel.userName = userName
                            manager.userModel = userModel
                            //如果用户信息不为空,则直接进入主界面
                            val intent = Intent(this@MDTLoginActivity, MDTMainActivity::class.java)
                            startActivity(intent)
                            finish()
                        }
                    }
                })
        }

    private fun initStatusBar() {
        val window = window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }

    companion object {
        private const val TAG = "LoginActivity"
    }
}