package com.zj365.health.act.datamanage

import android.annotation.SuppressLint
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.arouter.RouteManager
import com.xty.common.event.TZhongDataManageEvent
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.databinding.ActTzhongDataManageTypeBinding
import com.zj365.health.vm.DataManageVm
import com.zj365.health.weight.AddDataDialog
import com.xty.network.model.ExceptionBean
import com.xty.network.model.HealthDataBean
import org.greenrobot.eventbus.EventBus

/**
 * 体重--数据管理列表页面
 */
@Route(path = ARouterUrl.DATAMANAGE_TZHONG_TYPE_ACT)
class TZhongDataManageTypeAct : BaseListAct<DataManageVm>() {

    private val binding by lazy { ActTzhongDataManageTypeBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

    private val adapter by lazy { TZhongDataManageListAdapter() }

    private var list: ArrayList<String>? = null
    private var result = mutableListOf<ExceptionBean>()
    private var dataTyperesult: String? = ""
    private var isManage = false
    private var heightStr = ""
    private var userId = ""

    val tipDialog by lazy {
        AddDataDialog(
            this,
            dataTyperesult,
            { id, date, dataVlue, tcStr, tgStr, hdlStr, ldlStr, height ->
                heightStr = 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 ->
                heightStr = height
            }
        )
    }
    var year = ""
    var month = ""
    var isUpload = true
    var isEdit = false
    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
        }
    }

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

    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!!,
                if (TextUtils.isEmpty(dataValue.tc)) "" else dataValue.tc,
                if (TextUtils.isEmpty(dataValue.tg)) "" else dataValue.tg,
                if (TextUtils.isEmpty(dataValue.hdl)) "" else dataValue.hdl,
                if (TextUtils.isEmpty(dataValue.ldl)) "" else dataValue.ldl,
                if (TextUtils.isEmpty(dataValue.height)) "" else dataValue.height,
                dialogType = dataTyperesult!!.toInt()
            )
        }
    }

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

    @SuppressLint("NotifyDataSetChanged")
    private 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
        }
    }

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

    override fun initAdapter() {

        adapter.setOnItemClickListener { _, view, position ->
            val healthDataBean = adapter.data[position] as HealthDataBean

            if (isManage) {
                val findViewById = view.findViewById<ImageView>(R.id.ivSelected)
                findViewById.isSelected = !findViewById.isSelected
                healthDataBean.isSelected = findViewById.isSelected
            }
            changeButtonStatus(adapter.getSelectData().size == 1)

            if (!isManage) {
                if (healthDataBean.upType == 3) {  //物联网上传
                    bundle.clear()
                    bundle.putString("pbfId", healthDataBean.pbfId)
                } else {
                    bundle.clear()
                    bundle.putSerializable("manageInfo", healthDataBean)
                }
                RouteManager.goAct(ARouterUrl.BODY_FAT_DETAIL, bundle)
            }
        }
    }

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

    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)

        }
    }

    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 onStop() {
        super.onStop()
        EventBus.getDefault().post(TZhongDataManageEvent(heightStr))
    }
}