package com.zj365.health.act

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.get
import androidx.core.view.isVisible
import com.alibaba.android.arouter.facade.annotation.Route
import com.tamsiree.rxkit.RxKeyboardTool
import com.xty.base.act.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.util.ChineseNumberAndNumberUtils
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.PointLengthFilter
import com.zj365.health.R
import com.zj365.health.databinding.ActUricCalibrationSubmitBinding
import com.zj365.health.model.UricCalibrationBean
import com.zj365.health.vm.UricAcidVm


/**
 * 尿酸校准提交
 */
@Route(path = ARouterUrl.URIC_CALIBRATION_SUBMIT)
class UricCalibrationSubmitAct : BaseVmAct<UricAcidVm>() {

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

    private var userId: String = ""
    private val MAX_LENGTH = 10
    private val timSelect by lazy {
        TimeSelect(this) {
        }.apply {
            showHour = true
            showMin = true
            showSec = false
        }
    }

    override fun initData() {
        super.initData()
        addChildViews()

        userId = intent.getStringExtra("userId").toString()
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = "尿酸校准"
        binding.title.mIvBack.setOnClickListener { finish() }

        binding.mAdd.setOnClickListener {
            addChildViews()
        }

        binding.mSubmit.isSelected = true
        binding.mSubmit.setOnClickListener {
            val bloods: MutableList<UricCalibrationBean> =
                getBloodLipidAdjustData() ?: return@setOnClickListener
            mViewModel.submitUricCalibrationRequest(bloods, userId)
        }

        //尿酸校准记录
        binding.jiaozhijilu.setOnClickListener {
            bundle.clear()
            bundle.putString("userId", userId)
            RouteManager.goAct(ARouterUrl.URIC_CALIBRATION_HISTORY, bundle)
        }

        //尿酸校准须知
        binding.mTip.setOnClickListener {
            val webUrl = ""
            bundle.clear()
            bundle.putString("title", "尿酸校准须知")
            bundle.putString("url", webUrl)
            RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
        }
    }

    @SuppressLint("SetTextI18n", "InflateParams", "MissingInflatedId")
    private fun addChildViews() {
        val viewIndex = binding.childLayout.childCount
        val viewNum = viewIndex + 1
        if (viewNum > MAX_LENGTH) {
            CommonToastUtils.showToast("尿酸校准最多添加" + MAX_LENGTH + "条")
            return
        }
        val childView = LayoutInflater.from(this).inflate(
            R.layout.item_uric_calibration_submit,
            null
        )
        childView.findViewById<TextView>(R.id.mTitle).text = "第${
            ChineseNumberAndNumberUtils.intToChinese(viewNum)
        }次"
        childView.findViewById<EditText>(R.id.edUricValue).filters = arrayOf(
            PointLengthFilter(2)
        )
        val mTvTimeView = childView.findViewById<TextView>(R.id.mVTimeView)
        mTvTimeView.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timSelect.selectTime(it, "yyyy-MM-dd HH:mm")
        }
        childView.setPadding(0, 0, 0, dp2px(0))

        binding.childLayout.addView(
            childView
        )
    }

    private fun getBloodLipidAdjustData(): MutableList<UricCalibrationBean>? {
        val list: MutableList<UricCalibrationBean> = mutableListOf()
        for (i in 0 until binding.childLayout.childCount) {
            val uricCalibrationBean = UricCalibrationBean()
            uricCalibrationBean.bpTime =
                (getChildView(i, R.id.mVTimeView) as TextView).text.toString()
            uricCalibrationBean.uaValue =
                (getChildView(i, R.id.edUricValue) as TextView).text.toString()

            if (uricCalibrationBean.bpTime.isNullOrEmpty()) {
                CommonToastUtils.showToast("请选择测量时间")
                return null
            }

            if (uricCalibrationBean.uaValue.isNullOrEmpty()) {
                CommonToastUtils.showToast("请填写测量值")
                return null
            }

            uricCalibrationBean.bpTime = "${uricCalibrationBean.bpTime}:00"
            list.add(uricCalibrationBean)
        }
        return list
    }

    private fun getChildView(index: Int, childId: Int = 0): View {
        return if (childId == 0) binding.childLayout[index]
        else binding.childLayout[index].findViewById(childId)
    }

    override fun liveObserver() {
        mViewModel.submitUricCalibrationLive.observe(this) {
            if (it.code == 0) {
                CommonToastUtils.showSucceedToast("提交成功")
                bundle.clear()
                bundle.putString("userId", userId)
                RouteManager.goAct(ARouterUrl.URIC_CALIBRATION_HISTORY, bundle)
                finish()
            } else {
                CommonToastUtils.showToast("提交失败：${it.msg}")
            }
        }
    }
}