package com.zj365.health.act.datamanage

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.xty.base.fragment.BaseFragList
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.FragDatamanagerTijianBinding
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

/**
 * 体检上传--列表页面
 */
class DataManageTijianFrag : BaseFragList<HealthRecordVm>(), View.OnClickListener {

    val binding by lazy { FragDatamanagerTijianBinding.inflate(layoutInflater) }
    val mAdapter by lazy { DataManageTijianAdapter() }
    val monitor by lazy{EditTextMonitor()}
    var isChange = false
    override fun setLayout() = binding.root

    var result = mutableListOf<String>()
    override fun initView() {
        super.initView()
        initAdapter()
        mViewModel.getHealthDataList(page, "6")

        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.etDesc.addTextChangedListener(object : TextWatcher {
//            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//            }
//
//            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//            }
//
//            override fun afterTextChanged(s: Editable?) {
//               refresh()
//            }
//        })

        binding.mRefresh.setOnLoadMoreListener {
              loadMore()
        }

        monitor.setEditTexts(binding.etDesc)
        monitor.startMonitor()
        monitor.setEditTextListener(object : EditTextMonitor.OnEditTextMonitor{
            override fun monitor(editText: EditText?) {
                refresh()
            }
        })
    }


    var year = ""
    var month = ""
    var isUpload = true

    private val timSelect by lazy {
        TimeSelect(requireContext()) {
            val toString = binding.tvAll.text.toString()
            toString.let {
                val split = it.split("-")
                year = split[0]
                month = split[1]
            }
            mViewModel.getHealthDataList(1, "6", 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(activity)
        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))
                RouteManager.goAct(ARouterUrl.DATAMANAGE_DETAIL_ACT, bundle)
            }
        }
    }

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

        mViewModel.getHealthDataList(
            page,
            "6",
            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

    private fun changeButtonStatus(canChange: Boolean) {
        val dataManageTypeAct = requireActivity() as HealthRecordAct
        dataManageTypeAct.binding.tvChange.isEnabled = canChange
    }

    var isManage = false
    fun toManage(isManager: Boolean) {
        isManage = isManager
        mAdapter.isSelect = isManager
        mAdapter.notifyDataSetChanged()
        if (isManager) {
            activity?.let {
                val dataManageTypeAct = it as HealthRecordAct
                dataManageTypeAct.binding.title.mTvRight.visibility = View.VISIBLE
            }
            changeButtonStatus(mAdapter.getSelectData().size == 1)
            isEdit = true
        } else {
            activity?.let {
                val dataManageTypeAct = it as HealthRecordAct
                dataManageTypeAct.binding.title.mTvRight.visibility = View.GONE
                dataManageTypeAct.exitManage(false)
            }
            mAdapter.reset()
            isEdit = false
        }
    }

    var order: CancerGoodsBean? = null
    var status: Int? = null
    private var filePath: String? = null
    override fun initData() {
        super.initData()
        var result = arguments?.getString("order")
        result?.let {
            order = GsonUtils.fromJson(it, CancerGoodsBean::class.java)
        }
    }

    fun newInstance(): DataManageTijianFrag {

        val fragment = DataManageTijianFrag()
        var bundle = Bundle()
        fragment.arguments = bundle
        return fragment
    }


    override fun setViewModel() = HealthRecordVm()
    override fun observer() {
        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) {
            refresh()
            val dataManageTypeAct = requireActivity() as HealthRecordAct
            dataManageTypeAct.tijianExitManage()
        }
//        mViewModel.editOb.observe(this) {
//            page=1
//           refresh()
//        }
    }

    fun exitManage() {
        toManage(false)
    }

    fun alterData() {
        val selectData = mAdapter.getSelectData()
        if (selectData.isEmpty()) {
            return
        }
        val dataValue = selectData.get(0)
        bundle.clear()
        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
        }
        mViewModel.deleteMedical(mAdapter.getSelectData())
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivTestDate, R.id.tvTestDate -> {
                page = 1
                mViewModel.getHealthDataList(
                    page,
                    "6",
                    "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",
                    "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()
    }
}