package com.casic.br.view.device.waterheater

import android.content.Intent
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.model.TimeConfigModel
import com.casic.br.utils.CommandManager
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.extensions.toJson
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.tuya.smart.android.device.enums.TimerDeviceTypeEnum
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.ITuyaDataCallback
import com.tuya.smart.sdk.bean.TimerTask
import kotlinx.android.synthetic.main.activity_time_config.*
import kotlinx.android.synthetic.main.include_base_title.*

/**
 * TODO 时间预约指令不对
 * */
class TimeConfigActivity : KotlinBaseActivity() {

    private val kTag = "TimeConfigActivity"
    private lateinit var deviceId: String
    private var selectedTime: String? = null
    private var selectedTemp: String? = null

    override fun initLayoutView(): Int = R.layout.activity_time_config

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        ImmerseStatusBarUtil.setColor(this, R.color.white.convertColor(this))

        leftBackView.setOnClickListener { finish() }
        titleView.text = "预约时间设定"
    }

    override fun initData() {
        deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        TuyaHomeSdk.getTimerInstance()
            .getTimerList("预约时间设定", deviceId, TimerDeviceTypeEnum.DEVICE, object :
                ITuyaDataCallback<TimerTask> {
                override fun onSuccess(result: TimerTask?) {
                    if (result == null) {
                        Log.e(kTag, "预约时间未设定")
                        return
                    }
                    Log.d(kTag, result.toJson())
                    if (result.timerList.isEmpty()) {
                        timeConfigSwitch.isChecked = false
                    } else {
                        timeConfigSwitch.isChecked = result.timerTaskStatus.isOpen
                        val last = result.timerList.last()

                        timeConfigView.text = last.time
                        val parseObject = JSONObject.parseObject(last.value)
                        tempConfigView.text =
                            String.format("水温:${parseObject["16"]}${resources.getString(R.string.temperature_unit)}")
                    }
                }

                override fun onError(errorCode: String?, errorMessage: String?) {

                }

            })
    }

    private val timeConfigLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data!!
                selectedTime = data.getStringExtra("selectedTime")
                selectedTemp = data.getStringExtra("selectedTemp")

                timeConfigView.text = selectedTime
                tempConfigView.text = String.format("水温:$selectedTemp")
            }
        }

    override fun initEvent() {
        timeConfigLayout.setOnClickListener {
            timeConfigLauncher.launch(Intent(this, AddTimeConfigActivity::class.java))
        }

        timeConfigSwitch.setOnClickListener {
            if (timeConfigSwitch.isChecked) {
                /**
                 * 循环次数，格式为 0000000，每一位数字的取值可以是
                 * 0：关闭
                 * 1：开启
                 * 从左至右依次表示周日、周一、周二、周三、周四、周五、周六。
                 * 如每个周一循环该任务，则取值为 0100000。
                 * 0000000 表示只执行一次，1111111 表示每天执行。
                 *
                 * 设备功能（dps）的操作任务的 JSON 格式表达方式，格式为 {"dps":{}, "time":""}，
                 * 其中 Raw 类型的 DP 需要转换格式，
                 * 转换方式为：new String(Base64.encodeBase64(HexUtil.hexStringToBytes(dps)))
                 * */

                if (timeConfigView.text.isNullOrBlank() || tempConfigView.text.isNullOrBlank()) {
                    "操作错误！请先设置定时参数".show(this)
                    timeConfigSwitch.isChecked = false
                    return@setOnClickListener
                }

//            val dps = mutableMapOf<String, Any>()
//            dps["16"] = selectedTemp!!
//            val time = mutableMapOf<String, String>()
//            time["time"] = selectedTime!!
//            val action =
//                "{\"dps\":" + JSONObject.toJSONString(dps) + "," + JSONObject.toJSONString(time)
//                    .replace("{", "").replace("}", "") + "}"
//            Log.d(kTag, "action: $action")
                /**
                 * {"dps":{"16":"36°C"},"time":"10:35"}
                 * */
                val timeConfig = TimeConfigModel()
                val dpsModel = TimeConfigModel.DpsModel()
                dpsModel.`_$16` = selectedTemp!!
                timeConfig.dps = dpsModel
                timeConfig.time = selectedTime!!

                CommandManager.addDeviceTimer(
                    "预约时间设定",
                    deviceId,
                    timeConfig.toJson(),
                    "0000000",
                    "热水器"
                )
            } else {
                CommandManager.deleteDeviceTimer("预约时间设定", deviceId)
            }
        }
    }
}