package com.example.defenseapplication.liveVideo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.defenseapplication.R
import com.example.defenseapplication.bean.DeleteDeviceUserRequest
import com.example.defenseapplication.bean.ObtainInviterInformationRequest
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.DeviceUserUpdateEvent
import com.example.defenseapplication.databinding.UserDetailsActivityBinding
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.CustomDialogFragmentText
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//用户详情页面
class UserDetailsActivity : AppCompatActivity() {
    private lateinit var binding: UserDetailsActivityBinding

    private var userId: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = UserDetailsActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBar(binding.topBar)
            .init()

        initData()
        initListener()
        fetchInviterInformation()
    }

    private fun initData() {
        userId = intent.getStringExtra("userId") ?: ""
    }

    private fun fetchInviterInformation() {
        if (userId.isEmpty()) {
            Toast.makeText(this, "用户ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            try {
                val request = ObtainInviterInformationRequest(childId = userId)
                val response = RetrofitNetwork.getNetworkService().obtainInviterInformation(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        updateUI(response.data!!)
                    } else {
                        Toast.makeText(this@UserDetailsActivity, response.msg ?: "获取信息失败", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@UserDetailsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateUI(data: com.example.defenseapplication.bean.ObtainInviterInformationBean) {
        binding.tvContactName.text = data.nickName ?: "未知用户"
        binding.tvPhone.text = data.phonenumber ?: ""
        binding.tvIdCard.text = data.idCard ?: ""
        binding.tvMacAddress.text = data.mac ?: ""
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.swUserStatus.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> {
                    // 打开开关业务逻辑
                }
                false -> {
                    // 关闭开关业务逻辑
                }
            }
        }

        binding.btnDelete.setOnClickListener {
            showDeleteDialog()
        }
    }


    private fun showDeleteDialog() {
        val dialog = CustomDialogFragmentText()
        dialog.setTitle(getString(R.string.tip))
        dialog.setMessage(getString(R.string.confirm_delete_user))
        dialog.setShowInput(false)
        dialog.setPositiveText(getString(R.string.confirm))
        dialog.setNegativeText(getString(R.string.cancel))
        dialog.setOnConfirmListener {
            deleteDeviceUser()
        }
        dialog.show(supportFragmentManager, "DeleteUserDialog")
    }

    private fun deleteDeviceUser() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty() || userId.isEmpty()) {
            Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show()
            return
        }

        lifecycleScope.launch {
            try {
                val request = DeleteDeviceUserRequest(
                    userId = userId,
                    deviceId = deviceId
                )
                val response = RetrofitNetwork.getNetworkService().deleteDeviceUser(request)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        Toast.makeText(this@UserDetailsActivity, "删除成功", Toast.LENGTH_SHORT).show()
                        DeviceUserUpdateEvent.notifyUpdate()
                        finish()
                    } else {
                        Toast.makeText(this@UserDetailsActivity, response.msg ?: "删除失败", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@UserDetailsActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
