package com.zj365.health.act.datamanage

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.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.ActDatamanagerUserMedicalBinding
import com.zj365.health.vm.HealthRecordVm
import com.xty.network.model.CancerGoodsBean
import com.xty.network.model.MedicalDataBean
import com.xty.network.model.PaingBean
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 健康档案--用药上传
 */
@Route(path = ARouterUrl.DATA_MANAGE_USE_MEDICAL)
class DataManageUseMedicalAct : BaseListAct<HealthRecordVm>() {
    //val binding by lazy{FragWholeRankBinding.inflate(layoutInflater)}
    val binding by lazy { ActDatamanagerUserMedicalBinding.inflate(layoutInflater) }
    val mAdapter by lazy { DataManageMedicalAdapter() }
    var isChange = false
    override fun setLayout() = binding.root

    var result = mutableListOf<String>()

    var userId: String? = null
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvTitle.text = "用药记录"
        binding.title.mTvRight.apply {
            text = "退出管理"
            setTextColor(resources.getColor(R.color.col_02c))
            setOnClickListener {
                exitManage()
            }
        }

        binding.mAddData.text = "上传用药记录"

        mViewModel.getHealthDataList(page, "7", userId)
        binding.mRefresh.setOnLoadMoreListener {
            loadMore()
        }
        initAdapter()

        binding.mTvManage.setOnClickListener {
            if (mAdapter.data.size > 0) {
                toManage(!isManage)
            } else {
                CommonToastUtils.showToast("暂无数据")
            }
        }
        binding.mDelete.setOnClickListener {
            delete()
        }

        binding.tvChange.setOnClickListener {
            alterData()
        }

        binding.mAddData.setOnClickListener {
            //上传图片
            bundle.clear()
            bundle.putString("type", "7")
            bundle.putString("userId", userId)
            RouteManager.goAct(ARouterUrl.UPLOAD_Medical, bundle)
        }
    }

    override fun initAdapter() {
        setRecycleRefresh(binding.mRecycle, binding.mRefresh, true)
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = mAdapter

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val healthDataBean = mAdapter.data.get(position) as MedicalDataBean
            if (isManage) {
                val findViewById = view.findViewById<ImageView>(com.zj365.health.R.id.ivSelected)
                findViewById.isSelected = !findViewById.isSelected
                healthDataBean.isSelectd = findViewById.isSelected
                val selectData = this.mAdapter.getSelectData()
                changeButtonStatus(selectData.size == 1)
            } else {
                bundle.clear()
                bundle.putString("data", GsonUtils.toJson(healthDataBean))
                bundle.putString("type", "7")
                RouteManager.goAct(ARouterUrl.DATAMANAGE_DETAIL_ACT, bundle)
            }
        }

    }

    override fun loadData() {
        refresh()
    }

    override fun liveObserver() {
        mViewModel.getHealthData.observe(this) {
            setDate(mAdapter, it.data.records)
            isEnableLoadMore(it.data)

            //添加数据后滚动到第一条
            if (isChange) {
                binding.mRecycle.scrollToPosition(0)
                isChange = false
            }
        }
        mViewModel.deleteData.observe(this) {
            CommonToastUtils.showSucceedToast("删除成功")
            refresh()
        }
    }

    fun refresh() {
        page = 1
        if (isManage) {
            toManage(false)
        }
        mViewModel.getHealthDataList(page, "7", userId)
    }

    private fun loadMore() {
        page++
        if (isManage) {
            toManage(false)
        }
        mViewModel.getHealthDataList(page, "7", userId)
    }

    private fun isEnableLoadMore(datas: PaingBean<MedicalDataBean>) {

        if (binding.mRefresh.isLoading) {
            binding.mRefresh.finishLoadMore()
        }

        if (mAdapter.data.size == datas.total) {
            binding.mRefresh.setEnableLoadMore(false)
        } else {
            binding.mRefresh.setEnableLoadMore(true)
        }
    }

    var isEdit = false
    private fun changeButtonStatus(canChange: Boolean) {
        binding.tvChange.isEnabled = canChange
    }

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

    fun alterData() {
        val selectData = mAdapter.getSelectData()
        if (selectData.isEmpty()) {
            return
        }
        val dataValue = selectData.get(0)
        bundle.clear()
        bundle.putString("type", "7")
        bundle.putString("data", GsonUtils.toJson(dataValue))
        RouteManager.goAct(ARouterUrl.UPLOAD_Medical_EDIT, bundle)
    }

    var order: CancerGoodsBean? = null
    var status: Int? = null
    private var filePath: String? = null

    override fun initData() {
        super.initData()
        userId = intent.getStringExtra("userId")
//        var result = arguments?.getString("order")
//        result?.let {
//            order = GsonUtils.fromJson(it, CancerGoodsBean::class.java)
//        }
    }

    fun delete() {
        val selectData = mAdapter.getSelectData()
        if (selectData.isEmpty()) {
            CommonToastUtils.showLoserToast("未勾选数据")
            return
        }
        deleteDialog.show()
    }

    override fun deleteData() {
        mViewModel.deleteMedical(mAdapter.getSelectData())
    }

    fun exitManage() {
        toManage(false)
    }

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