package com.zj365.health.act.datamanage

import android.view.View
import android.widget.EditText
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.xty.common.util.EditTextMonitor
import com.zj365.health.R
import com.zj365.health.adapter.DataManageTijianAdapter
import com.zj365.health.databinding.ActDatamanagerTijianBinding
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_TIJIAN)
class DataManageTijianAct : BaseListAct<HealthRecordVm>(), View.OnClickListener {

    val binding by lazy { ActDatamanagerTijianBinding.inflate(layoutInflater) }
    val mAdapter by lazy { DataManageTijianAdapter() }
    val monitor by lazy { EditTextMonitor() }
    var isChange = false
    var userId:String? = null
    override fun setLayout() = binding.root

    var result = mutableListOf<String>()

    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 {
                toManage(false)
            }
        }

        binding.mAddData.text = "上传体检记录"
        initAdapter()
        mViewModel.getHealthDataList(page, "6",userId)

        binding.ivUpload.setOnClickListener(this)
        binding.tvUploadDate.setOnClickListener(this)

        binding.ivTestDate.setOnClickListener(this)
        binding.tvTestDate.setOnClickListener(this)

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

        binding.mRefresh.setOnLoadMoreListener {
            loadMore()
        }

        monitor.setEditTexts(binding.etDesc)
        monitor.startMonitor()
        monitor.setEditTextListener(object : EditTextMonitor.OnEditTextMonitor {
            override fun monitor(editText: EditText?) {
                refresh()
            }
        })
        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", "6")
            bundle.putString("userId",userId)
            RouteManager.goAct(ARouterUrl.UPLOAD_Medical, bundle)
        }
    }


    var year = ""
    var month = ""
    var isUpload = true
    private fun changeButtonStatus(canChange: Boolean) {
        binding.tvChange.isEnabled = canChange
    }

    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]
            }
            mViewModel.getHealthDataList(1, "6", userId,if (isUpload) "1" else "2", "", year, month)
        }.apply {
            chooseMany = false
            showYear = true
            showMonth = true
            showDay = false
            showHour = false
            showMin = false
            showSec = false
        }
    }

    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("type","6")
                bundle.putString("data", GsonUtils.toJson(healthDataBean))
                RouteManager.goAct(ARouterUrl.DATAMANAGE_DETAIL_ACT, bundle)
            }
        }
    }

    override fun loadData() {
        refresh()
    }

    override fun liveObserver() {

        mViewModel.getHealthData.observe(this) {
            setDate(mAdapter, it.data.records)
            binding.tvNumAll.text = "共${mAdapter.data.size}条"
            isEnableLoadMore(it.data)

            //添加数据后滚动到第一条
            if (isChange) {
                binding.mRecycle.scrollToPosition(0)
                isChange = false
            }
        }

        mViewModel.deleteData.observe(this) {
            CommonToastUtils.showSucceedToast("删除成功")
            refresh()
//            val dataManageTypeAct = requireActivity() as HealthRecordAct
//            dataManageTypeAct.tijianExitManage()
        }
    }

    fun refresh() {
        page = 1
        if (isManage) {
            toManage(false)
        }
        mViewModel.getHealthDataList(
            page,
            "6",
            userId,
            if (isUpload) "1" else "2",
            binding.etDesc.text.toString(),
            year,
            month
        )
    }

    private fun loadMore() {
        page++
        if (isManage) {
            toManage(false)
        }

        mViewModel.getHealthDataList(
            page,
            "6",
            userId,
            if (isUpload) "1" else "2",
            binding.etDesc.text.toString(),
            year,
            month
        )
    }

    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

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

    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 alterData() {
        val selectData = mAdapter.getSelectData()
        if (selectData.isEmpty()) {
            return
        }
        val dataValue = selectData.get(0)
        bundle.clear()
        bundle.putString("type", "6")
        bundle.putString("data", GsonUtils.toJson(dataValue))
        RouteManager.goAct(ARouterUrl.UPLOAD_Medical_EDIT, bundle)
    }

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

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivTestDate, R.id.tvTestDate -> {
                page = 1
                mViewModel.getHealthDataList(
                    page,
                    "6",
                    userId,
                    "2",
                    binding.etDesc.text.toString(),
                    year,
                    month
                )
                binding.ivUpload.setImageResource(R.mipmap.paixu)
                binding.ivTestDate.setImageResource(R.mipmap.paixu_2)
                isUpload = false
            }

            R.id.ivUpload, R.id.tvUploadDate -> {
                page = 1
                mViewModel.getHealthDataList(
                    page,
                    "6",
                    userId,
                    "1",
                    binding.etDesc.text.toString(),
                    year,
                    month
                )
                binding.ivUpload.setImageResource(R.mipmap.paixu_2)
                binding.ivTestDate.setImageResource(R.mipmap.paixu)
                isUpload = true
            }
        }
    }

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