package com.example.defenseapplication.liveVideo

import android.content.Intent
import android.graphics.Color
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import java.util.Calendar
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.defenseapplication.R
import com.example.defenseapplication.databinding.AutoModeActivityBinding
import com.example.defenseapplication.utils.DeviceIdEvent
import com.example.defenseapplication.utils.DeviceUpdateEvent
import com.example.defenseapplication.utils.RetrofitNetwork
import com.example.defenseapplication.view.AutoModeNoticeDialog
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Locale

//自动模式
class AutoModeActivity : AppCompatActivity() {

    private lateinit var binding: AutoModeActivityBinding
    private var selectedMode = "0"
    private var selectedStartHour = 8
    private var selectedStartMinute = 0
    private var selectedEndHour = 10
    private var selectedEndMinute = 0

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

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

        initListener()

        loadCurrentSettings()
    }

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

        binding.rbAutoMode.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectedMode = "0"
                binding.time.visibility = android.view.View.VISIBLE
                showAutoModeNoticeDialog()
            }
        }

        binding.rbSemiAutoMode.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                selectedMode = "1"
                binding.time.visibility = android.view.View.GONE
            }
        }

        binding.itemStartTime.setOnClickListener {
            showTimePicker(true) { hour, minute ->
                selectedStartHour = hour
                selectedStartMinute = minute
                val startTimeStr = String.format("%02d:%02d", hour, minute)
                binding.tvStartTime.text = startTimeStr
            }
        }

        binding.itemEndTime.setOnClickListener {
            showTimePicker(false) { hour, minute ->
                selectedEndHour = hour
                selectedEndMinute = minute
                val endTimeStr = String.format("%02d:%02d", hour, minute)
                binding.tvEndTime.text = endTimeStr
            }
        }
    }

    private fun loadCurrentSettings() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val response = RetrofitNetwork.getNetworkService().getDeviceInfo(deviceId)
                withContext(Dispatchers.Main) {
                    if (response.code == 200 && response.data != null) {
                        response.data.workMode?.let { mode ->
                            selectedMode = mode
                            if (mode == "0") {
                                binding.rbAutoMode.isChecked = true
                                binding.rbSemiAutoMode.isChecked = false
                                binding.time.visibility = android.view.View.VISIBLE
                            } else {
                                binding.rbAutoMode.isChecked = false
                                binding.rbSemiAutoMode.isChecked = true
                                binding.time.visibility = android.view.View.GONE
                            }
                        }
                        binding.tvStartTime.text = response.data.startTime?.formatToHourMinute()
                        binding.tvEndTime.text=response.data.endTime?.formatToHourMinute()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    private fun String.formatToHourMinute(): String {
        return try {
            val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            val outputFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
            val date = inputFormat.parse(this)
            outputFormat.format(date)
        } catch (e: Exception) {
            this // 解析失败返回原字符串
        }
    }

    private fun showTimePicker(isStartTime: Boolean, onTimeSelected: (hour: Int, minute: Int) -> Unit) {
        val currentHour = if (isStartTime) selectedStartHour else selectedEndHour
        val currentMinute = if (isStartTime) selectedStartMinute else selectedEndMinute

        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, currentHour)
        calendar.set(Calendar.MINUTE, currentMinute)

        val timePicker = TimePickerBuilder(this, OnTimeSelectListener { date, _ ->
            val selectedCalendar = Calendar.getInstance()
            selectedCalendar.time = date
            onTimeSelected(selectedCalendar.get(Calendar.HOUR_OF_DAY), selectedCalendar.get(Calendar.MINUTE))
        })
            .setType(booleanArrayOf(false, false, false, true, true, false)) // 时分
            .setTitleText(getString(R.string.select_time))
            .setSubmitColor(Color.parseColor("#09C2BD"))//确定按钮文字颜色
            .setCancelColor(Color.parseColor("#09C2BD"))//取消按钮文字颜色
            .setSubCalSize(18)//确定和取消文字大小
            .setTextColorCenter(Color.parseColor("#09C2BD"))//选中颜色
            .setLineSpacingMultiplier(2.5f)//行间距倍数
            .setItemVisibleCount(5)//可见项数量
            .setDate(calendar)
            .build()
        timePicker.show()
    }

    private fun showAutoModeNoticeDialog() {
        val dialog = AutoModeNoticeDialog(this)
        dialog.show()
    }

    private fun saveAutoModeSettings() {
        val deviceId = DeviceIdEvent.getDeviceId()
        if (deviceId.isNullOrEmpty()) {
            Toast.makeText(this, "设备ID为空", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        val startTime = binding.tvStartTime.text.toString()
        val endTime = binding.tvEndTime.text.toString()

        CoroutineScope(Dispatchers.IO).launch {
            try {
                val deviceBean = com.example.defenseapplication.bean.DeviceBean(
                    id = deviceId,
                    workMode = selectedMode,
                    startTime = startTime,
                    endTime = endTime
                )
                val response = RetrofitNetwork.getNetworkService().updateDeviceInfo(deviceBean)
                withContext(Dispatchers.Main) {
                    if (response.code == 200) {
                        val modeText = if (selectedMode == "0") {
                            getString(R.string.full_auto_mode)
                        } else {
                            getString(R.string.semi_auto_mode)
                        }
                        val resultIntent = Intent()
                        resultIntent.putExtra("auto_mode", modeText)
                        resultIntent.putExtra("auto_mode_value", selectedMode)
                        setResult(RESULT_OK, resultIntent)
                        Toast.makeText(this@AutoModeActivity, "修改成功", Toast.LENGTH_SHORT).show()
                        DeviceUpdateEvent.notifyDeviceUpdated(deviceId)
                    } else {
                        Toast.makeText(this@AutoModeActivity, response.msg, Toast.LENGTH_SHORT).show()
                    }
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@AutoModeActivity, "网络请求失败", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }
        }
    }
}
