package com.casic.br.view.device

import android.graphics.Color
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.casic.br.R
import com.casic.br.extensions.createCommand
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.utils.CommandManager
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.IDevListener
import com.tuya.smart.sdk.api.ITuyaDevice
import com.tuya.smart.sdk.bean.DeviceBean
import kotlinx.android.synthetic.main.activity_range_hood.*
import kotlinx.android.synthetic.main.activity_water_heater.deviceLogoView
import kotlinx.android.synthetic.main.activity_water_heater.rootView
import kotlinx.android.synthetic.main.include_device_title.*

/**
 * 油烟机
 * */
class RangeHoodActivity : KotlinBaseActivity() {

    private val kTag = "RangeHoodActivity"
    private val gson by lazy { Gson() }
    private lateinit var deviceId: String
    private lateinit var deviceInstance: ITuyaDevice
    private var deviceBean: DeviceBean? = null
    private var isDeviceWorking = false

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

    override fun observeRequestState() {

    }

    override fun setupTopBarLayout() {
        initLayoutImmersionBar(rootView)
        ImmersionBar.with(this).statusBarDarkFont(true).init()

        leftBackView.setOnClickListener { finish() }
        titleView.text = "油烟机"
    }

    override fun initData() {
        deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        Log.d(kTag, "deviceId: $deviceId")

        //控制设备前必须初始家庭化数据，每次 App 活跃期间，初始化一次即可。
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)
    }

    override fun onResume() {
        super.onResume()
        deviceBean = TuyaHomeSdk.getDataInstance().getDeviceBean(deviceId)
        if (deviceBean == null) {
            "查询设备信息失败，请检查设备是否已离线".show(this)
            return
        }

        Glide.with(this)
            .load(deviceBean?.iconUrl)
            .placeholder(R.mipmap.load_image_error)
            .into(deviceLogoView)

        //查询单个 DP 数据，查询后的数据会通过 IDevListener.onDpUpdate() 接口进行异步回调。
        //每次获取焦点都查询设备的开关机状态
        CommandManager.getTuyaDp(deviceInstance, "1")
    }

    override fun initEvent() {
        rightOperateView.setOnClickListener {

        }

        //开关机
        switchButton.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "1".createCommand(!isDeviceWorking))
        }

        //低速
        lowSpeedView.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "10".createCommand("low"))
        }

        //高速
        highSpeedView.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "10".createCommand("high"))
        }

        //爆炒
        maxSpeedView.setOnClickListener {
            CommandManager.sendTuyaDp(deviceInstance, "10".createCommand("strong"))
        }

        //清洁
        cleanSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "101".createCommand(isChecked))
        }

        //照明
        lightSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "4".createCommand(isChecked))
        }

        //巡航
        cruiseSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "104".createCommand(isChecked))
        }

        //延时开关
        delayTurnOffSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "2".createCommand(isChecked))
        }

        //假日通风
        ventilateSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "102".createCommand(isChecked))
        }

        //假日通风时长
        val timeArray = arrayListOf(
            "10", "20", "30", "40", "50", "60", "70", "80", "90", "100", "110", "120"
        )
        ventilateTimeLayout.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(timeArray)
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        CommandManager.sendTuyaDp(
                            deviceInstance, "103".createCommand(timeArray[position].toInt())
                        )
                    }
                }).build().show()
        }

        //防倒灌
        antiPourDownSwitch.setOnCheckedChangeListener { _, isChecked ->
            CommandManager.sendTuyaDp(deviceInstance, "108".createCommand(isChecked))
        }

        deviceInstance.registerDevListener(object : IDevListener {

            /**
             * DP 数据更新
             *
             * @param devId 设备 ID
             * @param dpStr 设备发生变动的功能点，为 JSON 字符串，数据格式：{"101": true}
             */
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d(kTag, "onDpUpdate: $dpStr")
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    when (it) {
                        "1" -> {//开关机
                            isDeviceWorking = parseObject[it] as Boolean
                            if (isDeviceWorking) {
                                //工作中
                                deviceStateButton.text = "关机"
                            } else {
                                //未工作
                                deviceStateButton.text = "开机"
                            }
                        }
                        "2" -> {//延时关机状态,{"105":90,"11":"delay","2":true}｜{"11":"low","2":false}
                            val isDelay = parseObject[it] as Boolean
                            if (!isDelay) {
                                delayTimeView.text = "已取消"
                            }
                            delayTurnOffSwitch.isChecked = isDelay
                        }
                        "4" -> {//照明
                            val isLighting = parseObject[it] as Boolean
                            lightSwitch.isChecked = isLighting
                        }
                        "10" -> {//风速

                        }
                        "11" -> {//设备状态，[off, low, high, strong, air, fangdaoguan, wash, delay, xunhang]
                            val status = parseObject[it] as String
                            deviceStateView.text = if (status == "off") {
                                "已关机"
                            } else {
                                "工作中"
                            }
                        }
                        "12" -> {//累计工作时间
                            workingTimeView.text = if (isDeviceWorking) {
                                "${parseObject[it]}分"
                            } else {
                                "0分"
                            }
                        }
                        "101" -> {//清洁,{"10":"off","101":true,"11":"wash"}｜{"101":false,"11":"off"}
                            val isCleaning = parseObject[it] as Boolean
                            cleanSwitch.isChecked = isCleaning
                        }
                        "102" -> {//假日通风
                            val isVentilating = parseObject[it] as Boolean
                            ventilateSwitch.isChecked = isVentilating
                        }
                        "103" -> {//通风时长
                            ventilateTimeView.text =
                                String.format("${parseObject[it].toString()}min")
                        }
                        "104" -> {//巡航
                            val isCruising = parseObject[it] as Boolean
                            cruiseSwitch.isChecked = isCruising
                        }
                        "105" -> {//延时关机倒计时
                            delayTimeView.text =
                                if (isDeviceWorking && delayTurnOffSwitch.isChecked) {
                                    String.format("${parseObject[it].toString()}s")
                                } else {
                                    "0s"
                                }
                        }
                        "106" -> {//烟灶联动
                            val isLinkage = parseObject[it] as Boolean
                            linkageView.text = if (isLinkage) {
                                "开"
                            } else {
                                "关"
                            }
                        }
                        "107" -> {//倒油提醒
                            val isPourOil = parseObject[it] as Boolean
                            pourOilView.text = if (isPourOil) {
                                "开"
                            } else {
                                "关"
                            }
                        }
                        "108" -> {//防倒灌
                            val isAntiPourDown = parseObject[it] as Boolean
                            antiPourDownSwitch.isChecked = isAntiPourDown
                        }
                    }
                }
            }

            /**
             * 设备移除回调
             *
             * @param devId 设备id
             */
            override fun onRemoved(devId: String?) {

            }

            /**
             * 设备上下线回调。如果设备断电或断网，服务端将会在3分钟后回调到此方法。
             *
             * @param devId  设备 ID
             * @param online 是否在线，在线为 true
             */
            override fun onStatusChanged(devId: String?, online: Boolean) {

            }

            /**
             * 网络状态发生变动时的回调
             *
             * @param devId  设备 ID
             *  @param status 网络状态是否可用，可用为 true
             */
            override fun onNetworkStatusChanged(devId: String?, status: Boolean) {

            }

            /**
             * 设备信息更新回调
             *
             * @param devId  设备 ID
             */
            override fun onDevInfoUpdate(devId: String?) {

            }
        })
    }

    private fun configFunctionPanel(
        isTurnOn: Boolean,
        isSpeedEnable: Boolean,
        isCleanEnable: Boolean,
        isLightEnable: Boolean,
        isCruiseEnable: Boolean,
        isDelayEnable: Boolean,
        isVentilateEnable: Boolean,
        isVentilateTimeEnable: Boolean,
        isAntiPourDownEnable: Boolean
    ) {
//        if (isTurnOn) {
//            switchButtonLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            switchButtonLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isSpeedEnable) {
//            speedLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            speedLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isCleanEnable) {
//            cleanLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            cleanLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isLightEnable) {
//            lightLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            lightLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isCruiseEnable) {
//            cruiseLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)//巡航
//        } else {
//            cruiseLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)//巡航
//        }
//        if (isDelayEnable) {
//            delayLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            delayLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isVentilateEnable) {
//            ventilateLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)//通风
//        } else {
//            ventilateLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)//通风
//        }
//        if (isVentilateTimeEnable) {
//            ventilateTimeLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)
//        } else {
//            ventilateTimeLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)
//        }
//        if (isAntiPourDownEnable) {
//            antiPourDownLayout.setBackgroundResource(R.drawable.bg_solid_layout_white_radius_10)//防倒灌
//        } else {
//            antiPourDownLayout.setBackgroundResource(R.drawable.bg_solid_layout_hint_radius_10)//防倒灌
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceInstance.unRegisterDevListener()
        deviceInstance.onDestroy()
    }
}