package com.zj365.health.act.binddevice

import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseListAct
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.MeasureWeightEvent
import com.xty.common.event.TZhongDataManageEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.adapter.binddevice.BodyFatBindDeviceHistoryAdapter
import com.zj365.health.databinding.ActBodyFatHistoryBinding
import com.zj365.health.vm.HistoryDeviceVm
import com.xty.network.model.BodyFatHistoryBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.StringBuilder

@Route(path = ARouterUrl.BODY_FAT_BIND_HISTORY)
class BodyFatDeviceHistoryAct : BaseListAct<HistoryDeviceVm>() {

    val binding by lazy { ActBodyFatHistoryBinding.inflate(layoutInflater) }
    val mAdapter by lazy { BodyFatBindDeviceHistoryAdapter() }
    var year: String = ""
    var month: String = ""
    var userID: String? = null
    var isManage: Boolean = true

    var mDeleteData = mutableListOf<BodyFatHistoryBean>()

    val timeSelect by lazy {
        TimeSelect(this) {
            val toString = binding.tvSelectTime.text.toString()
            toString.let {
                val split = it.split("-")
                year = split[0]
                month = split[1]
            }
            loadData()
        }
    }

    override fun liveObserver() {
        mViewModel.bodyFatData.observe(this) {
            setDate(mAdapter, it.data.records)
            binding.tvNumAll.text = "共${mAdapter.data.size}条"
            if (mAdapter.data.isEmpty()){
                binding.llBottom.visibility = View.GONE
            }else{
                binding.llBottom.visibility = View.VISIBLE
            }
        }

        mViewModel.deleteSuccess.observe(this) {
            CommonToastUtils.showSucceedToast("删除成功")
            mAdapter.data.removeAll(mDeleteData)
            mAdapter.notifyDataSetChanged()
            EventBus.getDefault().post(TZhongDataManageEvent(""))

            mDeleteData.clear()
            if (mAdapter.data.isEmpty()) {
                binding.mTvManage.text = "管理"
                binding.mTvManage.setBackgroundResource(R.drawable.selector_change)
                binding.mTvManage.setTextColor(ContextCompat.getColor(this@BodyFatDeviceHistoryAct,R.color.white))

                binding.llBottom.visibility = View.GONE
                mAdapter.isSelect = false
                isManage = true
                binding.mDelete.visibility = View.GONE
                loadData()
            }else{
                binding.llBottom.visibility = View.VISIBLE
            }
        }
    }


    override fun initData() {
        super.initData()
        userID = intent.getStringExtra("userId")
        if (userID.isNullOrEmpty()) {
            userID = CommonUtils.getMyUserId()
        }
    }

    override fun setLayout(): View = binding.root

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "体脂历史数据"
        binding.title.mIvBack.setOnClickListener { finish() }

        binding.tvSelectTime.setOnClickListener {
            timeSelect.selectTimeWithYearMonth(it, "yyyy-MM")
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bodyData = adapter.data[position] as BodyFatHistoryBean
            if (isManage) {
                bundle.clear()
                bundle.putSerializable("bodyData", bodyData)
                RouteManager.goAct(ARouterUrl.BODY_FAT_DETAIL, bundle)
            } else {
                bodyData.isSelect = !bodyData.isSelect
                mAdapter.notifyItemChanged(position)
                if (bodyData.isSelect) {
                    mDeleteData.add(bodyData)
                } else {
                    mDeleteData.remove(bodyData)
                }
            }
        }

        binding.mTvManage.setOnClickListener {
            isManage = !isManage
            if (isManage) { //退出管理
                binding.mTvManage.text = "管理"
                mAdapter.isSelect = false
                binding.mTvManage.setBackgroundResource(R.drawable.selector_change)
                binding.mTvManage.setTextColor(ContextCompat.getColor(this@BodyFatDeviceHistoryAct,R.color.white))

                binding.mDelete.visibility = View.GONE

                if (mDeleteData.isNotEmpty()) {
                    mDeleteData.clear()
                }
            } else {  //管理
                binding.mTvManage.text = "退出管理"
                binding.mTvManage.setBackgroundResource(R.drawable.shape_gray_click)
                binding.mTvManage.setTextColor(ContextCompat.getColor(this@BodyFatDeviceHistoryAct,R.color.col_02c))

                mAdapter.isSelect = true
                binding.mDelete.visibility = View.VISIBLE

            }
            mAdapter.notifyDataSetChanged()
        }

        binding.mDelete.setOnClickListener {
            if (mDeleteData.isEmpty()) {
                CommonToastUtils.showLoserToast("请勾选数据")
                return@setOnClickListener
            }

          deleteDialog.show()
        }
    }

    override fun deleteData() {
        super.deleteData()
        val sb = StringBuilder()
        mDeleteData.forEach {
            sb.append("${it.id},")
        }
        mViewModel.deleteBodyFatDatas(sb.toString())
    }

    override fun initAdapter() {

        setRecycleRefresh(binding.mRecycle, binding.mRefresh, true)
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = mAdapter

    }

    override fun loadData() {
        mViewModel.getBodyFatHistory(userID, year, month, page)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun reveiveMsg(event: MeasureWeightEvent) {
        CommonToastUtils.showToast("测量成功")
        mViewModel.getBodyFatHistory(userID, year, month, 1)
    }
}