package com.zj365.health.act.datamanage

import android.text.TextUtils
import android.view.View
import android.widget.ImageView
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.event.TZhongDataManageEvent
import com.xty.common.recycleUtils.RecycleItem
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.databinding.ActDataManageBaseBinding
import com.zj365.health.vm.DataManageVm
import com.zj365.health.weight.AddDataDialog
import com.xty.network.model.ExceptionBean
import org.greenrobot.eventbus.EventBus

/**
 *  异常数据
 */
@Route(path = ARouterUrl.DATAMANAGE_TYPE_ACT)
class DataManageTypeAct : BaseListAct<DataManageVm>() {

    val binding by lazy { ActDataManageBaseBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    var year = ""
    var month = ""
    private var userId = ""
    private var isUpload = true
    var isEdit = false
    var list: ArrayList<String>? = null
    var result = mutableListOf<ExceptionBean>()
    private var dataTyperesult: String? = ""
    var isManage = false

    val adapter by lazy { DataManageShowAdapter() }

    val timSelect by lazy {
        TimeSelect(this) {
            val toString = binding.tvAll.text.toString()
            toString.let {
                val split = it.split("-")
                year = split[0]
                month = split[1]
            }
            page = 1
            mViewModel.getDataList(userId, dataTyperesult, if (isUpload) "1" else "2", page, year, month)
        }.apply {
            chooseMany = false
            showYear = true
            showMonth = true
            showDay = false
            showHour = false
            showMin = false
            showSec = false
        }
    }

    val tipDialog by lazy {
        AddDataDialog(
            this,
            dataTyperesult,
            { id, date, dataVlue, tcStr, tgStr, hdlStr, ldlStr, height ->
                if (id.isNotEmpty() && isEdit) {
                    mViewModel.editData(
                        id,
                        dataTyperesult,
                        date,
                        dataVlue,
                        tcStr,
                        tgStr,
                        hdlStr,
                        ldlStr,
                        height
                    )
                } else {
                    mViewModel.addData(
                        userId,
                        dataTyperesult,
                        date,
                        dataVlue,
                        tcStr,
                        tgStr,
                        hdlStr,
                        ldlStr,
                        height
                    )
                }
            },
            {height ->  }
        )
    }

    companion object {
        var exceptionKey: String = "exception_title"
        var dataType: String = "data_type"
    }

    override fun initData() {
        super.initData()
        val stringExtra = intent.getStringExtra(exceptionKey)
        dataTyperesult = intent.getStringExtra(dataType)
        userId = intent.getStringExtra("userId").toString()
        binding.title.mTvTitle.text = stringExtra
    }

    override fun initAdapter() {
        adapter.addChildClickViewIds(
            com.zj365.health.R.id.root,
        )
        adapter.setOnItemChildClickListener { _, view, position ->
            val healthDataBean = adapter.data[position]
                if (isManage) {
                    val findViewById = view.findViewById<ImageView>(R.id.ivSelected)
                    findViewById.isSelected = !findViewById.isSelected
                        healthDataBean.isSelected = findViewById.isSelected
                }
                changeButtonStatus(adapter.getSelectData().size == 1)
        }
    }

    private fun changeButtonStatus(canChange: Boolean) {
        binding.tvChange.isEnabled = canChange && adapter.getSelectData()[0].upType !=3
    }

    override fun loadData() {
        mViewModel.getDataList(userId, dataTyperesult, if (isUpload) "1" else "2", page, year, month)
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)

        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }
        initRecycle()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
//        binding.title.mTvTitle.text = "数据管理"
        binding.mAddData.setOnClickListener {
            tipDialog.clear(dataTyperesult!!.toInt())
            tipDialog.show()
        }

        binding.tvUploadDate.setOnClickListener {
            page = 1
            mViewModel.getDataList(userId, dataTyperesult, "1", page, year, month)
            binding.ivUpload.setImageResource(R.mipmap.paixu_2)
            binding.ivTestDate.setImageResource(R.mipmap.paixu)
            isUpload = true
        }
        binding.tvTestDate.setOnClickListener {
            page = 1
            mViewModel.getDataList(userId, dataTyperesult, "2", page, year, month)
            binding.ivUpload.setImageResource(R.mipmap.paixu)
            binding.ivTestDate.setImageResource(R.mipmap.paixu_2)
            isUpload = false

        }
        binding.tvAll.setOnClickListener {
            timSelect.selectTimeWithYearMonth(it, "yyyy-MM")
        }

        binding.mTvManage.setOnClickListener {
            toManage(!isManage)
        }
        binding.mDelete.setOnClickListener {
            val selectData = adapter.getSelectData()
            if (selectData.isEmpty()) {
                CommonToastUtils.showToast("未勾选数据")
                return@setOnClickListener
            }
            deleteDialog.show()
        }
        binding.title.mTvRight.apply {
            text = "退出管理"
            setTextColor(resources.getColor(R.color.col_02c))
            setOnClickListener {

                toManage(false)
            }
        }
        binding.tvChange.setOnClickListener {
            isEdit = true
            val selectData = adapter.getSelectData()

            if (selectData.size == 0) {
                return@setOnClickListener
            }
            val dataValue = selectData[0]
            tipDialog.showWithData(
                dataValue.id!!,
                if (TextUtils.isEmpty(dataValue.time!!)) "" else dataValue.time!!,
                if (TextUtils.isEmpty(dataValue.dataValue!!)) "" else dataValue.dataValue!!,
                "",
                "",
                "",
                "",
                "",
                dialogType = dataTyperesult!!.toInt()
            )
        }
    }

    override fun deleteData() {
        mViewModel.delete(adapter.getSelectData())
    }

    fun toManage(isManager: Boolean) {
        isManage = isManager
        adapter.isSelect = isManager
        adapter.notifyDataSetChanged()
        if (isManager) {
            binding.mTvManage.visibility = View.GONE
            binding.mDelete.visibility = View.VISIBLE
            binding.mAddData.visibility = View.GONE
            binding.tvChange.visibility = View.VISIBLE
            binding.title.mTvRight.visibility = View.VISIBLE
            changeButtonStatus(adapter.getSelectData().size == 1)
            isEdit = true
        } else {
            binding.mTvManage.visibility = View.VISIBLE
            binding.mDelete.visibility = View.GONE
            binding.mAddData.visibility = View.VISIBLE
            binding.tvChange.visibility = View.GONE
            binding.title.mTvRight.visibility = View.GONE
            adapter.reset()
            isEdit = false
        }
    }

    fun initRecycle() {
        setRecycleRefresh(binding.mRecycle, binding.mRefresh, true)
        binding.mRecycle.addItemDecoration(RecycleItem(this, 30))
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = adapter
    }

    override fun liveObserver() {
        mViewModel.deleteOb.observe(this){
            CommonToastUtils.showSucceedToast("删除成功")
            page = 1
            loadData()
            toManage(false)
        }

        mViewModel.getDataListOb.observe(this) {
            setDate(adapter, it.data.records)
//            adapter.addData(it.data.records)
            binding.tvNumAll.text = "共${adapter.data.size}条"
        }

        mViewModel.addDataOb.observe(this) {
            page = 1
            loadData()
            toManage(false)
        }
        mViewModel.editOb.observe(this) {
            page = 1
            loadData()
            toManage(false)
        }
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().post(TZhongDataManageEvent())
    }
}