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

import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.casic.br.R
import com.casic.br.extensions.createCommand
import com.casic.br.model.LineChartEntryModel
import com.casic.br.utils.ChartViewHelper
import com.casic.br.utils.CommandManager
import com.casic.br.utils.LocaleConstant
import com.casic.br.utils.TuyaDeviceListener
import com.github.mikephil.charting.data.Entry
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.tuya.smart.home.sdk.TuyaHomeSdk
import com.tuya.smart.sdk.api.ITuyaDevice
import kotlinx.android.synthetic.main.activity_gas_consume.*
import kotlinx.android.synthetic.main.include_base_title.*
import java.util.*

/**
 * TODO 后面需要改成从后台获取数据
 * */
class GasConsumeActivity : KotlinBaseActivity() {

    private val kTag = "GasConsumeActivity"
    private lateinit var deviceId: String
    private lateinit var deviceInstance: ITuyaDevice
    private lateinit var calendar: Calendar

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

    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() {
        calendar = Calendar.getInstance()
        //默认选中
        dateRadioGroup.check(R.id.monthRadioButton)
        setLineChartData()

        setDate(
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH) + 1,
            calendar.get(Calendar.DATE)
        )

        deviceId = intent.getStringExtra(Constant.INTENT_PARAM)!!
        deviceInstance = TuyaHomeSdk.newDeviceInstance(deviceId)
        CommandManager.getTuyaDp(deviceInstance, "105")
        CommandManager.getTuyaDp(deviceInstance, "106")
        CommandManager.getTuyaDp(deviceInstance, "103")
        CommandManager.getTuyaDp(deviceInstance, "104")
        deviceInstance.registerDevListener(object : TuyaDeviceListener() {
            override fun onDpUpdate(devId: String?, dpStr: String?) {
                Log.d(kTag, "onDpUpdate: $dpStr")
                val parseObject = JSONObject.parseObject(dpStr)
                parseObject.keys.forEach {
                    //TODO 需要把单次的数据存到后台
                    when (it) {
                        "105" -> onceWaterUsedView.text =
                            String.format("${parseObject[it] as Int}L")
                        "106" -> totalUsedWaterView.text =
                            String.format("${parseObject[it] as Int}t")
                        "103" -> onceGasUsedView.text =
                            String.format("${parseObject[it] as Int}${resources.getString(R.string.volume_unit)}")
                        "104" -> totalGasUsedView.text =
                            String.format("${parseObject[it] as Int}${resources.getString(R.string.volume_unit)}")
                    }
                }
            }
        })
    }

    override fun initEvent() {
        dateRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.dayRadioButton -> {

                }
                R.id.monthRadioButton -> {

                }
                R.id.yearRadioButton -> {

                }
            }
            setLineChartData()
        }

        lastDateView.setOnClickListener {
            val currentYear = calendar.get(Calendar.YEAR)
            val currentMonth = calendar.get(Calendar.MONTH) + 1
            val currentDay = calendar.get(Calendar.DATE)
            when {
                dayRadioButton.isChecked -> {
                    //日 减一天
                    calendar.add(Calendar.DATE, -1)
                    setDate(currentYear, currentMonth, calendar.get(Calendar.DATE))
                }
                monthRadioButton.isChecked -> {
                    //月 减一月
                    calendar.add(Calendar.MONTH, -1)
                    setDate(currentYear, calendar.get(Calendar.MONTH) + 1, currentDay)
                }
                else -> {
                    //年 减一年
                    calendar.add(Calendar.YEAR, -1)
                    setDate(calendar.get(Calendar.YEAR), currentMonth, currentDay)
                }
            }
        }

        nextDateView.setOnClickListener {
            val currentYear = calendar.get(Calendar.YEAR)
            val currentMonth = calendar.get(Calendar.MONTH) + 1
            val currentDay = calendar.get(Calendar.DATE)
            when {
                dayRadioButton.isChecked -> {
                    //日 加一天
                    calendar.add(Calendar.DATE, 1)
                    setDate(currentYear, currentMonth, calendar.get(Calendar.DATE))
                }
                monthRadioButton.isChecked -> {
                    //月 加一月
                    calendar.add(Calendar.MONTH, 1)
                    setDate(currentYear, calendar.get(Calendar.MONTH) + 1, currentDay)
                }
                else -> {
                    //年 加一年
                    calendar.add(Calendar.YEAR, 1)
                    setDate(calendar.get(Calendar.YEAR), currentMonth, currentDay)
                }
            }
        }

        clearTotalWaterCheckBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                CommandManager.sendTuyaDp(deviceInstance, "107".createCommand(true))
            }
        }

        clearTotalGasCheckBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                CommandManager.sendTuyaDp(deviceInstance, "108".createCommand(true))
            }
        }
    }

    private fun setDate(year: Int, month: Int, day: Int) {
        when {
            dayRadioButton.isChecked -> dateView.text = String.format("$year-$month-${day}")
            monthRadioButton.isChecked -> dateView.text = String.format("$year-$month")
            else -> dateView.text = year.toString()
        }
    }

    /**
     * 设置折线统计数据
     * */
    private fun setLineChartData() {
        val xAxisLabel: MutableList<String> = ArrayList()
        val entryModels: MutableList<LineChartEntryModel> = ArrayList()
        val array = arrayListOf("用气量", "用水量")
        for (i in 0 until 2) {
            //每个entries都是一条折线
            val entries: ArrayList<Entry> = ArrayList()
            val entryModel = LineChartEntryModel()
            for (j in 1..31) {
                entryModel.lineColor = LocaleConstant.COLORS[i + 2].convertColor(this)

                xAxisLabel.add(j.toString())

                entries.add(
                    Entry(j.toFloat(), Random().nextFloat() * 10, array[i])
                )
            }
            entryModel.entryList = entries
            entryModels.add(entryModel)
        }
        ChartViewHelper.setLineChartData(dataLineChart, xAxisLabel, entryModels)
    }

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