package com.zj365.health.act.datamanage

import android.annotation.SuppressLint
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.GsonUtils
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.HealthDataChangeEvent
import com.xty.common.util.CommonToastUtils
import com.zj365.health.R
import com.zj365.health.databinding.ActYshiDataManageListBinding
import com.zj365.health.vm.DataManageVm
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 饮食管理--列表页面
 */
@Route(path = ARouterUrl.DATAMANAGE_YSHI_LIST_ACT)
class YShiDataManageListAct : BaseListAct<DataManageVm>() {

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

    val adapter by lazy { YShiDataManageListAdapter() }

    private var isManage = false
    private var isEdit = false
    private var isUpload = true
    private var userId = ""
    private var year = ""
    private var month = ""

    private 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.getYShiDataList(userId, page, "8", year, month, isUpload)
        }.apply {
            chooseMany = false
            showYear = true
            showMonth = true
            showDay = false
            showHour = false
            showMin = false
            showSec = false
        }
    }

    override fun initData() {
        super.initData()
        userId = intent.getStringExtra("userId").toString()
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "饮食管理"
        binding.title.mIvBack.apply {
            this.setOnClickListener {
                finish()
            }
        }
        binding.title.mTvRight.apply {
            text = "退出管理"
            setTextColor(resources.getColor(R.color.col_02c))
            setOnClickListener {
                toManage(false)
            }
        }

        //用餐时间
        binding.tvTestDate.setOnClickListener {
            page = 1
            binding.ivUpload.setImageResource(R.mipmap.paixu)
            binding.ivTestDate.setImageResource(R.mipmap.paixu_2)
            isUpload = false
            loadData()
        }
        //上传日期
        binding.tvUploadDate.setOnClickListener {
            page = 1
            binding.ivUpload.setImageResource(R.mipmap.paixu_2)
            binding.ivTestDate.setImageResource(R.mipmap.paixu)
            isUpload = true
            loadData()
        }

        //管理按钮
        binding.mTvManage.setOnClickListener {
            toManage(!isManage)
        }
        //上传饮食
        binding.mAddData.setOnClickListener {
            bundle.clear()
            bundle.putString("userId", userId)
            RouteManager.goAct(ARouterUrl.DATAMANAGE_YSHI_UPLOADING_ACT, bundle)
        }
        //修改
        binding.tvChange.setOnClickListener {
            isEdit = true
            val selectData = adapter.getSelectData()
            if (selectData.size == 0) {
                CommonToastUtils.showToast("未勾选数据")
                return@setOnClickListener
            }
            val dataValue = selectData[0]
            bundle.clear()
            bundle.putString("data", GsonUtils.toJson(dataValue))
            RouteManager.goAct(ARouterUrl.DATAMANAGE_YSHI_UPLOADING_ACT,bundle)
        }
        //删除
        binding.mDelete.setOnClickListener {
            if (adapter.getSelectData().isEmpty()) {
                CommonToastUtils.showLoserToast("未勾选数据")
                return@setOnClickListener
            }
           deleteDialog.show()
        }
        //点击选择时间
        binding.tvAll.setOnClickListener {
            timSelect.selectTimeWithYearMonth(it, "yyyy-MM")
        }

        initRecycle()
    }

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

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

                R.id.root -> {
                    bundle.clear()
                    bundle.putString("data", GsonUtils.toJson(adapter.data[position]))
                    RouteManager.goAct(ARouterUrl.DATAMANAGE_YSHI_DETAILS_ACT, bundle)
                }
            }
        }
    }

    override fun loadData() {
        mViewModel.getYShiDataList(userId, page, "8", year, month, isUpload)
    }

    @SuppressLint("SetTextI18n")
    override fun liveObserver() {
        //列表返回方法
        mViewModel.getMedicalDataListOb.observe(this) {
            val records = it.data.records
            setDate(adapter, records)
            changeButtonStatus(adapter.getSelectData().size == 1)
            binding.tvNumAll.text = "共${it.data.total}条"
        }
        //删除返回方法
        mViewModel.addDataOb.observe(this) {
            page = 1
            CommonToastUtils.showSucceedToast("删除成功")
            loadData()
            toManage(false)
        }
    }

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

    @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
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun healthDataChange(event: HealthDataChangeEvent) {
        loadData()
    }
}