package com.rdiot.yx485.device

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.rdiot.yx485.BaseActivity
import com.rdiot.yx485.R
import com.rdiot.yx485.bean.HomeBase
import com.rdiot.yx485.databinding.ActivityConsumableBinding
import com.rdiot.yx485.home.HomeViewModel
import com.rdiot.yx485.main.MainViewModel
import com.rdiot.yx485.util.LocalCache
import com.rdiot.yx485.widget.CommonPopupWindow
import com.zcolin.frame.util.DisplayUtil

class ConsumableActivity : BaseActivity(), ConsumableActionListener {
    private lateinit var binding: ActivityConsumableBinding
    private lateinit var viewModel: ConsumableViewModel
    private lateinit var adapter: DeviceAdapter
    private lateinit var mMainViewModel: MainViewModel
    private lateinit var mHomeViewModel: HomeViewModel
    private var homeListPopupWindow: CommonPopupWindow? = null
    private var defaultHome: HomeBase? = null
    private val homeList = ArrayList<HomeBase>()

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

        initView()
        initObservers()
        loadData()
    }

    private fun initView() {
        binding.titleBar.tvTitle.text = getString(R.string.device_consumable)
        binding.titleBar.btnTitleLeft.setOnClickListener { finish() }

        LocalCache.getDefaultHome()?.let {
            defaultHome = it
            binding.tvHomeTitle.text = it.name
        }

        binding.tvHomeTitle.setOnClickListener { showHomeListWindow(binding.tvHomeTitle) }
        adapter = DeviceAdapter(this)
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter

        binding.swipeRefreshLayout.setOnRefreshListener {
            loadData()
        }
    }

    private fun initObservers() {
        mMainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
        mMainViewModel.errorMessage.observe(this) { showMessage(it) }
        mMainViewModel.homeDef.observe(this) {
            it?.let { home ->
                binding.tvHomeTitle.text = home.name
                defaultHome = HomeBase(home.record_id, home.name)
            }
        }
        mHomeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        mHomeViewModel.errorMessage.observe(this) { showMessage(it) }
        mHomeViewModel.homeList.observe(this) { list ->
            homeList.clear()
            list ?: return@observe
            if (list.isEmpty()) {
                return@observe
            }
            homeList.addAll(list.map { home -> HomeBase(home.record_id, home.name) }.toList())
        }
        mHomeViewModel.loadHomeList()

        viewModel = ViewModelProvider(this)[ConsumableViewModel::class.java]
        viewModel.errorMessage.observe(this) { error ->
            binding.swipeRefreshLayout.isRefreshing = false
            showMessage(error)
        }
        viewModel.consumable.observe(this) { it ->
            binding.swipeRefreshLayout.isRefreshing = false
            val devices = it.devices
            binding.tvDataEmpty.visibility = if (devices.isEmpty()) View.VISIBLE else View.GONE
            adapter.submitList(devices)

            binding.tvConsumableCount.text = String.format("%s(%s)", it.desc, devices.size)
            if (it.enough) {
                binding.tvConsumableCount.setTextColor(Color.GRAY)
            } else {
                binding.tvConsumableCount.setTextColor(Color.RED)
            }
        }

        viewModel.operationResult.observe(this) { success ->
            if (success) {
                showMessage(getString(R.string.operation_success))
                loadData()
            }
        }
    }

    private fun loadData() {
        binding.swipeRefreshLayout.isRefreshing = true
        viewModel.loadConsumableList(defaultHome?.id)
    }

    override fun onResetClick(consumableId: String) {
        viewModel.resetConsumable(consumableId)
    }

    fun showHomeListWindow(view: TextView?) {
        if (homeList.isEmpty()) {
            showMessage("当前家庭列表数据为空")
            return
        }

        if (homeListPopupWindow == null) {
            homeListPopupWindow = CommonPopupWindow(this)
            for (home in homeList) {
                homeListPopupWindow?.addMenuItem(home.name, View.OnClickListener { v1: View? ->
                    mMainViewModel.updateDefaultHome(home)
                    defaultHome = home
                    loadData()
                })
            }
        }
        homeListPopupWindow?.show(view, 0, DisplayUtil.dip2px(this, 8f))
    }

    override fun onDestroy() {
        if (homeListPopupWindow != null) {
            homeListPopupWindow?.dismiss()
            homeListPopupWindow = null
        }
        super.onDestroy()
    }
} 